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 // We might have constant size array now, but fortunately it has the same
3842 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
3843 NewTL.setLBracketLoc(TL.getLBracketLoc());
3844 NewTL.setRBracketLoc(TL.getRBracketLoc());
3845 NewTL.setSizeExpr(Size);
3850 template<typename Derived>
3852 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
3853 DependentSizedArrayTypeLoc TL) {
3854 const DependentSizedArrayType *T = TL.getTypePtr();
3855 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
3856 if (ElementType.isNull())
3859 // Array bounds are constant expressions.
3860 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3861 Sema::ConstantEvaluated);
3863 // Prefer the expression from the TypeLoc; the other may have been uniqued.
3864 Expr *origSize = TL.getSizeExpr();
3865 if (!origSize) origSize = T->getSizeExpr();
3867 ExprResult sizeResult
3868 = getDerived().TransformExpr(origSize);
3869 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
3870 if (sizeResult.isInvalid())
3873 Expr *size = sizeResult.get();
3875 QualType Result = TL.getType();
3876 if (getDerived().AlwaysRebuild() ||
3877 ElementType != T->getElementType() ||
3879 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
3880 T->getSizeModifier(),
3882 T->getIndexTypeCVRQualifiers(),
3883 TL.getBracketsRange());
3884 if (Result.isNull())
3888 // We might have any sort of array type now, but fortunately they
3889 // all have the same location layout.
3890 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
3891 NewTL.setLBracketLoc(TL.getLBracketLoc());
3892 NewTL.setRBracketLoc(TL.getRBracketLoc());
3893 NewTL.setSizeExpr(size);
3898 template<typename Derived>
3899 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
3900 TypeLocBuilder &TLB,
3901 DependentSizedExtVectorTypeLoc TL) {
3902 const DependentSizedExtVectorType *T = TL.getTypePtr();
3904 // FIXME: ext vector locs should be nested
3905 QualType ElementType = getDerived().TransformType(T->getElementType());
3906 if (ElementType.isNull())
3909 // Vector sizes are constant expressions.
3910 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3911 Sema::ConstantEvaluated);
3913 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
3914 Size = SemaRef.ActOnConstantExpression(Size);
3915 if (Size.isInvalid())
3918 QualType Result = TL.getType();
3919 if (getDerived().AlwaysRebuild() ||
3920 ElementType != T->getElementType() ||
3921 Size.get() != T->getSizeExpr()) {
3922 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
3924 T->getAttributeLoc());
3925 if (Result.isNull())
3929 // Result might be dependent or not.
3930 if (isa<DependentSizedExtVectorType>(Result)) {
3931 DependentSizedExtVectorTypeLoc NewTL
3932 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
3933 NewTL.setNameLoc(TL.getNameLoc());
3935 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
3936 NewTL.setNameLoc(TL.getNameLoc());
3942 template<typename Derived>
3943 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
3945 const VectorType *T = TL.getTypePtr();
3946 QualType ElementType = getDerived().TransformType(T->getElementType());
3947 if (ElementType.isNull())
3950 QualType Result = TL.getType();
3951 if (getDerived().AlwaysRebuild() ||
3952 ElementType != T->getElementType()) {
3953 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
3954 T->getVectorKind());
3955 if (Result.isNull())
3959 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
3960 NewTL.setNameLoc(TL.getNameLoc());
3965 template<typename Derived>
3966 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
3967 ExtVectorTypeLoc TL) {
3968 const VectorType *T = TL.getTypePtr();
3969 QualType ElementType = getDerived().TransformType(T->getElementType());
3970 if (ElementType.isNull())
3973 QualType Result = TL.getType();
3974 if (getDerived().AlwaysRebuild() ||
3975 ElementType != T->getElementType()) {
3976 Result = getDerived().RebuildExtVectorType(ElementType,
3977 T->getNumElements(),
3978 /*FIXME*/ SourceLocation());
3979 if (Result.isNull())
3983 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
3984 NewTL.setNameLoc(TL.getNameLoc());
3989 template <typename Derived>
3990 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
3991 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
3992 bool ExpectParameterPack) {
3993 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3994 TypeSourceInfo *NewDI = 0;
3996 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
3997 // If we're substituting into a pack expansion type and we know the
3998 // length we want to expand to, just substitute for the pattern.
3999 TypeLoc OldTL = OldDI->getTypeLoc();
4000 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
4003 TypeLoc NewTL = OldDI->getTypeLoc();
4004 TLB.reserve(NewTL.getFullDataSize());
4006 QualType Result = getDerived().TransformType(TLB,
4007 OldExpansionTL.getPatternLoc());
4008 if (Result.isNull())
4011 Result = RebuildPackExpansionType(Result,
4012 OldExpansionTL.getPatternLoc().getSourceRange(),
4013 OldExpansionTL.getEllipsisLoc(),
4015 if (Result.isNull())
4018 PackExpansionTypeLoc NewExpansionTL
4019 = TLB.push<PackExpansionTypeLoc>(Result);
4020 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
4021 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
4023 NewDI = getDerived().TransformType(OldDI);
4027 if (NewDI == OldDI && indexAdjustment == 0)
4030 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
4031 OldParm->getDeclContext(),
4032 OldParm->getInnerLocStart(),
4033 OldParm->getLocation(),
4034 OldParm->getIdentifier(),
4037 OldParm->getStorageClass(),
4039 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
4040 OldParm->getFunctionScopeIndex() + indexAdjustment);
4044 template<typename Derived>
4045 bool TreeTransform<Derived>::
4046 TransformFunctionTypeParams(SourceLocation Loc,
4047 ParmVarDecl **Params, unsigned NumParams,
4048 const QualType *ParamTypes,
4049 SmallVectorImpl<QualType> &OutParamTypes,
4050 SmallVectorImpl<ParmVarDecl*> *PVars) {
4051 int indexAdjustment = 0;
4053 for (unsigned i = 0; i != NumParams; ++i) {
4054 if (ParmVarDecl *OldParm = Params[i]) {
4055 assert(OldParm->getFunctionScopeIndex() == i);
4057 Optional<unsigned> NumExpansions;
4058 ParmVarDecl *NewParm = 0;
4059 if (OldParm->isParameterPack()) {
4060 // We have a function parameter pack that may need to be expanded.
4061 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4063 // Find the parameter packs that could be expanded.
4064 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
4065 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
4066 TypeLoc Pattern = ExpansionTL.getPatternLoc();
4067 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
4068 assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
4070 // Determine whether we should expand the parameter packs.
4071 bool ShouldExpand = false;
4072 bool RetainExpansion = false;
4073 Optional<unsigned> OrigNumExpansions =
4074 ExpansionTL.getTypePtr()->getNumExpansions();
4075 NumExpansions = OrigNumExpansions;
4076 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
4077 Pattern.getSourceRange(),
4086 // Expand the function parameter pack into multiple, separate
4088 getDerived().ExpandingFunctionParameterPack(OldParm);
4089 for (unsigned I = 0; I != *NumExpansions; ++I) {
4090 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4091 ParmVarDecl *NewParm
4092 = getDerived().TransformFunctionTypeParam(OldParm,
4095 /*ExpectParameterPack=*/false);
4099 OutParamTypes.push_back(NewParm->getType());
4101 PVars->push_back(NewParm);
4104 // If we're supposed to retain a pack expansion, do so by temporarily
4105 // forgetting the partially-substituted parameter pack.
4106 if (RetainExpansion) {
4107 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4108 ParmVarDecl *NewParm
4109 = getDerived().TransformFunctionTypeParam(OldParm,
4112 /*ExpectParameterPack=*/false);
4116 OutParamTypes.push_back(NewParm->getType());
4118 PVars->push_back(NewParm);
4121 // The next parameter should have the same adjustment as the
4122 // last thing we pushed, but we post-incremented indexAdjustment
4123 // on every push. Also, if we push nothing, the adjustment should
4127 // We're done with the pack expansion.
4131 // We'll substitute the parameter now without expanding the pack
4133 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4134 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
4137 /*ExpectParameterPack=*/true);
4139 NewParm = getDerived().TransformFunctionTypeParam(
4140 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
4146 OutParamTypes.push_back(NewParm->getType());
4148 PVars->push_back(NewParm);
4152 // Deal with the possibility that we don't have a parameter
4153 // declaration for this parameter.
4154 QualType OldType = ParamTypes[i];
4155 bool IsPackExpansion = false;
4156 Optional<unsigned> NumExpansions;
4158 if (const PackExpansionType *Expansion
4159 = dyn_cast<PackExpansionType>(OldType)) {
4160 // We have a function parameter pack that may need to be expanded.
4161 QualType Pattern = Expansion->getPattern();
4162 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4163 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4165 // Determine whether we should expand the parameter packs.
4166 bool ShouldExpand = false;
4167 bool RetainExpansion = false;
4168 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
4177 // Expand the function parameter pack into multiple, separate
4179 for (unsigned I = 0; I != *NumExpansions; ++I) {
4180 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4181 QualType NewType = getDerived().TransformType(Pattern);
4182 if (NewType.isNull())
4185 OutParamTypes.push_back(NewType);
4187 PVars->push_back(0);
4190 // We're done with the pack expansion.
4194 // If we're supposed to retain a pack expansion, do so by temporarily
4195 // forgetting the partially-substituted parameter pack.
4196 if (RetainExpansion) {
4197 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4198 QualType NewType = getDerived().TransformType(Pattern);
4199 if (NewType.isNull())
4202 OutParamTypes.push_back(NewType);
4204 PVars->push_back(0);
4207 // We'll substitute the parameter now without expanding the pack
4209 OldType = Expansion->getPattern();
4210 IsPackExpansion = true;
4211 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4212 NewType = getDerived().TransformType(OldType);
4214 NewType = getDerived().TransformType(OldType);
4217 if (NewType.isNull())
4220 if (IsPackExpansion)
4221 NewType = getSema().Context.getPackExpansionType(NewType,
4224 OutParamTypes.push_back(NewType);
4226 PVars->push_back(0);
4231 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
4232 if (ParmVarDecl *parm = (*PVars)[i])
4233 assert(parm->getFunctionScopeIndex() == i);
4240 template<typename Derived>
4242 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
4243 FunctionProtoTypeLoc TL) {
4244 return getDerived().TransformFunctionProtoType(TLB, TL, 0, 0);
4247 template<typename Derived>
4249 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
4250 FunctionProtoTypeLoc TL,
4251 CXXRecordDecl *ThisContext,
4252 unsigned ThisTypeQuals) {
4253 // Transform the parameters and return type.
4255 // We are required to instantiate the params and return type in source order.
4256 // When the function has a trailing return type, we instantiate the
4257 // parameters before the return type, since the return type can then refer
4258 // to the parameters themselves (via decltype, sizeof, etc.).
4260 SmallVector<QualType, 4> ParamTypes;
4261 SmallVector<ParmVarDecl*, 4> ParamDecls;
4262 const FunctionProtoType *T = TL.getTypePtr();
4264 QualType ResultType;
4266 if (T->hasTrailingReturn()) {
4267 if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
4270 TL.getTypePtr()->arg_type_begin(),
4271 ParamTypes, &ParamDecls))
4275 // C++11 [expr.prim.general]p3:
4276 // If a declaration declares a member function or member function
4277 // template of a class X, the expression this is a prvalue of type
4278 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4279 // and the end of the function-definition, member-declarator, or
4281 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
4283 ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
4284 if (ResultType.isNull())
4289 ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
4290 if (ResultType.isNull())
4293 if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
4296 TL.getTypePtr()->arg_type_begin(),
4297 ParamTypes, &ParamDecls))
4301 // FIXME: Need to transform the exception-specification too.
4303 QualType Result = TL.getType();
4304 if (getDerived().AlwaysRebuild() ||
4305 ResultType != T->getResultType() ||
4306 T->getNumArgs() != ParamTypes.size() ||
4307 !std::equal(T->arg_type_begin(), T->arg_type_end(), ParamTypes.begin())) {
4308 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes,
4309 T->getExtProtoInfo());
4310 if (Result.isNull())
4314 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
4315 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4316 NewTL.setLParenLoc(TL.getLParenLoc());
4317 NewTL.setRParenLoc(TL.getRParenLoc());
4318 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4319 for (unsigned i = 0, e = NewTL.getNumArgs(); i != e; ++i)
4320 NewTL.setArg(i, ParamDecls[i]);
4325 template<typename Derived>
4326 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
4327 TypeLocBuilder &TLB,
4328 FunctionNoProtoTypeLoc TL) {
4329 const FunctionNoProtoType *T = TL.getTypePtr();
4330 QualType ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
4331 if (ResultType.isNull())
4334 QualType Result = TL.getType();
4335 if (getDerived().AlwaysRebuild() ||
4336 ResultType != T->getResultType())
4337 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
4339 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
4340 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4341 NewTL.setLParenLoc(TL.getLParenLoc());
4342 NewTL.setRParenLoc(TL.getRParenLoc());
4343 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4348 template<typename Derived> QualType
4349 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
4350 UnresolvedUsingTypeLoc TL) {
4351 const UnresolvedUsingType *T = TL.getTypePtr();
4352 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
4356 QualType Result = TL.getType();
4357 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
4358 Result = getDerived().RebuildUnresolvedUsingType(D);
4359 if (Result.isNull())
4363 // We might get an arbitrary type spec type back. We should at
4364 // least always get a type spec type, though.
4365 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
4366 NewTL.setNameLoc(TL.getNameLoc());
4371 template<typename Derived>
4372 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
4373 TypedefTypeLoc TL) {
4374 const TypedefType *T = TL.getTypePtr();
4375 TypedefNameDecl *Typedef
4376 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4381 QualType Result = TL.getType();
4382 if (getDerived().AlwaysRebuild() ||
4383 Typedef != T->getDecl()) {
4384 Result = getDerived().RebuildTypedefType(Typedef);
4385 if (Result.isNull())
4389 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
4390 NewTL.setNameLoc(TL.getNameLoc());
4395 template<typename Derived>
4396 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
4397 TypeOfExprTypeLoc TL) {
4398 // typeof expressions are not potentially evaluated contexts
4399 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4400 Sema::ReuseLambdaContextDecl);
4402 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
4406 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
4410 QualType Result = TL.getType();
4411 if (getDerived().AlwaysRebuild() ||
4412 E.get() != TL.getUnderlyingExpr()) {
4413 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
4414 if (Result.isNull())
4419 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
4420 NewTL.setTypeofLoc(TL.getTypeofLoc());
4421 NewTL.setLParenLoc(TL.getLParenLoc());
4422 NewTL.setRParenLoc(TL.getRParenLoc());
4427 template<typename Derived>
4428 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
4430 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
4431 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
4435 QualType Result = TL.getType();
4436 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
4437 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
4438 if (Result.isNull())
4442 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
4443 NewTL.setTypeofLoc(TL.getTypeofLoc());
4444 NewTL.setLParenLoc(TL.getLParenLoc());
4445 NewTL.setRParenLoc(TL.getRParenLoc());
4446 NewTL.setUnderlyingTInfo(New_Under_TI);
4451 template<typename Derived>
4452 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
4453 DecltypeTypeLoc TL) {
4454 const DecltypeType *T = TL.getTypePtr();
4456 // decltype expressions are not potentially evaluated contexts
4457 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated, 0,
4458 /*IsDecltype=*/ true);
4460 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
4464 E = getSema().ActOnDecltypeExpression(E.take());
4468 QualType Result = TL.getType();
4469 if (getDerived().AlwaysRebuild() ||
4470 E.get() != T->getUnderlyingExpr()) {
4471 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
4472 if (Result.isNull())
4477 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
4478 NewTL.setNameLoc(TL.getNameLoc());
4483 template<typename Derived>
4484 QualType TreeTransform<Derived>::TransformUnaryTransformType(
4485 TypeLocBuilder &TLB,
4486 UnaryTransformTypeLoc TL) {
4487 QualType Result = TL.getType();
4488 if (Result->isDependentType()) {
4489 const UnaryTransformType *T = TL.getTypePtr();
4491 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
4492 Result = getDerived().RebuildUnaryTransformType(NewBase,
4495 if (Result.isNull())
4499 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
4500 NewTL.setKWLoc(TL.getKWLoc());
4501 NewTL.setParensRange(TL.getParensRange());
4502 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
4506 template<typename Derived>
4507 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
4509 const AutoType *T = TL.getTypePtr();
4510 QualType OldDeduced = T->getDeducedType();
4511 QualType NewDeduced;
4512 if (!OldDeduced.isNull()) {
4513 NewDeduced = getDerived().TransformType(OldDeduced);
4514 if (NewDeduced.isNull())
4518 QualType Result = TL.getType();
4519 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
4520 T->isDependentType()) {
4521 Result = getDerived().RebuildAutoType(NewDeduced, T->isDecltypeAuto());
4522 if (Result.isNull())
4526 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4527 NewTL.setNameLoc(TL.getNameLoc());
4532 template<typename Derived>
4533 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
4535 const RecordType *T = TL.getTypePtr();
4537 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4542 QualType Result = TL.getType();
4543 if (getDerived().AlwaysRebuild() ||
4544 Record != T->getDecl()) {
4545 Result = getDerived().RebuildRecordType(Record);
4546 if (Result.isNull())
4550 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
4551 NewTL.setNameLoc(TL.getNameLoc());
4556 template<typename Derived>
4557 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
4559 const EnumType *T = TL.getTypePtr();
4561 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4566 QualType Result = TL.getType();
4567 if (getDerived().AlwaysRebuild() ||
4568 Enum != T->getDecl()) {
4569 Result = getDerived().RebuildEnumType(Enum);
4570 if (Result.isNull())
4574 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
4575 NewTL.setNameLoc(TL.getNameLoc());
4580 template<typename Derived>
4581 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
4582 TypeLocBuilder &TLB,
4583 InjectedClassNameTypeLoc TL) {
4584 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
4585 TL.getTypePtr()->getDecl());
4586 if (!D) return QualType();
4588 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
4589 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
4593 template<typename Derived>
4594 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
4595 TypeLocBuilder &TLB,
4596 TemplateTypeParmTypeLoc TL) {
4597 return TransformTypeSpecType(TLB, TL);
4600 template<typename Derived>
4601 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
4602 TypeLocBuilder &TLB,
4603 SubstTemplateTypeParmTypeLoc TL) {
4604 const SubstTemplateTypeParmType *T = TL.getTypePtr();
4606 // Substitute into the replacement type, which itself might involve something
4607 // that needs to be transformed. This only tends to occur with default
4608 // template arguments of template template parameters.
4609 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
4610 QualType Replacement = getDerived().TransformType(T->getReplacementType());
4611 if (Replacement.isNull())
4614 // Always canonicalize the replacement type.
4615 Replacement = SemaRef.Context.getCanonicalType(Replacement);
4617 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
4620 // Propagate type-source information.
4621 SubstTemplateTypeParmTypeLoc NewTL
4622 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
4623 NewTL.setNameLoc(TL.getNameLoc());
4628 template<typename Derived>
4629 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
4630 TypeLocBuilder &TLB,
4631 SubstTemplateTypeParmPackTypeLoc TL) {
4632 return TransformTypeSpecType(TLB, TL);
4635 template<typename Derived>
4636 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
4637 TypeLocBuilder &TLB,
4638 TemplateSpecializationTypeLoc TL) {
4639 const TemplateSpecializationType *T = TL.getTypePtr();
4641 // The nested-name-specifier never matters in a TemplateSpecializationType,
4642 // because we can't have a dependent nested-name-specifier anyway.
4644 TemplateName Template
4645 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
4646 TL.getTemplateNameLoc());
4647 if (Template.isNull())
4650 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
4653 template<typename Derived>
4654 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
4656 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
4657 if (ValueType.isNull())
4660 QualType Result = TL.getType();
4661 if (getDerived().AlwaysRebuild() ||
4662 ValueType != TL.getValueLoc().getType()) {
4663 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
4664 if (Result.isNull())
4668 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
4669 NewTL.setKWLoc(TL.getKWLoc());
4670 NewTL.setLParenLoc(TL.getLParenLoc());
4671 NewTL.setRParenLoc(TL.getRParenLoc());
4676 /// \brief Simple iterator that traverses the template arguments in a
4677 /// container that provides a \c getArgLoc() member function.
4679 /// This iterator is intended to be used with the iterator form of
4680 /// \c TreeTransform<Derived>::TransformTemplateArguments().
4681 template<typename ArgLocContainer>
4682 class TemplateArgumentLocContainerIterator {
4683 ArgLocContainer *Container;
4687 typedef TemplateArgumentLoc value_type;
4688 typedef TemplateArgumentLoc reference;
4689 typedef int difference_type;
4690 typedef std::input_iterator_tag iterator_category;
4693 TemplateArgumentLoc Arg;
4696 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4698 const TemplateArgumentLoc *operator->() const {
4704 TemplateArgumentLocContainerIterator() {}
4706 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
4708 : Container(&Container), Index(Index) { }
4710 TemplateArgumentLocContainerIterator &operator++() {
4715 TemplateArgumentLocContainerIterator operator++(int) {
4716 TemplateArgumentLocContainerIterator Old(*this);
4721 TemplateArgumentLoc operator*() const {
4722 return Container->getArgLoc(Index);
4725 pointer operator->() const {
4726 return pointer(Container->getArgLoc(Index));
4729 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
4730 const TemplateArgumentLocContainerIterator &Y) {
4731 return X.Container == Y.Container && X.Index == Y.Index;
4734 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
4735 const TemplateArgumentLocContainerIterator &Y) {
4741 template <typename Derived>
4742 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
4743 TypeLocBuilder &TLB,
4744 TemplateSpecializationTypeLoc TL,
4745 TemplateName Template) {
4746 TemplateArgumentListInfo NewTemplateArgs;
4747 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
4748 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
4749 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
4751 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
4752 ArgIterator(TL, TL.getNumArgs()),
4756 // FIXME: maybe don't rebuild if all the template arguments are the same.
4759 getDerived().RebuildTemplateSpecializationType(Template,
4760 TL.getTemplateNameLoc(),
4763 if (!Result.isNull()) {
4764 // Specializations of template template parameters are represented as
4765 // TemplateSpecializationTypes, and substitution of type alias templates
4766 // within a dependent context can transform them into
4767 // DependentTemplateSpecializationTypes.
4768 if (isa<DependentTemplateSpecializationType>(Result)) {
4769 DependentTemplateSpecializationTypeLoc NewTL
4770 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
4771 NewTL.setElaboratedKeywordLoc(SourceLocation());
4772 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
4773 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
4774 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
4775 NewTL.setLAngleLoc(TL.getLAngleLoc());
4776 NewTL.setRAngleLoc(TL.getRAngleLoc());
4777 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
4778 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
4782 TemplateSpecializationTypeLoc NewTL
4783 = TLB.push<TemplateSpecializationTypeLoc>(Result);
4784 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
4785 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
4786 NewTL.setLAngleLoc(TL.getLAngleLoc());
4787 NewTL.setRAngleLoc(TL.getRAngleLoc());
4788 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
4789 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
4795 template <typename Derived>
4796 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
4797 TypeLocBuilder &TLB,
4798 DependentTemplateSpecializationTypeLoc TL,
4799 TemplateName Template,
4801 TemplateArgumentListInfo NewTemplateArgs;
4802 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
4803 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
4804 typedef TemplateArgumentLocContainerIterator<
4805 DependentTemplateSpecializationTypeLoc> ArgIterator;
4806 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
4807 ArgIterator(TL, TL.getNumArgs()),
4811 // FIXME: maybe don't rebuild if all the template arguments are the same.
4813 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4815 = getSema().Context.getDependentTemplateSpecializationType(
4816 TL.getTypePtr()->getKeyword(),
4817 DTN->getQualifier(),
4818 DTN->getIdentifier(),
4821 DependentTemplateSpecializationTypeLoc NewTL
4822 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
4823 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
4824 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
4825 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
4826 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
4827 NewTL.setLAngleLoc(TL.getLAngleLoc());
4828 NewTL.setRAngleLoc(TL.getRAngleLoc());
4829 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
4830 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
4835 = getDerived().RebuildTemplateSpecializationType(Template,
4836 TL.getTemplateNameLoc(),
4839 if (!Result.isNull()) {
4840 /// FIXME: Wrap this in an elaborated-type-specifier?
4841 TemplateSpecializationTypeLoc NewTL
4842 = TLB.push<TemplateSpecializationTypeLoc>(Result);
4843 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
4844 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
4845 NewTL.setLAngleLoc(TL.getLAngleLoc());
4846 NewTL.setRAngleLoc(TL.getRAngleLoc());
4847 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
4848 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
4854 template<typename Derived>
4856 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
4857 ElaboratedTypeLoc TL) {
4858 const ElaboratedType *T = TL.getTypePtr();
4860 NestedNameSpecifierLoc QualifierLoc;
4861 // NOTE: the qualifier in an ElaboratedType is optional.
4862 if (TL.getQualifierLoc()) {
4864 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
4869 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
4870 if (NamedT.isNull())
4873 // C++0x [dcl.type.elab]p2:
4874 // If the identifier resolves to a typedef-name or the simple-template-id
4875 // resolves to an alias template specialization, the
4876 // elaborated-type-specifier is ill-formed.
4877 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
4878 if (const TemplateSpecializationType *TST =
4879 NamedT->getAs<TemplateSpecializationType>()) {
4880 TemplateName Template = TST->getTemplateName();
4881 if (TypeAliasTemplateDecl *TAT =
4882 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4883 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
4884 diag::err_tag_reference_non_tag) << 4;
4885 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
4890 QualType Result = TL.getType();
4891 if (getDerived().AlwaysRebuild() ||
4892 QualifierLoc != TL.getQualifierLoc() ||
4893 NamedT != T->getNamedType()) {
4894 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
4896 QualifierLoc, NamedT);
4897 if (Result.isNull())
4901 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
4902 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
4903 NewTL.setQualifierLoc(QualifierLoc);
4907 template<typename Derived>
4908 QualType TreeTransform<Derived>::TransformAttributedType(
4909 TypeLocBuilder &TLB,
4910 AttributedTypeLoc TL) {
4911 const AttributedType *oldType = TL.getTypePtr();
4912 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
4913 if (modifiedType.isNull())
4916 QualType result = TL.getType();
4918 // FIXME: dependent operand expressions?
4919 if (getDerived().AlwaysRebuild() ||
4920 modifiedType != oldType->getModifiedType()) {
4921 // TODO: this is really lame; we should really be rebuilding the
4922 // equivalent type from first principles.
4923 QualType equivalentType
4924 = getDerived().TransformType(oldType->getEquivalentType());
4925 if (equivalentType.isNull())
4927 result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
4932 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
4933 newTL.setAttrNameLoc(TL.getAttrNameLoc());
4934 if (TL.hasAttrOperand())
4935 newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
4936 if (TL.hasAttrExprOperand())
4937 newTL.setAttrExprOperand(TL.getAttrExprOperand());
4938 else if (TL.hasAttrEnumOperand())
4939 newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
4944 template<typename Derived>
4946 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
4948 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
4952 QualType Result = TL.getType();
4953 if (getDerived().AlwaysRebuild() ||
4954 Inner != TL.getInnerLoc().getType()) {
4955 Result = getDerived().RebuildParenType(Inner);
4956 if (Result.isNull())
4960 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
4961 NewTL.setLParenLoc(TL.getLParenLoc());
4962 NewTL.setRParenLoc(TL.getRParenLoc());
4966 template<typename Derived>
4967 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
4968 DependentNameTypeLoc TL) {
4969 const DependentNameType *T = TL.getTypePtr();
4971 NestedNameSpecifierLoc QualifierLoc
4972 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
4977 = getDerived().RebuildDependentNameType(T->getKeyword(),
4978 TL.getElaboratedKeywordLoc(),
4982 if (Result.isNull())
4985 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
4986 QualType NamedT = ElabT->getNamedType();
4987 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
4989 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
4990 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
4991 NewTL.setQualifierLoc(QualifierLoc);
4993 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
4994 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
4995 NewTL.setQualifierLoc(QualifierLoc);
4996 NewTL.setNameLoc(TL.getNameLoc());
5001 template<typename Derived>
5002 QualType TreeTransform<Derived>::
5003 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5004 DependentTemplateSpecializationTypeLoc TL) {
5005 NestedNameSpecifierLoc QualifierLoc;
5006 if (TL.getQualifierLoc()) {
5008 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5014 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
5017 template<typename Derived>
5018 QualType TreeTransform<Derived>::
5019 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5020 DependentTemplateSpecializationTypeLoc TL,
5021 NestedNameSpecifierLoc QualifierLoc) {
5022 const DependentTemplateSpecializationType *T = TL.getTypePtr();
5024 TemplateArgumentListInfo NewTemplateArgs;
5025 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5026 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5028 typedef TemplateArgumentLocContainerIterator<
5029 DependentTemplateSpecializationTypeLoc> ArgIterator;
5030 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5031 ArgIterator(TL, TL.getNumArgs()),
5036 = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
5039 TL.getTemplateNameLoc(),
5041 if (Result.isNull())
5044 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
5045 QualType NamedT = ElabT->getNamedType();
5047 // Copy information relevant to the template specialization.
5048 TemplateSpecializationTypeLoc NamedTL
5049 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5050 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5051 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5052 NamedTL.setLAngleLoc(TL.getLAngleLoc());
5053 NamedTL.setRAngleLoc(TL.getRAngleLoc());
5054 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5055 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5057 // Copy information relevant to the elaborated type.
5058 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5059 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5060 NewTL.setQualifierLoc(QualifierLoc);
5061 } else if (isa<DependentTemplateSpecializationType>(Result)) {
5062 DependentTemplateSpecializationTypeLoc SpecTL
5063 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5064 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5065 SpecTL.setQualifierLoc(QualifierLoc);
5066 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5067 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5068 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5069 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5070 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5071 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5073 TemplateSpecializationTypeLoc SpecTL
5074 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5075 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5076 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5077 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5078 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5079 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5080 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5085 template<typename Derived>
5086 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
5087 PackExpansionTypeLoc TL) {
5089 = getDerived().TransformType(TLB, TL.getPatternLoc());
5090 if (Pattern.isNull())
5093 QualType Result = TL.getType();
5094 if (getDerived().AlwaysRebuild() ||
5095 Pattern != TL.getPatternLoc().getType()) {
5096 Result = getDerived().RebuildPackExpansionType(Pattern,
5097 TL.getPatternLoc().getSourceRange(),
5098 TL.getEllipsisLoc(),
5099 TL.getTypePtr()->getNumExpansions());
5100 if (Result.isNull())
5104 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
5105 NewT.setEllipsisLoc(TL.getEllipsisLoc());
5109 template<typename Derived>
5111 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
5112 ObjCInterfaceTypeLoc TL) {
5113 // ObjCInterfaceType is never dependent.
5114 TLB.pushFullCopy(TL);
5115 return TL.getType();
5118 template<typename Derived>
5120 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
5121 ObjCObjectTypeLoc TL) {
5122 // ObjCObjectType is never dependent.
5123 TLB.pushFullCopy(TL);
5124 return TL.getType();
5127 template<typename Derived>
5129 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
5130 ObjCObjectPointerTypeLoc TL) {
5131 // ObjCObjectPointerType is never dependent.
5132 TLB.pushFullCopy(TL);
5133 return TL.getType();
5136 //===----------------------------------------------------------------------===//
5137 // Statement transformation
5138 //===----------------------------------------------------------------------===//
5139 template<typename Derived>
5141 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
5142 return SemaRef.Owned(S);
5145 template<typename Derived>
5147 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
5148 return getDerived().TransformCompoundStmt(S, false);
5151 template<typename Derived>
5153 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
5155 Sema::CompoundScopeRAII CompoundScope(getSema());
5157 bool SubStmtInvalid = false;
5158 bool SubStmtChanged = false;
5159 SmallVector<Stmt*, 8> Statements;
5160 for (CompoundStmt::body_iterator B = S->body_begin(), BEnd = S->body_end();
5162 StmtResult Result = getDerived().TransformStmt(*B);
5163 if (Result.isInvalid()) {
5164 // Immediately fail if this was a DeclStmt, since it's very
5165 // likely that this will cause problems for future statements.
5166 if (isa<DeclStmt>(*B))
5169 // Otherwise, just keep processing substatements and fail later.
5170 SubStmtInvalid = true;
5174 SubStmtChanged = SubStmtChanged || Result.get() != *B;
5175 Statements.push_back(Result.takeAs<Stmt>());
5181 if (!getDerived().AlwaysRebuild() &&
5183 return SemaRef.Owned(S);
5185 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
5191 template<typename Derived>
5193 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
5194 ExprResult LHS, RHS;
5196 EnterExpressionEvaluationContext Unevaluated(SemaRef,
5197 Sema::ConstantEvaluated);
5199 // Transform the left-hand case value.
5200 LHS = getDerived().TransformExpr(S->getLHS());
5201 LHS = SemaRef.ActOnConstantExpression(LHS);
5202 if (LHS.isInvalid())
5205 // Transform the right-hand case value (for the GNU case-range extension).
5206 RHS = getDerived().TransformExpr(S->getRHS());
5207 RHS = SemaRef.ActOnConstantExpression(RHS);
5208 if (RHS.isInvalid())
5212 // Build the case statement.
5213 // Case statements are always rebuilt so that they will attached to their
5214 // transformed switch statement.
5215 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
5217 S->getEllipsisLoc(),
5220 if (Case.isInvalid())
5223 // Transform the statement following the case
5224 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5225 if (SubStmt.isInvalid())
5228 // Attach the body to the case statement
5229 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
5232 template<typename Derived>
5234 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
5235 // Transform the statement following the default case
5236 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5237 if (SubStmt.isInvalid())
5240 // Default statements are always rebuilt
5241 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
5245 template<typename Derived>
5247 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
5248 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5249 if (SubStmt.isInvalid())
5252 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
5258 // FIXME: Pass the real colon location in.
5259 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
5260 cast<LabelDecl>(LD), SourceLocation(),
5264 template<typename Derived>
5266 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
5267 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5268 if (SubStmt.isInvalid())
5271 // TODO: transform attributes
5272 if (SubStmt.get() == S->getSubStmt() /* && attrs are the same */)
5275 return getDerived().RebuildAttributedStmt(S->getAttrLoc(),
5280 template<typename Derived>
5282 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
5283 // Transform the condition
5285 VarDecl *ConditionVar = 0;
5286 if (S->getConditionVariable()) {
5288 = cast_or_null<VarDecl>(
5289 getDerived().TransformDefinition(
5290 S->getConditionVariable()->getLocation(),
5291 S->getConditionVariable()));
5295 Cond = getDerived().TransformExpr(S->getCond());
5297 if (Cond.isInvalid())
5300 // Convert the condition to a boolean value.
5302 ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getIfLoc(),
5304 if (CondE.isInvalid())
5311 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
5312 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5315 // Transform the "then" branch.
5316 StmtResult Then = getDerived().TransformStmt(S->getThen());
5317 if (Then.isInvalid())
5320 // Transform the "else" branch.
5321 StmtResult Else = getDerived().TransformStmt(S->getElse());
5322 if (Else.isInvalid())
5325 if (!getDerived().AlwaysRebuild() &&
5326 FullCond.get() == S->getCond() &&
5327 ConditionVar == S->getConditionVariable() &&
5328 Then.get() == S->getThen() &&
5329 Else.get() == S->getElse())
5330 return SemaRef.Owned(S);
5332 return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
5334 S->getElseLoc(), Else.get());
5337 template<typename Derived>
5339 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
5340 // Transform the condition.
5342 VarDecl *ConditionVar = 0;
5343 if (S->getConditionVariable()) {
5345 = cast_or_null<VarDecl>(
5346 getDerived().TransformDefinition(
5347 S->getConditionVariable()->getLocation(),
5348 S->getConditionVariable()));
5352 Cond = getDerived().TransformExpr(S->getCond());
5354 if (Cond.isInvalid())
5358 // Rebuild the switch statement.
5360 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
5362 if (Switch.isInvalid())
5365 // Transform the body of the switch statement.
5366 StmtResult Body = getDerived().TransformStmt(S->getBody());
5367 if (Body.isInvalid())
5370 // Complete the switch statement.
5371 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
5375 template<typename Derived>
5377 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
5378 // Transform the condition
5380 VarDecl *ConditionVar = 0;
5381 if (S->getConditionVariable()) {
5383 = cast_or_null<VarDecl>(
5384 getDerived().TransformDefinition(
5385 S->getConditionVariable()->getLocation(),
5386 S->getConditionVariable()));
5390 Cond = getDerived().TransformExpr(S->getCond());
5392 if (Cond.isInvalid())
5396 // Convert the condition to a boolean value.
5397 ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getWhileLoc(),
5399 if (CondE.isInvalid())
5405 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
5406 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5409 // Transform the body
5410 StmtResult Body = getDerived().TransformStmt(S->getBody());
5411 if (Body.isInvalid())
5414 if (!getDerived().AlwaysRebuild() &&
5415 FullCond.get() == S->getCond() &&
5416 ConditionVar == S->getConditionVariable() &&
5417 Body.get() == S->getBody())
5420 return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
5421 ConditionVar, Body.get());
5424 template<typename Derived>
5426 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
5427 // Transform the body
5428 StmtResult Body = getDerived().TransformStmt(S->getBody());
5429 if (Body.isInvalid())
5432 // Transform the condition
5433 ExprResult Cond = getDerived().TransformExpr(S->getCond());
5434 if (Cond.isInvalid())
5437 if (!getDerived().AlwaysRebuild() &&
5438 Cond.get() == S->getCond() &&
5439 Body.get() == S->getBody())
5440 return SemaRef.Owned(S);
5442 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
5443 /*FIXME:*/S->getWhileLoc(), Cond.get(),
5447 template<typename Derived>
5449 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
5450 // Transform the initialization statement
5451 StmtResult Init = getDerived().TransformStmt(S->getInit());
5452 if (Init.isInvalid())
5455 // Transform the condition
5457 VarDecl *ConditionVar = 0;
5458 if (S->getConditionVariable()) {
5460 = cast_or_null<VarDecl>(
5461 getDerived().TransformDefinition(
5462 S->getConditionVariable()->getLocation(),
5463 S->getConditionVariable()));
5467 Cond = getDerived().TransformExpr(S->getCond());
5469 if (Cond.isInvalid())
5473 // Convert the condition to a boolean value.
5474 ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getForLoc(),
5476 if (CondE.isInvalid())
5483 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
5484 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5487 // Transform the increment
5488 ExprResult Inc = getDerived().TransformExpr(S->getInc());
5489 if (Inc.isInvalid())
5492 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
5493 if (S->getInc() && !FullInc.get())
5496 // Transform the body
5497 StmtResult Body = getDerived().TransformStmt(S->getBody());
5498 if (Body.isInvalid())
5501 if (!getDerived().AlwaysRebuild() &&
5502 Init.get() == S->getInit() &&
5503 FullCond.get() == S->getCond() &&
5504 Inc.get() == S->getInc() &&
5505 Body.get() == S->getBody())
5506 return SemaRef.Owned(S);
5508 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
5509 Init.get(), FullCond, ConditionVar,
5510 FullInc, S->getRParenLoc(), Body.get());
5513 template<typename Derived>
5515 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
5516 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
5521 // Goto statements must always be rebuilt, to resolve the label.
5522 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
5523 cast<LabelDecl>(LD));
5526 template<typename Derived>
5528 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
5529 ExprResult Target = getDerived().TransformExpr(S->getTarget());
5530 if (Target.isInvalid())
5532 Target = SemaRef.MaybeCreateExprWithCleanups(Target.take());
5534 if (!getDerived().AlwaysRebuild() &&
5535 Target.get() == S->getTarget())
5536 return SemaRef.Owned(S);
5538 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
5542 template<typename Derived>
5544 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
5545 return SemaRef.Owned(S);
5548 template<typename Derived>
5550 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
5551 return SemaRef.Owned(S);
5554 template<typename Derived>
5556 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
5557 ExprResult Result = getDerived().TransformExpr(S->getRetValue());
5558 if (Result.isInvalid())
5561 // FIXME: We always rebuild the return statement because there is no way
5562 // to tell whether the return type of the function has changed.
5563 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
5566 template<typename Derived>
5568 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
5569 bool DeclChanged = false;
5570 SmallVector<Decl *, 4> Decls;
5571 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
5573 Decl *Transformed = getDerived().TransformDefinition((*D)->getLocation(),
5578 if (Transformed != *D)
5581 Decls.push_back(Transformed);
5584 if (!getDerived().AlwaysRebuild() && !DeclChanged)
5585 return SemaRef.Owned(S);
5587 return getDerived().RebuildDeclStmt(Decls.data(), Decls.size(),
5588 S->getStartLoc(), S->getEndLoc());
5591 template<typename Derived>
5593 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
5595 SmallVector<Expr*, 8> Constraints;
5596 SmallVector<Expr*, 8> Exprs;
5597 SmallVector<IdentifierInfo *, 4> Names;
5599 ExprResult AsmString;
5600 SmallVector<Expr*, 8> Clobbers;
5602 bool ExprsChanged = false;
5604 // Go through the outputs.
5605 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
5606 Names.push_back(S->getOutputIdentifier(I));
5608 // No need to transform the constraint literal.
5609 Constraints.push_back(S->getOutputConstraintLiteral(I));
5611 // Transform the output expr.
5612 Expr *OutputExpr = S->getOutputExpr(I);
5613 ExprResult Result = getDerived().TransformExpr(OutputExpr);
5614 if (Result.isInvalid())
5617 ExprsChanged |= Result.get() != OutputExpr;
5619 Exprs.push_back(Result.get());
5622 // Go through the inputs.
5623 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
5624 Names.push_back(S->getInputIdentifier(I));
5626 // No need to transform the constraint literal.
5627 Constraints.push_back(S->getInputConstraintLiteral(I));
5629 // Transform the input expr.
5630 Expr *InputExpr = S->getInputExpr(I);
5631 ExprResult Result = getDerived().TransformExpr(InputExpr);
5632 if (Result.isInvalid())
5635 ExprsChanged |= Result.get() != InputExpr;
5637 Exprs.push_back(Result.get());
5640 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
5641 return SemaRef.Owned(S);
5643 // Go through the clobbers.
5644 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
5645 Clobbers.push_back(S->getClobberStringLiteral(I));
5647 // No need to transform the asm string literal.
5648 AsmString = SemaRef.Owned(S->getAsmString());
5649 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
5650 S->isVolatile(), S->getNumOutputs(),
5651 S->getNumInputs(), Names.data(),
5652 Constraints, Exprs, AsmString.get(),
5653 Clobbers, S->getRParenLoc());
5656 template<typename Derived>
5658 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
5659 ArrayRef<Token> AsmToks =
5660 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
5662 bool HadError = false, HadChange = false;
5664 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
5665 SmallVector<Expr*, 8> TransformedExprs;
5666 TransformedExprs.reserve(SrcExprs.size());
5667 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
5668 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
5669 if (!Result.isUsable()) {
5672 HadChange |= (Result.get() != SrcExprs[i]);
5673 TransformedExprs.push_back(Result.take());
5677 if (HadError) return StmtError();
5678 if (!HadChange && !getDerived().AlwaysRebuild())
5681 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
5682 AsmToks, S->getAsmString(),
5683 S->getNumOutputs(), S->getNumInputs(),
5684 S->getAllConstraints(), S->getClobbers(),
5685 TransformedExprs, S->getEndLoc());
5688 template<typename Derived>
5690 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
5691 // Transform the body of the @try.
5692 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
5693 if (TryBody.isInvalid())
5696 // Transform the @catch statements (if present).
5697 bool AnyCatchChanged = false;
5698 SmallVector<Stmt*, 8> CatchStmts;
5699 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
5700 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
5701 if (Catch.isInvalid())
5703 if (Catch.get() != S->getCatchStmt(I))
5704 AnyCatchChanged = true;
5705 CatchStmts.push_back(Catch.release());
5708 // Transform the @finally statement (if present).
5710 if (S->getFinallyStmt()) {
5711 Finally = getDerived().TransformStmt(S->getFinallyStmt());
5712 if (Finally.isInvalid())
5716 // If nothing changed, just retain this statement.
5717 if (!getDerived().AlwaysRebuild() &&
5718 TryBody.get() == S->getTryBody() &&
5720 Finally.get() == S->getFinallyStmt())
5721 return SemaRef.Owned(S);
5723 // Build a new statement.
5724 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
5725 CatchStmts, Finally.get());
5728 template<typename Derived>
5730 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
5731 // Transform the @catch parameter, if there is one.
5733 if (VarDecl *FromVar = S->getCatchParamDecl()) {
5734 TypeSourceInfo *TSInfo = 0;
5735 if (FromVar->getTypeSourceInfo()) {
5736 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
5743 T = TSInfo->getType();
5745 T = getDerived().TransformType(FromVar->getType());
5750 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
5755 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
5756 if (Body.isInvalid())
5759 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
5764 template<typename Derived>
5766 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
5767 // Transform the body.
5768 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
5769 if (Body.isInvalid())
5772 // If nothing changed, just retain this statement.
5773 if (!getDerived().AlwaysRebuild() &&
5774 Body.get() == S->getFinallyBody())
5775 return SemaRef.Owned(S);
5777 // Build a new statement.
5778 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
5782 template<typename Derived>
5784 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5786 if (S->getThrowExpr()) {
5787 Operand = getDerived().TransformExpr(S->getThrowExpr());
5788 if (Operand.isInvalid())
5792 if (!getDerived().AlwaysRebuild() &&
5793 Operand.get() == S->getThrowExpr())
5794 return getSema().Owned(S);
5796 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
5799 template<typename Derived>
5801 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
5802 ObjCAtSynchronizedStmt *S) {
5803 // Transform the object we are locking.
5804 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
5805 if (Object.isInvalid())
5808 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
5810 if (Object.isInvalid())
5813 // Transform the body.
5814 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
5815 if (Body.isInvalid())
5818 // If nothing change, just retain the current statement.
5819 if (!getDerived().AlwaysRebuild() &&
5820 Object.get() == S->getSynchExpr() &&
5821 Body.get() == S->getSynchBody())
5822 return SemaRef.Owned(S);
5824 // Build a new statement.
5825 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
5826 Object.get(), Body.get());
5829 template<typename Derived>
5831 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
5832 ObjCAutoreleasePoolStmt *S) {
5833 // Transform the body.
5834 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
5835 if (Body.isInvalid())
5838 // If nothing changed, just retain this statement.
5839 if (!getDerived().AlwaysRebuild() &&
5840 Body.get() == S->getSubStmt())
5841 return SemaRef.Owned(S);
5843 // Build a new statement.
5844 return getDerived().RebuildObjCAutoreleasePoolStmt(
5845 S->getAtLoc(), Body.get());
5848 template<typename Derived>
5850 TreeTransform<Derived>::TransformObjCForCollectionStmt(
5851 ObjCForCollectionStmt *S) {
5852 // Transform the element statement.
5853 StmtResult Element = getDerived().TransformStmt(S->getElement());
5854 if (Element.isInvalid())
5857 // Transform the collection expression.
5858 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
5859 if (Collection.isInvalid())
5862 // Transform the body.
5863 StmtResult Body = getDerived().TransformStmt(S->getBody());
5864 if (Body.isInvalid())
5867 // If nothing changed, just retain this statement.
5868 if (!getDerived().AlwaysRebuild() &&
5869 Element.get() == S->getElement() &&
5870 Collection.get() == S->getCollection() &&
5871 Body.get() == S->getBody())
5872 return SemaRef.Owned(S);
5874 // Build a new statement.
5875 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
5883 template<typename Derived>
5885 TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
5886 // Transform the exception declaration, if any.
5888 if (S->getExceptionDecl()) {
5889 VarDecl *ExceptionDecl = S->getExceptionDecl();
5890 TypeSourceInfo *T = getDerived().TransformType(
5891 ExceptionDecl->getTypeSourceInfo());
5895 Var = getDerived().RebuildExceptionDecl(ExceptionDecl, T,
5896 ExceptionDecl->getInnerLocStart(),
5897 ExceptionDecl->getLocation(),
5898 ExceptionDecl->getIdentifier());
5899 if (!Var || Var->isInvalidDecl())
5903 // Transform the actual exception handler.
5904 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
5905 if (Handler.isInvalid())
5908 if (!getDerived().AlwaysRebuild() &&
5910 Handler.get() == S->getHandlerBlock())
5911 return SemaRef.Owned(S);
5913 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(),
5918 template<typename Derived>
5920 TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
5921 // Transform the try block itself.
5923 = getDerived().TransformCompoundStmt(S->getTryBlock());
5924 if (TryBlock.isInvalid())
5927 // Transform the handlers.
5928 bool HandlerChanged = false;
5929 SmallVector<Stmt*, 8> Handlers;
5930 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
5932 = getDerived().TransformCXXCatchStmt(S->getHandler(I));
5933 if (Handler.isInvalid())
5936 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
5937 Handlers.push_back(Handler.takeAs<Stmt>());
5940 if (!getDerived().AlwaysRebuild() &&
5941 TryBlock.get() == S->getTryBlock() &&
5943 return SemaRef.Owned(S);
5945 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
5949 template<typename Derived>
5951 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
5952 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
5953 if (Range.isInvalid())
5956 StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
5957 if (BeginEnd.isInvalid())
5960 ExprResult Cond = getDerived().TransformExpr(S->getCond());
5961 if (Cond.isInvalid())
5964 Cond = SemaRef.CheckBooleanCondition(Cond.take(), S->getColonLoc());
5965 if (Cond.isInvalid())
5968 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.take());
5970 ExprResult Inc = getDerived().TransformExpr(S->getInc());
5971 if (Inc.isInvalid())
5974 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.take());
5976 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
5977 if (LoopVar.isInvalid())
5980 StmtResult NewStmt = S;
5981 if (getDerived().AlwaysRebuild() ||
5982 Range.get() != S->getRangeStmt() ||
5983 BeginEnd.get() != S->getBeginEndStmt() ||
5984 Cond.get() != S->getCond() ||
5985 Inc.get() != S->getInc() ||
5986 LoopVar.get() != S->getLoopVarStmt()) {
5987 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
5988 S->getColonLoc(), Range.get(),
5989 BeginEnd.get(), Cond.get(),
5990 Inc.get(), LoopVar.get(),
5992 if (NewStmt.isInvalid())
5996 StmtResult Body = getDerived().TransformStmt(S->getBody());
5997 if (Body.isInvalid())
6000 // Body has changed but we didn't rebuild the for-range statement. Rebuild
6001 // it now so we have a new statement to attach the body to.
6002 if (Body.get() != S->getBody() && NewStmt.get() == S) {
6003 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6004 S->getColonLoc(), Range.get(),
6005 BeginEnd.get(), Cond.get(),
6006 Inc.get(), LoopVar.get(),
6008 if (NewStmt.isInvalid())
6012 if (NewStmt.get() == S)
6013 return SemaRef.Owned(S);
6015 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
6018 template<typename Derived>
6020 TreeTransform<Derived>::TransformMSDependentExistsStmt(
6021 MSDependentExistsStmt *S) {
6022 // Transform the nested-name-specifier, if any.
6023 NestedNameSpecifierLoc QualifierLoc;
6024 if (S->getQualifierLoc()) {
6026 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
6031 // Transform the declaration name.
6032 DeclarationNameInfo NameInfo = S->getNameInfo();
6033 if (NameInfo.getName()) {
6034 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
6035 if (!NameInfo.getName())
6039 // Check whether anything changed.
6040 if (!getDerived().AlwaysRebuild() &&
6041 QualifierLoc == S->getQualifierLoc() &&
6042 NameInfo.getName() == S->getNameInfo().getName())
6045 // Determine whether this name exists, if we can.
6047 SS.Adopt(QualifierLoc);
6048 bool Dependent = false;
6049 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/0, SS, NameInfo)) {
6050 case Sema::IER_Exists:
6051 if (S->isIfExists())
6054 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6056 case Sema::IER_DoesNotExist:
6057 if (S->isIfNotExists())
6060 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6062 case Sema::IER_Dependent:
6066 case Sema::IER_Error:
6070 // We need to continue with the instantiation, so do so now.
6071 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
6072 if (SubStmt.isInvalid())
6075 // If we have resolved the name, just transform to the substatement.
6079 // The name is still dependent, so build a dependent expression again.
6080 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
6087 template<typename Derived>
6089 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
6090 NestedNameSpecifierLoc QualifierLoc;
6091 if (E->getQualifierLoc()) {
6093 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6098 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
6099 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
6103 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
6104 if (Base.isInvalid())
6107 return new (SemaRef.getASTContext())
6108 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
6109 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
6110 QualifierLoc, E->getMemberLoc());
6113 template<typename Derived>
6115 TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
6116 StmtResult TryBlock; // = getDerived().TransformCompoundStmt(S->getTryBlock());
6117 if(TryBlock.isInvalid()) return StmtError();
6119 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
6120 if(!getDerived().AlwaysRebuild() &&
6121 TryBlock.get() == S->getTryBlock() &&
6122 Handler.get() == S->getHandler())
6123 return SemaRef.Owned(S);
6125 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(),
6131 template<typename Derived>
6133 TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
6134 StmtResult Block; // = getDerived().TransformCompoundStatement(S->getBlock());
6135 if(Block.isInvalid()) return StmtError();
6137 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(),
6141 template<typename Derived>
6143 TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
6144 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
6145 if(FilterExpr.isInvalid()) return StmtError();
6147 StmtResult Block; // = getDerived().TransformCompoundStatement(S->getBlock());
6148 if(Block.isInvalid()) return StmtError();
6150 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(),
6155 template<typename Derived>
6157 TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
6158 if(isa<SEHFinallyStmt>(Handler))
6159 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
6161 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
6164 //===----------------------------------------------------------------------===//
6165 // Expression transformation
6166 //===----------------------------------------------------------------------===//
6167 template<typename Derived>
6169 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
6170 return SemaRef.Owned(E);
6173 template<typename Derived>
6175 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
6176 NestedNameSpecifierLoc QualifierLoc;
6177 if (E->getQualifierLoc()) {
6179 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6185 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
6190 DeclarationNameInfo NameInfo = E->getNameInfo();
6191 if (NameInfo.getName()) {
6192 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
6193 if (!NameInfo.getName())
6197 if (!getDerived().AlwaysRebuild() &&
6198 QualifierLoc == E->getQualifierLoc() &&
6199 ND == E->getDecl() &&
6200 NameInfo.getName() == E->getDecl()->getDeclName() &&
6201 !E->hasExplicitTemplateArgs()) {
6203 // Mark it referenced in the new context regardless.
6204 // FIXME: this is a bit instantiation-specific.
6205 SemaRef.MarkDeclRefReferenced(E);
6207 return SemaRef.Owned(E);
6210 TemplateArgumentListInfo TransArgs, *TemplateArgs = 0;
6211 if (E->hasExplicitTemplateArgs()) {
6212 TemplateArgs = &TransArgs;
6213 TransArgs.setLAngleLoc(E->getLAngleLoc());
6214 TransArgs.setRAngleLoc(E->getRAngleLoc());
6215 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
6216 E->getNumTemplateArgs(),
6221 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
6225 template<typename Derived>
6227 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
6228 return SemaRef.Owned(E);
6231 template<typename Derived>
6233 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
6234 return SemaRef.Owned(E);
6237 template<typename Derived>
6239 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
6240 return SemaRef.Owned(E);
6243 template<typename Derived>
6245 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
6246 return SemaRef.Owned(E);
6249 template<typename Derived>
6251 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
6252 return SemaRef.Owned(E);
6255 template<typename Derived>
6257 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
6258 if (FunctionDecl *FD = E->getDirectCallee())
6259 SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
6260 return SemaRef.MaybeBindToTemporary(E);
6263 template<typename Derived>
6265 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
6266 ExprResult ControllingExpr =
6267 getDerived().TransformExpr(E->getControllingExpr());
6268 if (ControllingExpr.isInvalid())
6271 SmallVector<Expr *, 4> AssocExprs;
6272 SmallVector<TypeSourceInfo *, 4> AssocTypes;
6273 for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
6274 TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
6276 TypeSourceInfo *AssocType = getDerived().TransformType(TS);
6279 AssocTypes.push_back(AssocType);
6281 AssocTypes.push_back(0);
6284 ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
6285 if (AssocExpr.isInvalid())
6287 AssocExprs.push_back(AssocExpr.release());
6290 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
6293 ControllingExpr.release(),
6299 template<typename Derived>
6301 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
6302 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
6303 if (SubExpr.isInvalid())
6306 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
6307 return SemaRef.Owned(E);
6309 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
6313 /// \brief The operand of a unary address-of operator has special rules: it's
6314 /// allowed to refer to a non-static member of a class even if there's no 'this'
6315 /// object available.
6316 template<typename Derived>
6318 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
6319 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
6320 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true);
6322 return getDerived().TransformExpr(E);
6325 template<typename Derived>
6327 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
6328 ExprResult SubExpr = TransformAddressOfOperand(E->getSubExpr());
6329 if (SubExpr.isInvalid())
6332 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
6333 return SemaRef.Owned(E);
6335 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
6340 template<typename Derived>
6342 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
6343 // Transform the type.
6344 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
6348 // Transform all of the components into components similar to what the
6350 // FIXME: It would be slightly more efficient in the non-dependent case to
6351 // just map FieldDecls, rather than requiring the rebuilder to look for
6352 // the fields again. However, __builtin_offsetof is rare enough in
6353 // template code that we don't care.
6354 bool ExprChanged = false;
6355 typedef Sema::OffsetOfComponent Component;
6356 typedef OffsetOfExpr::OffsetOfNode Node;
6357 SmallVector<Component, 4> Components;
6358 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
6359 const Node &ON = E->getComponent(I);
6361 Comp.isBrackets = true;
6362 Comp.LocStart = ON.getSourceRange().getBegin();
6363 Comp.LocEnd = ON.getSourceRange().getEnd();
6364 switch (ON.getKind()) {
6366 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
6367 ExprResult Index = getDerived().TransformExpr(FromIndex);
6368 if (Index.isInvalid())
6371 ExprChanged = ExprChanged || Index.get() != FromIndex;
6372 Comp.isBrackets = true;
6373 Comp.U.E = Index.get();
6378 case Node::Identifier:
6379 Comp.isBrackets = false;
6380 Comp.U.IdentInfo = ON.getFieldName();
6381 if (!Comp.U.IdentInfo)
6387 // Will be recomputed during the rebuild.
6391 Components.push_back(Comp);
6394 // If nothing changed, retain the existing expression.
6395 if (!getDerived().AlwaysRebuild() &&
6396 Type == E->getTypeSourceInfo() &&
6398 return SemaRef.Owned(E);
6400 // Build a new offsetof expression.
6401 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
6402 Components.data(), Components.size(),
6406 template<typename Derived>
6408 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
6409 assert(getDerived().AlreadyTransformed(E->getType()) &&
6410 "opaque value expression requires transformation");
6411 return SemaRef.Owned(E);
6414 template<typename Derived>
6416 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
6417 // Rebuild the syntactic form. The original syntactic form has
6418 // opaque-value expressions in it, so strip those away and rebuild
6419 // the result. This is a really awful way of doing this, but the
6420 // better solution (rebuilding the semantic expressions and
6421 // rebinding OVEs as necessary) doesn't work; we'd need
6422 // TreeTransform to not strip away implicit conversions.
6423 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
6424 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
6425 if (result.isInvalid()) return ExprError();
6427 // If that gives us a pseudo-object result back, the pseudo-object
6428 // expression must have been an lvalue-to-rvalue conversion which we
6430 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
6431 result = SemaRef.checkPseudoObjectRValue(result.take());
6436 template<typename Derived>
6438 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
6439 UnaryExprOrTypeTraitExpr *E) {
6440 if (E->isArgumentType()) {
6441 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
6443 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
6447 if (!getDerived().AlwaysRebuild() && OldT == NewT)
6448 return SemaRef.Owned(E);
6450 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
6452 E->getSourceRange());
6455 // C++0x [expr.sizeof]p1:
6456 // The operand is either an expression, which is an unevaluated operand
6458 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
6459 Sema::ReuseLambdaContextDecl);
6461 ExprResult SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
6462 if (SubExpr.isInvalid())
6465 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
6466 return SemaRef.Owned(E);
6468 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
6469 E->getOperatorLoc(),
6471 E->getSourceRange());
6474 template<typename Derived>
6476 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
6477 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
6478 if (LHS.isInvalid())
6481 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
6482 if (RHS.isInvalid())
6486 if (!getDerived().AlwaysRebuild() &&
6487 LHS.get() == E->getLHS() &&
6488 RHS.get() == E->getRHS())
6489 return SemaRef.Owned(E);
6491 return getDerived().RebuildArraySubscriptExpr(LHS.get(),
6492 /*FIXME:*/E->getLHS()->getLocStart(),
6494 E->getRBracketLoc());
6497 template<typename Derived>
6499 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
6500 // Transform the callee.
6501 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
6502 if (Callee.isInvalid())
6505 // Transform arguments.
6506 bool ArgChanged = false;
6507 SmallVector<Expr*, 8> Args;
6508 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
6512 if (!getDerived().AlwaysRebuild() &&
6513 Callee.get() == E->getCallee() &&
6515 return SemaRef.MaybeBindToTemporary(E);
6517 // FIXME: Wrong source location information for the '('.
6518 SourceLocation FakeLParenLoc
6519 = ((Expr *)Callee.get())->getSourceRange().getBegin();
6520 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
6525 template<typename Derived>
6527 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
6528 ExprResult Base = getDerived().TransformExpr(E->getBase());
6529 if (Base.isInvalid())
6532 NestedNameSpecifierLoc QualifierLoc;
6533 if (E->hasQualifier()) {
6535 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6540 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
6543 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
6544 E->getMemberDecl()));
6548 NamedDecl *FoundDecl = E->getFoundDecl();
6549 if (FoundDecl == E->getMemberDecl()) {
6552 FoundDecl = cast_or_null<NamedDecl>(
6553 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
6558 if (!getDerived().AlwaysRebuild() &&
6559 Base.get() == E->getBase() &&
6560 QualifierLoc == E->getQualifierLoc() &&
6561 Member == E->getMemberDecl() &&
6562 FoundDecl == E->getFoundDecl() &&
6563 !E->hasExplicitTemplateArgs()) {
6565 // Mark it referenced in the new context regardless.
6566 // FIXME: this is a bit instantiation-specific.
6567 SemaRef.MarkMemberReferenced(E);
6569 return SemaRef.Owned(E);
6572 TemplateArgumentListInfo TransArgs;
6573 if (E->hasExplicitTemplateArgs()) {
6574 TransArgs.setLAngleLoc(E->getLAngleLoc());
6575 TransArgs.setRAngleLoc(E->getRAngleLoc());
6576 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
6577 E->getNumTemplateArgs(),
6582 // FIXME: Bogus source location for the operator
6583 SourceLocation FakeOperatorLoc
6584 = SemaRef.PP.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
6586 // FIXME: to do this check properly, we will need to preserve the
6587 // first-qualifier-in-scope here, just in case we had a dependent
6588 // base (and therefore couldn't do the check) and a
6589 // nested-name-qualifier (and therefore could do the lookup).
6590 NamedDecl *FirstQualifierInScope = 0;
6592 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
6596 E->getMemberNameInfo(),
6599 (E->hasExplicitTemplateArgs()
6601 FirstQualifierInScope);
6604 template<typename Derived>
6606 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
6607 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
6608 if (LHS.isInvalid())
6611 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
6612 if (RHS.isInvalid())
6615 if (!getDerived().AlwaysRebuild() &&
6616 LHS.get() == E->getLHS() &&
6617 RHS.get() == E->getRHS())
6618 return SemaRef.Owned(E);
6620 Sema::FPContractStateRAII FPContractState(getSema());
6621 getSema().FPFeatures.fp_contract = E->isFPContractable();
6623 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
6624 LHS.get(), RHS.get());
6627 template<typename Derived>
6629 TreeTransform<Derived>::TransformCompoundAssignOperator(
6630 CompoundAssignOperator *E) {
6631 return getDerived().TransformBinaryOperator(E);
6634 template<typename Derived>
6635 ExprResult TreeTransform<Derived>::
6636 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
6637 // Just rebuild the common and RHS expressions and see whether we
6640 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
6641 if (commonExpr.isInvalid())
6644 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
6645 if (rhs.isInvalid())
6648 if (!getDerived().AlwaysRebuild() &&
6649 commonExpr.get() == e->getCommon() &&
6650 rhs.get() == e->getFalseExpr())
6651 return SemaRef.Owned(e);
6653 return getDerived().RebuildConditionalOperator(commonExpr.take(),
6654 e->getQuestionLoc(),
6660 template<typename Derived>
6662 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
6663 ExprResult Cond = getDerived().TransformExpr(E->getCond());
6664 if (Cond.isInvalid())
6667 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
6668 if (LHS.isInvalid())
6671 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
6672 if (RHS.isInvalid())
6675 if (!getDerived().AlwaysRebuild() &&
6676 Cond.get() == E->getCond() &&
6677 LHS.get() == E->getLHS() &&
6678 RHS.get() == E->getRHS())
6679 return SemaRef.Owned(E);
6681 return getDerived().RebuildConditionalOperator(Cond.get(),
6682 E->getQuestionLoc(),
6688 template<typename Derived>
6690 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
6691 // Implicit casts are eliminated during transformation, since they
6692 // will be recomputed by semantic analysis after transformation.
6693 return getDerived().TransformExpr(E->getSubExprAsWritten());
6696 template<typename Derived>
6698 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
6699 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
6704 = getDerived().TransformExpr(E->getSubExprAsWritten());
6705 if (SubExpr.isInvalid())
6708 if (!getDerived().AlwaysRebuild() &&
6709 Type == E->getTypeInfoAsWritten() &&
6710 SubExpr.get() == E->getSubExpr())
6711 return SemaRef.Owned(E);
6713 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
6719 template<typename Derived>
6721 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
6722 TypeSourceInfo *OldT = E->getTypeSourceInfo();
6723 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
6727 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
6728 if (Init.isInvalid())
6731 if (!getDerived().AlwaysRebuild() &&
6733 Init.get() == E->getInitializer())
6734 return SemaRef.MaybeBindToTemporary(E);
6736 // Note: the expression type doesn't necessarily match the
6737 // type-as-written, but that's okay, because it should always be
6738 // derivable from the initializer.
6740 return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
6741 /*FIXME:*/E->getInitializer()->getLocEnd(),
6745 template<typename Derived>
6747 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
6748 ExprResult Base = getDerived().TransformExpr(E->getBase());
6749 if (Base.isInvalid())
6752 if (!getDerived().AlwaysRebuild() &&
6753 Base.get() == E->getBase())
6754 return SemaRef.Owned(E);
6756 // FIXME: Bad source location
6757 SourceLocation FakeOperatorLoc
6758 = SemaRef.PP.getLocForEndOfToken(E->getBase()->getLocEnd());
6759 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
6760 E->getAccessorLoc(),
6764 template<typename Derived>
6766 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
6767 bool InitChanged = false;
6769 SmallVector<Expr*, 4> Inits;
6770 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
6771 Inits, &InitChanged))
6774 if (!getDerived().AlwaysRebuild() && !InitChanged)
6775 return SemaRef.Owned(E);
6777 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
6778 E->getRBraceLoc(), E->getType());
6781 template<typename Derived>
6783 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
6786 // transform the initializer value
6787 ExprResult Init = getDerived().TransformExpr(E->getInit());
6788 if (Init.isInvalid())
6791 // transform the designators.
6792 SmallVector<Expr*, 4> ArrayExprs;
6793 bool ExprChanged = false;
6794 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
6795 DEnd = E->designators_end();
6797 if (D->isFieldDesignator()) {
6798 Desig.AddDesignator(Designator::getField(D->getFieldName(),
6804 if (D->isArrayDesignator()) {
6805 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
6806 if (Index.isInvalid())
6809 Desig.AddDesignator(Designator::getArray(Index.get(),
6810 D->getLBracketLoc()));
6812 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
6813 ArrayExprs.push_back(Index.release());
6817 assert(D->isArrayRangeDesignator() && "New kind of designator?");
6819 = getDerived().TransformExpr(E->getArrayRangeStart(*D));
6820 if (Start.isInvalid())
6823 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
6824 if (End.isInvalid())
6827 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
6829 D->getLBracketLoc(),
6830 D->getEllipsisLoc()));
6832 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
6833 End.get() != E->getArrayRangeEnd(*D);
6835 ArrayExprs.push_back(Start.release());
6836 ArrayExprs.push_back(End.release());
6839 if (!getDerived().AlwaysRebuild() &&
6840 Init.get() == E->getInit() &&
6842 return SemaRef.Owned(E);
6844 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
6845 E->getEqualOrColonLoc(),
6846 E->usesGNUSyntax(), Init.get());
6849 template<typename Derived>
6851 TreeTransform<Derived>::TransformImplicitValueInitExpr(
6852 ImplicitValueInitExpr *E) {
6853 TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
6855 // FIXME: Will we ever have proper type location here? Will we actually
6856 // need to transform the type?
6857 QualType T = getDerived().TransformType(E->getType());
6861 if (!getDerived().AlwaysRebuild() &&
6863 return SemaRef.Owned(E);
6865 return getDerived().RebuildImplicitValueInitExpr(T);
6868 template<typename Derived>
6870 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
6871 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
6875 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
6876 if (SubExpr.isInvalid())
6879 if (!getDerived().AlwaysRebuild() &&
6880 TInfo == E->getWrittenTypeInfo() &&
6881 SubExpr.get() == E->getSubExpr())
6882 return SemaRef.Owned(E);
6884 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
6885 TInfo, E->getRParenLoc());
6888 template<typename Derived>
6890 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
6891 bool ArgumentChanged = false;
6892 SmallVector<Expr*, 4> Inits;
6893 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
6897 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
6902 /// \brief Transform an address-of-label expression.
6904 /// By default, the transformation of an address-of-label expression always
6905 /// rebuilds the expression, so that the label identifier can be resolved to
6906 /// the corresponding label statement by semantic analysis.
6907 template<typename Derived>
6909 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
6910 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
6915 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
6916 cast<LabelDecl>(LD));
6919 template<typename Derived>
6921 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
6922 SemaRef.ActOnStartStmtExpr();
6924 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
6925 if (SubStmt.isInvalid()) {
6926 SemaRef.ActOnStmtExprError();
6930 if (!getDerived().AlwaysRebuild() &&
6931 SubStmt.get() == E->getSubStmt()) {
6932 // Calling this an 'error' is unintuitive, but it does the right thing.
6933 SemaRef.ActOnStmtExprError();
6934 return SemaRef.MaybeBindToTemporary(E);
6937 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
6942 template<typename Derived>
6944 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
6945 ExprResult Cond = getDerived().TransformExpr(E->getCond());
6946 if (Cond.isInvalid())
6949 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
6950 if (LHS.isInvalid())
6953 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
6954 if (RHS.isInvalid())
6957 if (!getDerived().AlwaysRebuild() &&
6958 Cond.get() == E->getCond() &&
6959 LHS.get() == E->getLHS() &&
6960 RHS.get() == E->getRHS())
6961 return SemaRef.Owned(E);
6963 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
6964 Cond.get(), LHS.get(), RHS.get(),
6968 template<typename Derived>
6970 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
6971 return SemaRef.Owned(E);
6974 template<typename Derived>
6976 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
6977 switch (E->getOperator()) {
6981 case OO_Array_Delete:
6982 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
6985 // This is a call to an object's operator().
6986 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
6988 // Transform the object itself.
6989 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
6990 if (Object.isInvalid())
6993 // FIXME: Poor location information
6994 SourceLocation FakeLParenLoc
6995 = SemaRef.PP.getLocForEndOfToken(
6996 static_cast<Expr *>(Object.get())->getLocEnd());
6998 // Transform the call arguments.
6999 SmallVector<Expr*, 8> Args;
7000 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
7004 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
7009 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7011 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
7012 #include "clang/Basic/OperatorKinds.def"
7017 case OO_Conditional:
7018 llvm_unreachable("conditional operator is not actually overloadable");
7021 case NUM_OVERLOADED_OPERATORS:
7022 llvm_unreachable("not an overloaded operator?");
7025 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
7026 if (Callee.isInvalid())
7030 if (E->getOperator() == OO_Amp)
7031 First = getDerived().TransformAddressOfOperand(E->getArg(0));
7033 First = getDerived().TransformExpr(E->getArg(0));
7034 if (First.isInvalid())
7038 if (E->getNumArgs() == 2) {
7039 Second = getDerived().TransformExpr(E->getArg(1));
7040 if (Second.isInvalid())
7044 if (!getDerived().AlwaysRebuild() &&
7045 Callee.get() == E->getCallee() &&
7046 First.get() == E->getArg(0) &&
7047 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
7048 return SemaRef.MaybeBindToTemporary(E);
7050 Sema::FPContractStateRAII FPContractState(getSema());
7051 getSema().FPFeatures.fp_contract = E->isFPContractable();
7053 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
7054 E->getOperatorLoc(),
7060 template<typename Derived>
7062 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
7063 return getDerived().TransformCallExpr(E);
7066 template<typename Derived>
7068 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
7069 // Transform the callee.
7070 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
7071 if (Callee.isInvalid())
7074 // Transform exec config.
7075 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
7079 // Transform arguments.
7080 bool ArgChanged = false;
7081 SmallVector<Expr*, 8> Args;
7082 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
7086 if (!getDerived().AlwaysRebuild() &&
7087 Callee.get() == E->getCallee() &&
7089 return SemaRef.MaybeBindToTemporary(E);
7091 // FIXME: Wrong source location information for the '('.
7092 SourceLocation FakeLParenLoc
7093 = ((Expr *)Callee.get())->getSourceRange().getBegin();
7094 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
7096 E->getRParenLoc(), EC.get());
7099 template<typename Derived>
7101 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
7102 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
7107 = getDerived().TransformExpr(E->getSubExprAsWritten());
7108 if (SubExpr.isInvalid())
7111 if (!getDerived().AlwaysRebuild() &&
7112 Type == E->getTypeInfoAsWritten() &&
7113 SubExpr.get() == E->getSubExpr())
7114 return SemaRef.Owned(E);
7115 return getDerived().RebuildCXXNamedCastExpr(E->getOperatorLoc(),
7117 E->getAngleBrackets().getBegin(),
7119 E->getAngleBrackets().getEnd(),
7120 // FIXME. this should be '(' location
7121 E->getAngleBrackets().getEnd(),
7126 template<typename Derived>
7128 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
7129 return getDerived().TransformCXXNamedCastExpr(E);
7132 template<typename Derived>
7134 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
7135 return getDerived().TransformCXXNamedCastExpr(E);
7138 template<typename Derived>
7140 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
7141 CXXReinterpretCastExpr *E) {
7142 return getDerived().TransformCXXNamedCastExpr(E);
7145 template<typename Derived>
7147 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
7148 return getDerived().TransformCXXNamedCastExpr(E);
7151 template<typename Derived>
7153 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
7154 CXXFunctionalCastExpr *E) {
7155 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
7160 = getDerived().TransformExpr(E->getSubExprAsWritten());
7161 if (SubExpr.isInvalid())
7164 if (!getDerived().AlwaysRebuild() &&
7165 Type == E->getTypeInfoAsWritten() &&
7166 SubExpr.get() == E->getSubExpr())
7167 return SemaRef.Owned(E);
7169 return getDerived().RebuildCXXFunctionalCastExpr(Type,
7170 /*FIXME:*/E->getSubExpr()->getLocStart(),
7175 template<typename Derived>
7177 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
7178 if (E->isTypeOperand()) {
7179 TypeSourceInfo *TInfo
7180 = getDerived().TransformType(E->getTypeOperandSourceInfo());
7184 if (!getDerived().AlwaysRebuild() &&
7185 TInfo == E->getTypeOperandSourceInfo())
7186 return SemaRef.Owned(E);
7188 return getDerived().RebuildCXXTypeidExpr(E->getType(),
7194 // We don't know whether the subexpression is potentially evaluated until
7195 // after we perform semantic analysis. We speculatively assume it is
7196 // unevaluated; it will get fixed later if the subexpression is in fact
7197 // potentially evaluated.
7198 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
7199 Sema::ReuseLambdaContextDecl);
7201 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
7202 if (SubExpr.isInvalid())
7205 if (!getDerived().AlwaysRebuild() &&
7206 SubExpr.get() == E->getExprOperand())
7207 return SemaRef.Owned(E);
7209 return getDerived().RebuildCXXTypeidExpr(E->getType(),
7215 template<typename Derived>
7217 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
7218 if (E->isTypeOperand()) {
7219 TypeSourceInfo *TInfo
7220 = getDerived().TransformType(E->getTypeOperandSourceInfo());
7224 if (!getDerived().AlwaysRebuild() &&
7225 TInfo == E->getTypeOperandSourceInfo())
7226 return SemaRef.Owned(E);
7228 return getDerived().RebuildCXXUuidofExpr(E->getType(),
7234 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
7236 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
7237 if (SubExpr.isInvalid())
7240 if (!getDerived().AlwaysRebuild() &&
7241 SubExpr.get() == E->getExprOperand())
7242 return SemaRef.Owned(E);
7244 return getDerived().RebuildCXXUuidofExpr(E->getType(),
7250 template<typename Derived>
7252 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
7253 return SemaRef.Owned(E);
7256 template<typename Derived>
7258 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
7259 CXXNullPtrLiteralExpr *E) {
7260 return SemaRef.Owned(E);
7263 template<typename Derived>
7265 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
7266 DeclContext *DC = getSema().getFunctionLevelDeclContext();
7268 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
7269 T = MD->getThisType(getSema().Context);
7270 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
7271 T = getSema().Context.getPointerType(
7272 getSema().Context.getRecordType(Record));
7274 assert(SemaRef.Context.getDiagnostics().hasErrorOccurred() &&
7275 "this in the wrong scope?");
7279 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
7280 // Make sure that we capture 'this'.
7281 getSema().CheckCXXThisCapture(E->getLocStart());
7282 return SemaRef.Owned(E);
7285 return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
7288 template<typename Derived>
7290 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
7291 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
7292 if (SubExpr.isInvalid())
7295 if (!getDerived().AlwaysRebuild() &&
7296 SubExpr.get() == E->getSubExpr())
7297 return SemaRef.Owned(E);
7299 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
7300 E->isThrownVariableInScope());
7303 template<typename Derived>
7305 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
7307 = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
7312 if (!getDerived().AlwaysRebuild() &&
7313 Param == E->getParam())
7314 return SemaRef.Owned(E);
7316 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
7319 template<typename Derived>
7321 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
7323 = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
7328 if (!getDerived().AlwaysRebuild() && Field == E->getField())
7329 return SemaRef.Owned(E);
7331 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
7334 template<typename Derived>
7336 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
7337 CXXScalarValueInitExpr *E) {
7338 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
7342 if (!getDerived().AlwaysRebuild() &&
7343 T == E->getTypeSourceInfo())
7344 return SemaRef.Owned(E);
7346 return getDerived().RebuildCXXScalarValueInitExpr(T,
7347 /*FIXME:*/T->getTypeLoc().getEndLoc(),
7351 template<typename Derived>
7353 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
7354 // Transform the type that we're allocating
7355 TypeSourceInfo *AllocTypeInfo
7356 = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
7360 // Transform the size of the array we're allocating (if any).
7361 ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
7362 if (ArraySize.isInvalid())
7365 // Transform the placement arguments (if any).
7366 bool ArgumentChanged = false;
7367 SmallVector<Expr*, 8> PlacementArgs;
7368 if (getDerived().TransformExprs(E->getPlacementArgs(),
7369 E->getNumPlacementArgs(), true,
7370 PlacementArgs, &ArgumentChanged))
7373 // Transform the initializer (if any).
7374 Expr *OldInit = E->getInitializer();
7377 NewInit = getDerived().TransformExpr(OldInit);
7378 if (NewInit.isInvalid())
7381 // Transform new operator and delete operator.
7382 FunctionDecl *OperatorNew = 0;
7383 if (E->getOperatorNew()) {
7384 OperatorNew = cast_or_null<FunctionDecl>(
7385 getDerived().TransformDecl(E->getLocStart(),
7386 E->getOperatorNew()));
7391 FunctionDecl *OperatorDelete = 0;
7392 if (E->getOperatorDelete()) {
7393 OperatorDelete = cast_or_null<FunctionDecl>(
7394 getDerived().TransformDecl(E->getLocStart(),
7395 E->getOperatorDelete()));
7396 if (!OperatorDelete)
7400 if (!getDerived().AlwaysRebuild() &&
7401 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
7402 ArraySize.get() == E->getArraySize() &&
7403 NewInit.get() == OldInit &&
7404 OperatorNew == E->getOperatorNew() &&
7405 OperatorDelete == E->getOperatorDelete() &&
7407 // Mark any declarations we need as referenced.
7408 // FIXME: instantiation-specific.
7410 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
7412 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
7414 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
7415 QualType ElementType
7416 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
7417 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
7418 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
7419 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
7420 SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
7425 return SemaRef.Owned(E);
7428 QualType AllocType = AllocTypeInfo->getType();
7429 if (!ArraySize.get()) {
7430 // If no array size was specified, but the new expression was
7431 // instantiated with an array type (e.g., "new T" where T is
7432 // instantiated with "int[4]"), extract the outer bound from the
7433 // array type as our array size. We do this with constant and
7434 // dependently-sized array types.
7435 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
7438 } else if (const ConstantArrayType *ConsArrayT
7439 = dyn_cast<ConstantArrayType>(ArrayT)) {
7441 = SemaRef.Owned(IntegerLiteral::Create(SemaRef.Context,
7442 ConsArrayT->getSize(),
7443 SemaRef.Context.getSizeType(),
7444 /*FIXME:*/E->getLocStart()));
7445 AllocType = ConsArrayT->getElementType();
7446 } else if (const DependentSizedArrayType *DepArrayT
7447 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
7448 if (DepArrayT->getSizeExpr()) {
7449 ArraySize = SemaRef.Owned(DepArrayT->getSizeExpr());
7450 AllocType = DepArrayT->getElementType();
7455 return getDerived().RebuildCXXNewExpr(E->getLocStart(),
7457 /*FIXME:*/E->getLocStart(),
7459 /*FIXME:*/E->getLocStart(),
7460 E->getTypeIdParens(),
7464 E->getDirectInitRange(),
7468 template<typename Derived>
7470 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
7471 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
7472 if (Operand.isInvalid())
7475 // Transform the delete operator, if known.
7476 FunctionDecl *OperatorDelete = 0;
7477 if (E->getOperatorDelete()) {
7478 OperatorDelete = cast_or_null<FunctionDecl>(
7479 getDerived().TransformDecl(E->getLocStart(),
7480 E->getOperatorDelete()));
7481 if (!OperatorDelete)
7485 if (!getDerived().AlwaysRebuild() &&
7486 Operand.get() == E->getArgument() &&
7487 OperatorDelete == E->getOperatorDelete()) {
7488 // Mark any declarations we need as referenced.
7489 // FIXME: instantiation-specific.
7491 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
7493 if (!E->getArgument()->isTypeDependent()) {
7494 QualType Destroyed = SemaRef.Context.getBaseElementType(
7495 E->getDestroyedType());
7496 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
7497 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
7498 SemaRef.MarkFunctionReferenced(E->getLocStart(),
7499 SemaRef.LookupDestructor(Record));
7503 return SemaRef.Owned(E);
7506 return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
7507 E->isGlobalDelete(),
7512 template<typename Derived>
7514 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
7515 CXXPseudoDestructorExpr *E) {
7516 ExprResult Base = getDerived().TransformExpr(E->getBase());
7517 if (Base.isInvalid())
7520 ParsedType ObjectTypePtr;
7521 bool MayBePseudoDestructor = false;
7522 Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
7523 E->getOperatorLoc(),
7524 E->isArrow()? tok::arrow : tok::period,
7526 MayBePseudoDestructor);
7527 if (Base.isInvalid())
7530 QualType ObjectType = ObjectTypePtr.get();
7531 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
7534 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
7539 SS.Adopt(QualifierLoc);
7541 PseudoDestructorTypeStorage Destroyed;
7542 if (E->getDestroyedTypeInfo()) {
7543 TypeSourceInfo *DestroyedTypeInfo
7544 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
7546 if (!DestroyedTypeInfo)
7548 Destroyed = DestroyedTypeInfo;
7549 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
7550 // We aren't likely to be able to resolve the identifier down to a type
7551 // now anyway, so just retain the identifier.
7552 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
7553 E->getDestroyedTypeLoc());
7555 // Look for a destructor known with the given name.
7556 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
7557 *E->getDestroyedTypeIdentifier(),
7558 E->getDestroyedTypeLoc(),
7566 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
7567 E->getDestroyedTypeLoc());
7570 TypeSourceInfo *ScopeTypeInfo = 0;
7571 if (E->getScopeTypeInfo()) {
7572 CXXScopeSpec EmptySS;
7573 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
7574 E->getScopeTypeInfo(), ObjectType, 0, EmptySS);
7579 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
7580 E->getOperatorLoc(),
7584 E->getColonColonLoc(),
7589 template<typename Derived>
7591 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
7592 UnresolvedLookupExpr *Old) {
7593 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
7594 Sema::LookupOrdinaryName);
7596 // Transform all the decls.
7597 for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
7598 E = Old->decls_end(); I != E; ++I) {
7599 NamedDecl *InstD = static_cast<NamedDecl*>(
7600 getDerived().TransformDecl(Old->getNameLoc(),
7603 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
7604 // This can happen because of dependent hiding.
7605 if (isa<UsingShadowDecl>(*I))
7611 // Expand using declarations.
7612 if (isa<UsingDecl>(InstD)) {
7613 UsingDecl *UD = cast<UsingDecl>(InstD);
7614 for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
7615 E = UD->shadow_end(); I != E; ++I)
7623 // Resolve a kind, but don't do any further analysis. If it's
7624 // ambiguous, the callee needs to deal with it.
7627 // Rebuild the nested-name qualifier, if present.
7629 if (Old->getQualifierLoc()) {
7630 NestedNameSpecifierLoc QualifierLoc
7631 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
7635 SS.Adopt(QualifierLoc);
7638 if (Old->getNamingClass()) {
7639 CXXRecordDecl *NamingClass
7640 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
7642 Old->getNamingClass()));
7646 R.setNamingClass(NamingClass);
7649 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
7651 // If we have neither explicit template arguments, nor the template keyword,
7652 // it's a normal declaration name.
7653 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid())
7654 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
7656 // If we have template arguments, rebuild them, then rebuild the
7657 // templateid expression.
7658 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
7659 if (Old->hasExplicitTemplateArgs() &&
7660 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
7661 Old->getNumTemplateArgs(),
7665 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
7666 Old->requiresADL(), &TransArgs);
7669 template<typename Derived>
7671 TreeTransform<Derived>::TransformUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
7672 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
7676 if (!getDerived().AlwaysRebuild() &&
7677 T == E->getQueriedTypeSourceInfo())
7678 return SemaRef.Owned(E);
7680 return getDerived().RebuildUnaryTypeTrait(E->getTrait(),
7686 template<typename Derived>
7688 TreeTransform<Derived>::TransformBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
7689 TypeSourceInfo *LhsT = getDerived().TransformType(E->getLhsTypeSourceInfo());
7693 TypeSourceInfo *RhsT = getDerived().TransformType(E->getRhsTypeSourceInfo());
7697 if (!getDerived().AlwaysRebuild() &&
7698 LhsT == E->getLhsTypeSourceInfo() && RhsT == E->getRhsTypeSourceInfo())
7699 return SemaRef.Owned(E);
7701 return getDerived().RebuildBinaryTypeTrait(E->getTrait(),
7707 template<typename Derived>
7709 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
7710 bool ArgChanged = false;
7711 SmallVector<TypeSourceInfo *, 4> Args;
7712 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
7713 TypeSourceInfo *From = E->getArg(I);
7714 TypeLoc FromTL = From->getTypeLoc();
7715 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
7717 TLB.reserve(FromTL.getFullDataSize());
7718 QualType To = getDerived().TransformType(TLB, FromTL);
7722 if (To == From->getType())
7723 Args.push_back(From);
7725 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
7733 // We have a pack expansion. Instantiate it.
7734 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
7735 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
7736 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7737 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
7739 // Determine whether the set of unexpanded parameter packs can and should
7742 bool RetainExpansion = false;
7743 Optional<unsigned> OrigNumExpansions =
7744 ExpansionTL.getTypePtr()->getNumExpansions();
7745 Optional<unsigned> NumExpansions = OrigNumExpansions;
7746 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
7747 PatternTL.getSourceRange(),
7749 Expand, RetainExpansion,
7754 // The transform has determined that we should perform a simple
7755 // transformation on the pack expansion, producing another pack
7757 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7760 TLB.reserve(From->getTypeLoc().getFullDataSize());
7762 QualType To = getDerived().TransformType(TLB, PatternTL);
7766 To = getDerived().RebuildPackExpansionType(To,
7767 PatternTL.getSourceRange(),
7768 ExpansionTL.getEllipsisLoc(),
7773 PackExpansionTypeLoc ToExpansionTL
7774 = TLB.push<PackExpansionTypeLoc>(To);
7775 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
7776 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
7780 // Expand the pack expansion by substituting for each argument in the
7782 for (unsigned I = 0; I != *NumExpansions; ++I) {
7783 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
7785 TLB.reserve(PatternTL.getFullDataSize());
7786 QualType To = getDerived().TransformType(TLB, PatternTL);
7790 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
7793 if (!RetainExpansion)
7796 // If we're supposed to retain a pack expansion, do so by temporarily
7797 // forgetting the partially-substituted parameter pack.
7798 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
7801 TLB.reserve(From->getTypeLoc().getFullDataSize());
7803 QualType To = getDerived().TransformType(TLB, PatternTL);
7807 To = getDerived().RebuildPackExpansionType(To,
7808 PatternTL.getSourceRange(),
7809 ExpansionTL.getEllipsisLoc(),
7814 PackExpansionTypeLoc ToExpansionTL
7815 = TLB.push<PackExpansionTypeLoc>(To);
7816 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
7817 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
7820 if (!getDerived().AlwaysRebuild() && !ArgChanged)
7821 return SemaRef.Owned(E);
7823 return getDerived().RebuildTypeTrait(E->getTrait(),
7829 template<typename Derived>
7831 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
7832 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
7836 if (!getDerived().AlwaysRebuild() &&
7837 T == E->getQueriedTypeSourceInfo())
7838 return SemaRef.Owned(E);
7842 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
7843 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
7844 if (SubExpr.isInvalid())
7847 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
7848 return SemaRef.Owned(E);
7851 return getDerived().RebuildArrayTypeTrait(E->getTrait(),
7858 template<typename Derived>
7860 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
7863 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
7864 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
7865 if (SubExpr.isInvalid())
7868 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
7869 return SemaRef.Owned(E);
7872 return getDerived().RebuildExpressionTrait(
7873 E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
7876 template<typename Derived>
7878 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
7879 DependentScopeDeclRefExpr *E) {
7880 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand*/false);
7883 template<typename Derived>
7885 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
7886 DependentScopeDeclRefExpr *E,
7887 bool IsAddressOfOperand) {
7888 NestedNameSpecifierLoc QualifierLoc
7889 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7892 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
7894 // TODO: If this is a conversion-function-id, verify that the
7895 // destination type name (if present) resolves the same way after
7896 // instantiation as it did in the local scope.
7898 DeclarationNameInfo NameInfo
7899 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
7900 if (!NameInfo.getName())
7903 if (!E->hasExplicitTemplateArgs()) {
7904 if (!getDerived().AlwaysRebuild() &&
7905 QualifierLoc == E->getQualifierLoc() &&
7906 // Note: it is sufficient to compare the Name component of NameInfo:
7907 // if name has not changed, DNLoc has not changed either.
7908 NameInfo.getName() == E->getDeclName())
7909 return SemaRef.Owned(E);
7911 return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
7915 IsAddressOfOperand);
7918 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
7919 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7920 E->getNumTemplateArgs(),
7924 return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
7928 IsAddressOfOperand);
7931 template<typename Derived>
7933 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
7934 // CXXConstructExprs other than for list-initialization and
7935 // CXXTemporaryObjectExpr are always implicit, so when we have
7936 // a 1-argument construction we just transform that argument.
7937 if ((E->getNumArgs() == 1 ||
7938 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
7939 (!getDerived().DropCallArgument(E->getArg(0))) &&
7940 !E->isListInitialization())
7941 return getDerived().TransformExpr(E->getArg(0));
7943 TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
7945 QualType T = getDerived().TransformType(E->getType());
7949 CXXConstructorDecl *Constructor
7950 = cast_or_null<CXXConstructorDecl>(
7951 getDerived().TransformDecl(E->getLocStart(),
7952 E->getConstructor()));
7956 bool ArgumentChanged = false;
7957 SmallVector<Expr*, 8> Args;
7958 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
7962 if (!getDerived().AlwaysRebuild() &&
7963 T == E->getType() &&
7964 Constructor == E->getConstructor() &&
7966 // Mark the constructor as referenced.
7967 // FIXME: Instantiation-specific
7968 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
7969 return SemaRef.Owned(E);
7972 return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
7973 Constructor, E->isElidable(),
7975 E->hadMultipleCandidates(),
7976 E->isListInitialization(),
7977 E->requiresZeroInitialization(),
7978 E->getConstructionKind(),
7979 E->getParenRange());
7982 /// \brief Transform a C++ temporary-binding expression.
7984 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
7985 /// transform the subexpression and return that.
7986 template<typename Derived>
7988 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
7989 return getDerived().TransformExpr(E->getSubExpr());
7992 /// \brief Transform a C++ expression that contains cleanups that should
7993 /// be run after the expression is evaluated.
7995 /// Since ExprWithCleanups nodes are implicitly generated, we
7996 /// just transform the subexpression and return that.
7997 template<typename Derived>
7999 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
8000 return getDerived().TransformExpr(E->getSubExpr());
8003 template<typename Derived>
8005 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
8006 CXXTemporaryObjectExpr *E) {
8007 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
8011 CXXConstructorDecl *Constructor
8012 = cast_or_null<CXXConstructorDecl>(
8013 getDerived().TransformDecl(E->getLocStart(),
8014 E->getConstructor()));
8018 bool ArgumentChanged = false;
8019 SmallVector<Expr*, 8> Args;
8020 Args.reserve(E->getNumArgs());
8021 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
8025 if (!getDerived().AlwaysRebuild() &&
8026 T == E->getTypeSourceInfo() &&
8027 Constructor == E->getConstructor() &&
8029 // FIXME: Instantiation-specific
8030 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
8031 return SemaRef.MaybeBindToTemporary(E);
8034 // FIXME: Pass in E->isListInitialization().
8035 return getDerived().RebuildCXXTemporaryObjectExpr(T,
8036 /*FIXME:*/T->getTypeLoc().getEndLoc(),
8041 template<typename Derived>
8043 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
8044 // Transform the type of the lambda parameters and start the definition of
8045 // the lambda itself.
8046 TypeSourceInfo *MethodTy
8047 = TransformType(E->getCallOperator()->getTypeSourceInfo());
8051 // Create the local class that will describe the lambda.
8052 CXXRecordDecl *Class
8053 = getSema().createLambdaClosureType(E->getIntroducerRange(),
8055 /*KnownDependent=*/false);
8056 getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
8058 // Transform lambda parameters.
8059 SmallVector<QualType, 4> ParamTypes;
8060 SmallVector<ParmVarDecl *, 4> Params;
8061 if (getDerived().TransformFunctionTypeParams(E->getLocStart(),
8062 E->getCallOperator()->param_begin(),
8063 E->getCallOperator()->param_size(),
8064 0, ParamTypes, &Params))
8067 // Build the call operator.
8068 CXXMethodDecl *CallOperator
8069 = getSema().startLambdaDefinition(Class, E->getIntroducerRange(),
8071 E->getCallOperator()->getLocEnd(),
8073 getDerived().transformAttrs(E->getCallOperator(), CallOperator);
8075 return getDerived().TransformLambdaScope(E, CallOperator);
8078 template<typename Derived>
8080 TreeTransform<Derived>::TransformLambdaScope(LambdaExpr *E,
8081 CXXMethodDecl *CallOperator) {
8082 // Introduce the context of the call operator.
8083 Sema::ContextRAII SavedContext(getSema(), CallOperator);
8085 // Enter the scope of the lambda.
8086 sema::LambdaScopeInfo *LSI
8087 = getSema().enterLambdaScope(CallOperator, E->getIntroducerRange(),
8088 E->getCaptureDefault(),
8089 E->hasExplicitParameters(),
8090 E->hasExplicitResultType(),
8093 // Transform captures.
8094 bool Invalid = false;
8095 bool FinishedExplicitCaptures = false;
8096 for (LambdaExpr::capture_iterator C = E->capture_begin(),
8097 CEnd = E->capture_end();
8099 // When we hit the first implicit capture, tell Sema that we've finished
8100 // the list of explicit captures.
8101 if (!FinishedExplicitCaptures && C->isImplicit()) {
8102 getSema().finishLambdaExplicitCaptures(LSI);
8103 FinishedExplicitCaptures = true;
8106 // Capturing 'this' is trivial.
8107 if (C->capturesThis()) {
8108 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
8112 // Determine the capture kind for Sema.
8113 Sema::TryCaptureKind Kind
8114 = C->isImplicit()? Sema::TryCapture_Implicit
8115 : C->getCaptureKind() == LCK_ByCopy
8116 ? Sema::TryCapture_ExplicitByVal
8117 : Sema::TryCapture_ExplicitByRef;
8118 SourceLocation EllipsisLoc;
8119 if (C->isPackExpansion()) {
8120 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
8121 bool ShouldExpand = false;
8122 bool RetainExpansion = false;
8123 Optional<unsigned> NumExpansions;
8124 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
8127 ShouldExpand, RetainExpansion,
8132 // The transform has determined that we should perform an expansion;
8133 // transform and capture each of the arguments.
8134 // expansion of the pattern. Do so.
8135 VarDecl *Pack = C->getCapturedVar();
8136 for (unsigned I = 0; I != *NumExpansions; ++I) {
8137 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
8138 VarDecl *CapturedVar
8139 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
8146 // Capture the transformed variable.
8147 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
8152 EllipsisLoc = C->getEllipsisLoc();
8155 // Transform the captured variable.
8156 VarDecl *CapturedVar
8157 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
8158 C->getCapturedVar()));
8164 // Capture the transformed variable.
8165 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
8167 if (!FinishedExplicitCaptures)
8168 getSema().finishLambdaExplicitCaptures(LSI);
8171 // Enter a new evaluation context to insulate the lambda from any
8172 // cleanups from the enclosing full-expression.
8173 getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
8176 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/0,
8177 /*IsInstantiation=*/true);
8181 // Instantiate the body of the lambda expression.
8182 StmtResult Body = getDerived().TransformStmt(E->getBody());
8183 if (Body.isInvalid()) {
8184 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/0,
8185 /*IsInstantiation=*/true);
8189 return getSema().ActOnLambdaExpr(E->getLocStart(), Body.take(),
8190 /*CurScope=*/0, /*IsInstantiation=*/true);
8193 template<typename Derived>
8195 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
8196 CXXUnresolvedConstructExpr *E) {
8197 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
8201 bool ArgumentChanged = false;
8202 SmallVector<Expr*, 8> Args;
8203 Args.reserve(E->arg_size());
8204 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
8208 if (!getDerived().AlwaysRebuild() &&
8209 T == E->getTypeSourceInfo() &&
8211 return SemaRef.Owned(E);
8213 // FIXME: we're faking the locations of the commas
8214 return getDerived().RebuildCXXUnresolvedConstructExpr(T,
8220 template<typename Derived>
8222 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
8223 CXXDependentScopeMemberExpr *E) {
8224 // Transform the base of the expression.
8225 ExprResult Base((Expr*) 0);
8228 QualType ObjectType;
8229 if (!E->isImplicitAccess()) {
8230 OldBase = E->getBase();
8231 Base = getDerived().TransformExpr(OldBase);
8232 if (Base.isInvalid())
8235 // Start the member reference and compute the object's type.
8236 ParsedType ObjectTy;
8237 bool MayBePseudoDestructor = false;
8238 Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
8239 E->getOperatorLoc(),
8240 E->isArrow()? tok::arrow : tok::period,
8242 MayBePseudoDestructor);
8243 if (Base.isInvalid())
8246 ObjectType = ObjectTy.get();
8247 BaseType = ((Expr*) Base.get())->getType();
8250 BaseType = getDerived().TransformType(E->getBaseType());
8251 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
8254 // Transform the first part of the nested-name-specifier that qualifies
8256 NamedDecl *FirstQualifierInScope
8257 = getDerived().TransformFirstQualifierInScope(
8258 E->getFirstQualifierFoundInScope(),
8259 E->getQualifierLoc().getBeginLoc());
8261 NestedNameSpecifierLoc QualifierLoc;
8262 if (E->getQualifier()) {
8264 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
8266 FirstQualifierInScope);
8271 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
8273 // TODO: If this is a conversion-function-id, verify that the
8274 // destination type name (if present) resolves the same way after
8275 // instantiation as it did in the local scope.
8277 DeclarationNameInfo NameInfo
8278 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
8279 if (!NameInfo.getName())
8282 if (!E->hasExplicitTemplateArgs()) {
8283 // This is a reference to a member without an explicitly-specified
8284 // template argument list. Optimize for this common case.
8285 if (!getDerived().AlwaysRebuild() &&
8286 Base.get() == OldBase &&
8287 BaseType == E->getBaseType() &&
8288 QualifierLoc == E->getQualifierLoc() &&
8289 NameInfo.getName() == E->getMember() &&
8290 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
8291 return SemaRef.Owned(E);
8293 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
8296 E->getOperatorLoc(),
8299 FirstQualifierInScope,
8301 /*TemplateArgs*/ 0);
8304 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
8305 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
8306 E->getNumTemplateArgs(),
8310 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
8313 E->getOperatorLoc(),
8316 FirstQualifierInScope,
8321 template<typename Derived>
8323 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
8324 // Transform the base of the expression.
8325 ExprResult Base((Expr*) 0);
8327 if (!Old->isImplicitAccess()) {
8328 Base = getDerived().TransformExpr(Old->getBase());
8329 if (Base.isInvalid())
8331 Base = getSema().PerformMemberExprBaseConversion(Base.take(),
8333 if (Base.isInvalid())
8335 BaseType = Base.get()->getType();
8337 BaseType = getDerived().TransformType(Old->getBaseType());
8340 NestedNameSpecifierLoc QualifierLoc;
8341 if (Old->getQualifierLoc()) {
8343 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
8348 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
8350 LookupResult R(SemaRef, Old->getMemberNameInfo(),
8351 Sema::LookupOrdinaryName);
8353 // Transform all the decls.
8354 for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
8355 E = Old->decls_end(); I != E; ++I) {
8356 NamedDecl *InstD = static_cast<NamedDecl*>(
8357 getDerived().TransformDecl(Old->getMemberLoc(),
8360 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
8361 // This can happen because of dependent hiding.
8362 if (isa<UsingShadowDecl>(*I))
8370 // Expand using declarations.
8371 if (isa<UsingDecl>(InstD)) {
8372 UsingDecl *UD = cast<UsingDecl>(InstD);
8373 for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
8374 E = UD->shadow_end(); I != E; ++I)
8384 // Determine the naming class.
8385 if (Old->getNamingClass()) {
8386 CXXRecordDecl *NamingClass
8387 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
8388 Old->getMemberLoc(),
8389 Old->getNamingClass()));
8393 R.setNamingClass(NamingClass);
8396 TemplateArgumentListInfo TransArgs;
8397 if (Old->hasExplicitTemplateArgs()) {
8398 TransArgs.setLAngleLoc(Old->getLAngleLoc());
8399 TransArgs.setRAngleLoc(Old->getRAngleLoc());
8400 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
8401 Old->getNumTemplateArgs(),
8406 // FIXME: to do this check properly, we will need to preserve the
8407 // first-qualifier-in-scope here, just in case we had a dependent
8408 // base (and therefore couldn't do the check) and a
8409 // nested-name-qualifier (and therefore could do the lookup).
8410 NamedDecl *FirstQualifierInScope = 0;
8412 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
8414 Old->getOperatorLoc(),
8418 FirstQualifierInScope,
8420 (Old->hasExplicitTemplateArgs()
8424 template<typename Derived>
8426 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
8427 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8428 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
8429 if (SubExpr.isInvalid())
8432 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
8433 return SemaRef.Owned(E);
8435 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
8438 template<typename Derived>
8440 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
8441 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
8442 if (Pattern.isInvalid())
8445 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
8446 return SemaRef.Owned(E);
8448 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
8449 E->getNumExpansions());
8452 template<typename Derived>
8454 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
8455 // If E is not value-dependent, then nothing will change when we transform it.
8456 // Note: This is an instantiation-centric view.
8457 if (!E->isValueDependent())
8458 return SemaRef.Owned(E);
8460 // Note: None of the implementations of TryExpandParameterPacks can ever
8461 // produce a diagnostic when given only a single unexpanded parameter pack,
8463 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
8464 bool ShouldExpand = false;
8465 bool RetainExpansion = false;
8466 Optional<unsigned> NumExpansions;
8467 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
8469 ShouldExpand, RetainExpansion,
8473 if (RetainExpansion)
8474 return SemaRef.Owned(E);
8476 NamedDecl *Pack = E->getPack();
8477 if (!ShouldExpand) {
8478 Pack = cast_or_null<NamedDecl>(getDerived().TransformDecl(E->getPackLoc(),
8485 // We now know the length of the parameter pack, so build a new expression
8486 // that stores that length.
8487 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
8488 E->getPackLoc(), E->getRParenLoc(),
8492 template<typename Derived>
8494 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
8495 SubstNonTypeTemplateParmPackExpr *E) {
8496 // Default behavior is to do nothing with this transformation.
8497 return SemaRef.Owned(E);
8500 template<typename Derived>
8502 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
8503 SubstNonTypeTemplateParmExpr *E) {
8504 // Default behavior is to do nothing with this transformation.
8505 return SemaRef.Owned(E);
8508 template<typename Derived>
8510 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
8511 // Default behavior is to do nothing with this transformation.
8512 return SemaRef.Owned(E);
8515 template<typename Derived>
8517 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
8518 MaterializeTemporaryExpr *E) {
8519 return getDerived().TransformExpr(E->GetTemporaryExpr());
8522 template<typename Derived>
8524 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
8525 return SemaRef.MaybeBindToTemporary(E);
8528 template<typename Derived>
8530 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
8531 return SemaRef.Owned(E);
8534 template<typename Derived>
8536 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
8537 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8538 if (SubExpr.isInvalid())
8541 if (!getDerived().AlwaysRebuild() &&
8542 SubExpr.get() == E->getSubExpr())
8543 return SemaRef.Owned(E);
8545 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
8548 template<typename Derived>
8550 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
8551 // Transform each of the elements.
8552 SmallVector<Expr *, 8> Elements;
8553 bool ArgChanged = false;
8554 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
8555 /*IsCall=*/false, Elements, &ArgChanged))
8558 if (!getDerived().AlwaysRebuild() && !ArgChanged)
8559 return SemaRef.MaybeBindToTemporary(E);
8561 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
8566 template<typename Derived>
8568 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
8569 ObjCDictionaryLiteral *E) {
8570 // Transform each of the elements.
8571 SmallVector<ObjCDictionaryElement, 8> Elements;
8572 bool ArgChanged = false;
8573 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
8574 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
8576 if (OrigElement.isPackExpansion()) {
8577 // This key/value element is a pack expansion.
8578 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
8579 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
8580 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
8581 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
8583 // Determine whether the set of unexpanded parameter packs can
8584 // and should be expanded.
8586 bool RetainExpansion = false;
8587 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
8588 Optional<unsigned> NumExpansions = OrigNumExpansions;
8589 SourceRange PatternRange(OrigElement.Key->getLocStart(),
8590 OrigElement.Value->getLocEnd());
8591 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
8594 Expand, RetainExpansion,
8599 // The transform has determined that we should perform a simple
8600 // transformation on the pack expansion, producing another pack
8602 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
8603 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
8604 if (Key.isInvalid())
8607 if (Key.get() != OrigElement.Key)
8610 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
8611 if (Value.isInvalid())
8614 if (Value.get() != OrigElement.Value)
8617 ObjCDictionaryElement Expansion = {
8618 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
8620 Elements.push_back(Expansion);
8624 // Record right away that the argument was changed. This needs
8625 // to happen even if the array expands to nothing.
8628 // The transform has determined that we should perform an elementwise
8629 // expansion of the pattern. Do so.
8630 for (unsigned I = 0; I != *NumExpansions; ++I) {
8631 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
8632 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
8633 if (Key.isInvalid())
8636 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
8637 if (Value.isInvalid())
8640 ObjCDictionaryElement Element = {
8641 Key.get(), Value.get(), SourceLocation(), NumExpansions
8644 // If any unexpanded parameter packs remain, we still have a
8646 if (Key.get()->containsUnexpandedParameterPack() ||
8647 Value.get()->containsUnexpandedParameterPack())
8648 Element.EllipsisLoc = OrigElement.EllipsisLoc;
8650 Elements.push_back(Element);
8653 // We've finished with this pack expansion.
8657 // Transform and check key.
8658 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
8659 if (Key.isInvalid())
8662 if (Key.get() != OrigElement.Key)
8665 // Transform and check value.
8667 = getDerived().TransformExpr(OrigElement.Value);
8668 if (Value.isInvalid())
8671 if (Value.get() != OrigElement.Value)
8674 ObjCDictionaryElement Element = {
8675 Key.get(), Value.get(), SourceLocation(), None
8677 Elements.push_back(Element);
8680 if (!getDerived().AlwaysRebuild() && !ArgChanged)
8681 return SemaRef.MaybeBindToTemporary(E);
8683 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
8688 template<typename Derived>
8690 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
8691 TypeSourceInfo *EncodedTypeInfo
8692 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
8693 if (!EncodedTypeInfo)
8696 if (!getDerived().AlwaysRebuild() &&
8697 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
8698 return SemaRef.Owned(E);
8700 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
8705 template<typename Derived>
8706 ExprResult TreeTransform<Derived>::
8707 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
8708 // This is a kind of implicit conversion, and it needs to get dropped
8709 // and recomputed for the same general reasons that ImplicitCastExprs
8710 // do, as well a more specific one: this expression is only valid when
8711 // it appears *immediately* as an argument expression.
8712 return getDerived().TransformExpr(E->getSubExpr());
8715 template<typename Derived>
8716 ExprResult TreeTransform<Derived>::
8717 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
8718 TypeSourceInfo *TSInfo
8719 = getDerived().TransformType(E->getTypeInfoAsWritten());
8723 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
8724 if (Result.isInvalid())
8727 if (!getDerived().AlwaysRebuild() &&
8728 TSInfo == E->getTypeInfoAsWritten() &&
8729 Result.get() == E->getSubExpr())
8730 return SemaRef.Owned(E);
8732 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
8733 E->getBridgeKeywordLoc(), TSInfo,
8737 template<typename Derived>
8739 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
8740 // Transform arguments.
8741 bool ArgChanged = false;
8742 SmallVector<Expr*, 8> Args;
8743 Args.reserve(E->getNumArgs());
8744 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
8748 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
8749 // Class message: transform the receiver type.
8750 TypeSourceInfo *ReceiverTypeInfo
8751 = getDerived().TransformType(E->getClassReceiverTypeInfo());
8752 if (!ReceiverTypeInfo)
8755 // If nothing changed, just retain the existing message send.
8756 if (!getDerived().AlwaysRebuild() &&
8757 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
8758 return SemaRef.MaybeBindToTemporary(E);
8760 // Build a new class message send.
8761 SmallVector<SourceLocation, 16> SelLocs;
8762 E->getSelectorLocs(SelLocs);
8763 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
8772 // Instance message: transform the receiver
8773 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
8774 "Only class and instance messages may be instantiated");
8776 = getDerived().TransformExpr(E->getInstanceReceiver());
8777 if (Receiver.isInvalid())
8780 // If nothing changed, just retain the existing message send.
8781 if (!getDerived().AlwaysRebuild() &&
8782 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
8783 return SemaRef.MaybeBindToTemporary(E);
8785 // Build a new instance message send.
8786 SmallVector<SourceLocation, 16> SelLocs;
8787 E->getSelectorLocs(SelLocs);
8788 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
8797 template<typename Derived>
8799 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
8800 return SemaRef.Owned(E);
8803 template<typename Derived>
8805 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
8806 return SemaRef.Owned(E);
8809 template<typename Derived>
8811 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
8812 // Transform the base expression.
8813 ExprResult Base = getDerived().TransformExpr(E->getBase());
8814 if (Base.isInvalid())
8817 // We don't need to transform the ivar; it will never change.
8819 // If nothing changed, just retain the existing expression.
8820 if (!getDerived().AlwaysRebuild() &&
8821 Base.get() == E->getBase())
8822 return SemaRef.Owned(E);
8824 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
8826 E->isArrow(), E->isFreeIvar());
8829 template<typename Derived>
8831 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
8832 // 'super' and types never change. Property never changes. Just
8833 // retain the existing expression.
8834 if (!E->isObjectReceiver())
8835 return SemaRef.Owned(E);
8837 // Transform the base expression.
8838 ExprResult Base = getDerived().TransformExpr(E->getBase());
8839 if (Base.isInvalid())
8842 // We don't need to transform the property; it will never change.
8844 // If nothing changed, just retain the existing expression.
8845 if (!getDerived().AlwaysRebuild() &&
8846 Base.get() == E->getBase())
8847 return SemaRef.Owned(E);
8849 if (E->isExplicitProperty())
8850 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
8851 E->getExplicitProperty(),
8854 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
8855 SemaRef.Context.PseudoObjectTy,
8856 E->getImplicitPropertyGetter(),
8857 E->getImplicitPropertySetter(),
8861 template<typename Derived>
8863 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
8864 // Transform the base expression.
8865 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8866 if (Base.isInvalid())
8869 // Transform the key expression.
8870 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
8871 if (Key.isInvalid())
8874 // If nothing changed, just retain the existing expression.
8875 if (!getDerived().AlwaysRebuild() &&
8876 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
8877 return SemaRef.Owned(E);
8879 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
8880 Base.get(), Key.get(),
8881 E->getAtIndexMethodDecl(),
8882 E->setAtIndexMethodDecl());
8885 template<typename Derived>
8887 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
8888 // Transform the base expression.
8889 ExprResult Base = getDerived().TransformExpr(E->getBase());
8890 if (Base.isInvalid())
8893 // If nothing changed, just retain the existing expression.
8894 if (!getDerived().AlwaysRebuild() &&
8895 Base.get() == E->getBase())
8896 return SemaRef.Owned(E);
8898 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
8903 template<typename Derived>
8905 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
8906 bool ArgumentChanged = false;
8907 SmallVector<Expr*, 8> SubExprs;
8908 SubExprs.reserve(E->getNumSubExprs());
8909 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
8910 SubExprs, &ArgumentChanged))
8913 if (!getDerived().AlwaysRebuild() &&
8915 return SemaRef.Owned(E);
8917 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
8922 template<typename Derived>
8924 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
8925 BlockDecl *oldBlock = E->getBlockDecl();
8927 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/0);
8928 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
8930 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
8931 blockScope->TheDecl->setBlockMissingReturnType(
8932 oldBlock->blockMissingReturnType());
8934 SmallVector<ParmVarDecl*, 4> params;
8935 SmallVector<QualType, 4> paramTypes;
8937 // Parameter substitution.
8938 if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
8939 oldBlock->param_begin(),
8940 oldBlock->param_size(),
8941 0, paramTypes, ¶ms)) {
8942 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/0);
8946 const FunctionProtoType *exprFunctionType = E->getFunctionType();
8947 QualType exprResultType =
8948 getDerived().TransformType(exprFunctionType->getResultType());
8950 // Don't allow returning a objc interface by value.
8951 if (exprResultType->isObjCObjectType()) {
8952 getSema().Diag(E->getCaretLocation(),
8953 diag::err_object_cannot_be_passed_returned_by_value)
8954 << 0 << exprResultType;
8955 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/0);
8959 QualType functionType =
8960 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes,
8961 exprFunctionType->getExtProtoInfo());
8962 blockScope->FunctionType = functionType;
8964 // Set the parameters on the block decl.
8965 if (!params.empty())
8966 blockScope->TheDecl->setParams(params);
8968 if (!oldBlock->blockMissingReturnType()) {
8969 blockScope->HasImplicitReturnType = false;
8970 blockScope->ReturnType = exprResultType;
8973 // Transform the body
8974 StmtResult body = getDerived().TransformStmt(E->getBody());
8975 if (body.isInvalid()) {
8976 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/0);
8981 // In builds with assertions, make sure that we captured everything we
8983 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
8984 for (BlockDecl::capture_iterator i = oldBlock->capture_begin(),
8985 e = oldBlock->capture_end(); i != e; ++i) {
8986 VarDecl *oldCapture = i->getVariable();
8988 // Ignore parameter packs.
8989 if (isa<ParmVarDecl>(oldCapture) &&
8990 cast<ParmVarDecl>(oldCapture)->isParameterPack())
8993 VarDecl *newCapture =
8994 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
8996 assert(blockScope->CaptureMap.count(newCapture));
8998 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
9002 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
9006 template<typename Derived>
9008 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
9009 llvm_unreachable("Cannot transform asType expressions yet");
9012 template<typename Derived>
9014 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
9015 QualType RetTy = getDerived().TransformType(E->getType());
9016 bool ArgumentChanged = false;
9017 SmallVector<Expr*, 8> SubExprs;
9018 SubExprs.reserve(E->getNumSubExprs());
9019 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
9020 SubExprs, &ArgumentChanged))
9023 if (!getDerived().AlwaysRebuild() &&
9025 return SemaRef.Owned(E);
9027 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
9028 RetTy, E->getOp(), E->getRParenLoc());
9031 //===----------------------------------------------------------------------===//
9032 // Type reconstruction
9033 //===----------------------------------------------------------------------===//
9035 template<typename Derived>
9036 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
9037 SourceLocation Star) {
9038 return SemaRef.BuildPointerType(PointeeType, Star,
9039 getDerived().getBaseEntity());
9042 template<typename Derived>
9043 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
9044 SourceLocation Star) {
9045 return SemaRef.BuildBlockPointerType(PointeeType, Star,
9046 getDerived().getBaseEntity());
9049 template<typename Derived>
9051 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
9052 bool WrittenAsLValue,
9053 SourceLocation Sigil) {
9054 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
9055 Sigil, getDerived().getBaseEntity());
9058 template<typename Derived>
9060 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
9062 SourceLocation Sigil) {
9063 return SemaRef.BuildMemberPointerType(PointeeType, ClassType,
9064 Sigil, getDerived().getBaseEntity());
9067 template<typename Derived>
9069 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
9070 ArrayType::ArraySizeModifier SizeMod,
9071 const llvm::APInt *Size,
9073 unsigned IndexTypeQuals,
9074 SourceRange BracketsRange) {
9075 if (SizeExpr || !Size)
9076 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
9077 IndexTypeQuals, BracketsRange,
9078 getDerived().getBaseEntity());
9080 QualType Types[] = {
9081 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
9082 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
9083 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
9085 const unsigned NumTypes = sizeof(Types) / sizeof(QualType);
9087 for (unsigned I = 0; I != NumTypes; ++I)
9088 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
9089 SizeType = Types[I];
9093 // Note that we can return a VariableArrayType here in the case where
9094 // the element type was a dependent VariableArrayType.
9095 IntegerLiteral *ArraySize
9096 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
9097 /*FIXME*/BracketsRange.getBegin());
9098 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
9099 IndexTypeQuals, BracketsRange,
9100 getDerived().getBaseEntity());
9103 template<typename Derived>
9105 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
9106 ArrayType::ArraySizeModifier SizeMod,
9107 const llvm::APInt &Size,
9108 unsigned IndexTypeQuals,
9109 SourceRange BracketsRange) {
9110 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, 0,
9111 IndexTypeQuals, BracketsRange);
9114 template<typename Derived>
9116 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
9117 ArrayType::ArraySizeModifier SizeMod,
9118 unsigned IndexTypeQuals,
9119 SourceRange BracketsRange) {
9120 return getDerived().RebuildArrayType(ElementType, SizeMod, 0, 0,
9121 IndexTypeQuals, BracketsRange);
9124 template<typename Derived>
9126 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
9127 ArrayType::ArraySizeModifier SizeMod,
9129 unsigned IndexTypeQuals,
9130 SourceRange BracketsRange) {
9131 return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
9133 IndexTypeQuals, BracketsRange);
9136 template<typename Derived>
9138 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
9139 ArrayType::ArraySizeModifier SizeMod,
9141 unsigned IndexTypeQuals,
9142 SourceRange BracketsRange) {
9143 return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
9145 IndexTypeQuals, BracketsRange);
9148 template<typename Derived>
9149 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
9150 unsigned NumElements,
9151 VectorType::VectorKind VecKind) {
9152 // FIXME: semantic checking!
9153 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
9156 template<typename Derived>
9157 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
9158 unsigned NumElements,
9159 SourceLocation AttributeLoc) {
9160 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
9162 IntegerLiteral *VectorSize
9163 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
9165 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
9168 template<typename Derived>
9170 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
9172 SourceLocation AttributeLoc) {
9173 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
9176 template<typename Derived>
9177 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
9179 llvm::MutableArrayRef<QualType> ParamTypes,
9180 const FunctionProtoType::ExtProtoInfo &EPI) {
9181 return SemaRef.BuildFunctionType(T, ParamTypes,
9182 getDerived().getBaseLocation(),
9183 getDerived().getBaseEntity(),
9187 template<typename Derived>
9188 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
9189 return SemaRef.Context.getFunctionNoProtoType(T);
9192 template<typename Derived>
9193 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
9194 assert(D && "no decl found");
9195 if (D->isInvalidDecl()) return QualType();
9197 // FIXME: Doesn't account for ObjCInterfaceDecl!
9199 if (isa<UsingDecl>(D)) {
9200 UsingDecl *Using = cast<UsingDecl>(D);
9201 assert(Using->isTypeName() &&
9202 "UnresolvedUsingTypenameDecl transformed to non-typename using");
9204 // A valid resolved using typename decl points to exactly one type decl.
9205 assert(++Using->shadow_begin() == Using->shadow_end());
9206 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
9209 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
9210 "UnresolvedUsingTypenameDecl transformed to non-using decl");
9211 Ty = cast<UnresolvedUsingTypenameDecl>(D);
9214 return SemaRef.Context.getTypeDeclType(Ty);
9217 template<typename Derived>
9218 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
9219 SourceLocation Loc) {
9220 return SemaRef.BuildTypeofExprType(E, Loc);
9223 template<typename Derived>
9224 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
9225 return SemaRef.Context.getTypeOfType(Underlying);
9228 template<typename Derived>
9229 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
9230 SourceLocation Loc) {
9231 return SemaRef.BuildDecltypeType(E, Loc);
9234 template<typename Derived>
9235 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
9236 UnaryTransformType::UTTKind UKind,
9237 SourceLocation Loc) {
9238 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
9241 template<typename Derived>
9242 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
9243 TemplateName Template,
9244 SourceLocation TemplateNameLoc,
9245 TemplateArgumentListInfo &TemplateArgs) {
9246 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
9249 template<typename Derived>
9250 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
9251 SourceLocation KWLoc) {
9252 return SemaRef.BuildAtomicType(ValueType, KWLoc);
9255 template<typename Derived>
9257 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
9259 TemplateDecl *Template) {
9260 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
9264 template<typename Derived>
9266 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
9267 const IdentifierInfo &Name,
9268 SourceLocation NameLoc,
9269 QualType ObjectType,
9270 NamedDecl *FirstQualifierInScope) {
9271 UnqualifiedId TemplateName;
9272 TemplateName.setIdentifier(&Name, NameLoc);
9273 Sema::TemplateTy Template;
9274 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
9275 getSema().ActOnDependentTemplateName(/*Scope=*/0,
9276 SS, TemplateKWLoc, TemplateName,
9277 ParsedType::make(ObjectType),
9278 /*EnteringContext=*/false,
9280 return Template.get();
9283 template<typename Derived>
9285 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
9286 OverloadedOperatorKind Operator,
9287 SourceLocation NameLoc,
9288 QualType ObjectType) {
9290 // FIXME: Bogus location information.
9291 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
9292 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
9293 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
9294 Sema::TemplateTy Template;
9295 getSema().ActOnDependentTemplateName(/*Scope=*/0,
9296 SS, TemplateKWLoc, Name,
9297 ParsedType::make(ObjectType),
9298 /*EnteringContext=*/false,
9300 return Template.template getAsVal<TemplateName>();
9303 template<typename Derived>
9305 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
9306 SourceLocation OpLoc,
9310 Expr *Callee = OrigCallee->IgnoreParenCasts();
9311 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
9313 // Determine whether this should be a builtin operation.
9314 if (Op == OO_Subscript) {
9315 if (!First->getType()->isOverloadableType() &&
9316 !Second->getType()->isOverloadableType())
9317 return getSema().CreateBuiltinArraySubscriptExpr(First,
9318 Callee->getLocStart(),
9320 } else if (Op == OO_Arrow) {
9321 // -> is never a builtin operation.
9322 return SemaRef.BuildOverloadedArrowExpr(0, First, OpLoc);
9323 } else if (Second == 0 || isPostIncDec) {
9324 if (!First->getType()->isOverloadableType()) {
9325 // The argument is not of overloadable type, so try to create a
9326 // built-in unary operation.
9327 UnaryOperatorKind Opc
9328 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
9330 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
9333 if (!First->getType()->isOverloadableType() &&
9334 !Second->getType()->isOverloadableType()) {
9335 // Neither of the arguments is an overloadable type, so try to
9336 // create a built-in binary operation.
9337 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
9339 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
9340 if (Result.isInvalid())
9347 // Compute the transformed set of functions (and function templates) to be
9348 // used during overload resolution.
9349 UnresolvedSet<16> Functions;
9351 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
9352 assert(ULE->requiresADL());
9354 // FIXME: Do we have to check
9355 // IsAcceptableNonMemberOperatorCandidate for each of these?
9356 Functions.append(ULE->decls_begin(), ULE->decls_end());
9358 // If we've resolved this to a particular non-member function, just call
9359 // that function. If we resolved it to a member function,
9360 // CreateOverloaded* will find that function for us.
9361 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
9362 if (!isa<CXXMethodDecl>(ND))
9363 Functions.addDecl(ND);
9366 // Add any functions found via argument-dependent lookup.
9367 Expr *Args[2] = { First, Second };
9368 unsigned NumArgs = 1 + (Second != 0);
9370 // Create the overloaded operator invocation for unary operators.
9371 if (NumArgs == 1 || isPostIncDec) {
9372 UnaryOperatorKind Opc
9373 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
9374 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
9377 if (Op == OO_Subscript) {
9378 SourceLocation LBrace;
9379 SourceLocation RBrace;
9381 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
9382 DeclarationNameLoc &NameLoc = DRE->getNameInfo().getInfo();
9383 LBrace = SourceLocation::getFromRawEncoding(
9384 NameLoc.CXXOperatorName.BeginOpNameLoc);
9385 RBrace = SourceLocation::getFromRawEncoding(
9386 NameLoc.CXXOperatorName.EndOpNameLoc);
9388 LBrace = Callee->getLocStart();
9392 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
9396 // Create the overloaded operator invocation for binary operators.
9397 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
9399 = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
9400 if (Result.isInvalid())
9406 template<typename Derived>
9408 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
9409 SourceLocation OperatorLoc,
9412 TypeSourceInfo *ScopeType,
9413 SourceLocation CCLoc,
9414 SourceLocation TildeLoc,
9415 PseudoDestructorTypeStorage Destroyed) {
9416 QualType BaseType = Base->getType();
9417 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
9418 (!isArrow && !BaseType->getAs<RecordType>()) ||
9419 (isArrow && BaseType->getAs<PointerType>() &&
9420 !BaseType->getAs<PointerType>()->getPointeeType()
9421 ->template getAs<RecordType>())){
9422 // This pseudo-destructor expression is still a pseudo-destructor.
9423 return SemaRef.BuildPseudoDestructorExpr(Base, OperatorLoc,
9424 isArrow? tok::arrow : tok::period,
9425 SS, ScopeType, CCLoc, TildeLoc,
9430 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
9431 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
9432 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
9433 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
9434 NameInfo.setNamedTypeInfo(DestroyedType);
9436 // The scope type is now known to be a valid nested name specifier
9437 // component. Tack it on to the end of the nested name specifier.
9439 SS.Extend(SemaRef.Context, SourceLocation(),
9440 ScopeType->getTypeLoc(), CCLoc);
9442 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
9443 return getSema().BuildMemberReferenceExpr(Base, BaseType,
9444 OperatorLoc, isArrow,
9446 /*FIXME: FirstQualifier*/ 0,
9448 /*TemplateArgs*/ 0);
9451 template<typename Derived>
9453 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
9454 SourceLocation Loc = S->getLocStart();
9455 unsigned NumParams = S->getCapturedDecl()->getNumParams();
9456 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/0,
9457 S->getCapturedRegionKind(), NumParams);
9458 StmtResult Body = getDerived().TransformStmt(S->getCapturedStmt());
9460 if (Body.isInvalid()) {
9461 getSema().ActOnCapturedRegionError();
9465 return getSema().ActOnCapturedRegionEnd(Body.take());
9468 } // end namespace clang
9470 #endif // LLVM_CLANG_SEMA_TREETRANSFORM_H