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_LIB_SEMA_TREETRANSFORM_H
15 #define LLVM_CLANG_LIB_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/AST/StmtOpenMP.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.
145 /// We must always rebuild all AST nodes when performing variadic template
146 /// pack expansion, in order to avoid violating the AST invariant that each
147 /// statement node appears at most once in its containing declaration.
148 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
150 /// \brief Returns the location of the entity being transformed, if that
151 /// information was not available elsewhere in the AST.
153 /// By default, returns no source-location information. Subclasses can
154 /// provide an alternative implementation that provides better location
156 SourceLocation getBaseLocation() { return SourceLocation(); }
158 /// \brief Returns the name of the entity being transformed, if that
159 /// information was not available elsewhere in the AST.
161 /// By default, returns an empty name. Subclasses can provide an alternative
162 /// implementation with a more precise name.
163 DeclarationName getBaseEntity() { return DeclarationName(); }
165 /// \brief Sets the "base" location and entity when that
166 /// information is known based on another transformation.
168 /// By default, the source location and entity are ignored. Subclasses can
169 /// override this function to provide a customized implementation.
170 void setBase(SourceLocation Loc, DeclarationName Entity) { }
172 /// \brief RAII object that temporarily sets the base location and entity
173 /// used for reporting diagnostics in types.
174 class TemporaryBase {
176 SourceLocation OldLocation;
177 DeclarationName OldEntity;
180 TemporaryBase(TreeTransform &Self, SourceLocation Location,
181 DeclarationName Entity) : Self(Self) {
182 OldLocation = Self.getDerived().getBaseLocation();
183 OldEntity = Self.getDerived().getBaseEntity();
185 if (Location.isValid())
186 Self.getDerived().setBase(Location, Entity);
190 Self.getDerived().setBase(OldLocation, OldEntity);
194 /// \brief Determine whether the given type \p T has already been
197 /// Subclasses can provide an alternative implementation of this routine
198 /// to short-circuit evaluation when it is known that a given type will
199 /// not change. For example, template instantiation need not traverse
200 /// non-dependent types.
201 bool AlreadyTransformed(QualType T) {
205 /// \brief Determine whether the given call argument should be dropped, e.g.,
206 /// because it is a default argument.
208 /// Subclasses can provide an alternative implementation of this routine to
209 /// determine which kinds of call arguments get dropped. By default,
210 /// CXXDefaultArgument nodes are dropped (prior to transformation).
211 bool DropCallArgument(Expr *E) {
212 return E->isDefaultArgument();
215 /// \brief Determine whether we should expand a pack expansion with the
216 /// given set of parameter packs into separate arguments by repeatedly
217 /// transforming the pattern.
219 /// By default, the transformer never tries to expand pack expansions.
220 /// Subclasses can override this routine to provide different behavior.
222 /// \param EllipsisLoc The location of the ellipsis that identifies the
225 /// \param PatternRange The source range that covers the entire pattern of
226 /// the pack expansion.
228 /// \param Unexpanded The set of unexpanded parameter packs within the
231 /// \param ShouldExpand Will be set to \c true if the transformer should
232 /// expand the corresponding pack expansions into separate arguments. When
233 /// set, \c NumExpansions must also be set.
235 /// \param RetainExpansion Whether the caller should add an unexpanded
236 /// pack expansion after all of the expanded arguments. This is used
237 /// when extending explicitly-specified template argument packs per
238 /// C++0x [temp.arg.explicit]p9.
240 /// \param NumExpansions The number of separate arguments that will be in
241 /// the expanded form of the corresponding pack expansion. This is both an
242 /// input and an output parameter, which can be set by the caller if the
243 /// number of expansions is known a priori (e.g., due to a prior substitution)
244 /// and will be set by the callee when the number of expansions is known.
245 /// The callee must set this value when \c ShouldExpand is \c true; it may
246 /// set this value in other cases.
248 /// \returns true if an error occurred (e.g., because the parameter packs
249 /// are to be instantiated with arguments of different lengths), false
250 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
252 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
253 SourceRange PatternRange,
254 ArrayRef<UnexpandedParameterPack> Unexpanded,
256 bool &RetainExpansion,
257 Optional<unsigned> &NumExpansions) {
258 ShouldExpand = false;
262 /// \brief "Forget" about the partially-substituted pack template argument,
263 /// when performing an instantiation that must preserve the parameter pack
266 /// This routine is meant to be overridden by the template instantiator.
267 TemplateArgument ForgetPartiallySubstitutedPack() {
268 return TemplateArgument();
271 /// \brief "Remember" the partially-substituted pack template argument
272 /// after performing an instantiation that must preserve the parameter pack
275 /// This routine is meant to be overridden by the template instantiator.
276 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
278 /// \brief Note to the derived class when a function parameter pack is
280 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
282 /// \brief Transforms the given type into another type.
284 /// By default, this routine transforms a type by creating a
285 /// TypeSourceInfo for it and delegating to the appropriate
286 /// function. This is expensive, but we don't mind, because
287 /// this method is deprecated anyway; all users should be
288 /// switched to storing TypeSourceInfos.
290 /// \returns the transformed type.
291 QualType TransformType(QualType T);
293 /// \brief Transforms the given type-with-location into a new
294 /// type-with-location.
296 /// By default, this routine transforms a type by delegating to the
297 /// appropriate TransformXXXType to build a new type. Subclasses
298 /// may override this function (to take over all type
299 /// transformations) or some set of the TransformXXXType functions
300 /// to alter the transformation.
301 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
303 /// \brief Transform the given type-with-location into a new
304 /// type, collecting location information in the given builder
307 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
309 /// \brief Transform the given statement.
311 /// By default, this routine transforms a statement by delegating to the
312 /// appropriate TransformXXXStmt function to transform a specific kind of
313 /// statement or the TransformExpr() function to transform an expression.
314 /// Subclasses may override this function to transform statements using some
317 /// \returns the transformed statement.
318 StmtResult TransformStmt(Stmt *S);
320 /// \brief Transform the given statement.
322 /// By default, this routine transforms a statement by delegating to the
323 /// appropriate TransformOMPXXXClause function to transform a specific kind
324 /// of clause. Subclasses may override this function to transform statements
325 /// using some other mechanism.
327 /// \returns the transformed OpenMP clause.
328 OMPClause *TransformOMPClause(OMPClause *S);
330 /// \brief Transform the given attribute.
332 /// By default, this routine transforms a statement by delegating to the
333 /// appropriate TransformXXXAttr function to transform a specific kind
334 /// of attribute. Subclasses may override this function to transform
335 /// attributed statements using some other mechanism.
337 /// \returns the transformed attribute
338 const Attr *TransformAttr(const Attr *S);
340 /// \brief Transform the specified attribute.
342 /// Subclasses should override the transformation of attributes with a pragma
343 /// spelling to transform expressions stored within the attribute.
345 /// \returns the transformed attribute.
347 #define PRAGMA_SPELLING_ATTR(X) \
348 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
349 #include "clang/Basic/AttrList.inc"
351 /// \brief Transform the given expression.
353 /// By default, this routine transforms an expression by delegating to the
354 /// appropriate TransformXXXExpr function to build a new expression.
355 /// Subclasses may override this function to transform expressions using some
358 /// \returns the transformed expression.
359 ExprResult TransformExpr(Expr *E);
361 /// \brief Transform the given initializer.
363 /// By default, this routine transforms an initializer by stripping off the
364 /// semantic nodes added by initialization, then passing the result to
365 /// TransformExpr or TransformExprs.
367 /// \returns the transformed initializer.
368 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
370 /// \brief Transform the given list of expressions.
372 /// This routine transforms a list of expressions by invoking
373 /// \c TransformExpr() for each subexpression. However, it also provides
374 /// support for variadic templates by expanding any pack expansions (if the
375 /// derived class permits such expansion) along the way. When pack expansions
376 /// are present, the number of outputs may not equal the number of inputs.
378 /// \param Inputs The set of expressions to be transformed.
380 /// \param NumInputs The number of expressions in \c Inputs.
382 /// \param IsCall If \c true, then this transform is being performed on
383 /// function-call arguments, and any arguments that should be dropped, will
386 /// \param Outputs The transformed input expressions will be added to this
389 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
390 /// due to transformation.
392 /// \returns true if an error occurred, false otherwise.
393 bool TransformExprs(Expr **Inputs, unsigned NumInputs, bool IsCall,
394 SmallVectorImpl<Expr *> &Outputs,
395 bool *ArgChanged = nullptr);
397 /// \brief Transform the given declaration, which is referenced from a type
400 /// By default, acts as the identity function on declarations, unless the
401 /// transformer has had to transform the declaration itself. Subclasses
402 /// may override this function to provide alternate behavior.
403 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
404 llvm::DenseMap<Decl *, Decl *>::iterator Known
405 = TransformedLocalDecls.find(D);
406 if (Known != TransformedLocalDecls.end())
407 return Known->second;
412 /// \brief Transform the attributes associated with the given declaration and
413 /// place them on the new declaration.
415 /// By default, this operation does nothing. Subclasses may override this
416 /// behavior to transform attributes.
417 void transformAttrs(Decl *Old, Decl *New) { }
419 /// \brief Note that a local declaration has been transformed by this
422 /// Local declarations are typically transformed via a call to
423 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
424 /// the transformer itself has to transform the declarations. This routine
425 /// can be overridden by a subclass that keeps track of such mappings.
426 void transformedLocalDecl(Decl *Old, Decl *New) {
427 TransformedLocalDecls[Old] = New;
430 /// \brief Transform the definition of the given declaration.
432 /// By default, invokes TransformDecl() to transform the declaration.
433 /// Subclasses may override this function to provide alternate behavior.
434 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
435 return getDerived().TransformDecl(Loc, D);
438 /// \brief Transform the given declaration, which was the first part of a
439 /// nested-name-specifier in a member access expression.
441 /// This specific declaration transformation only applies to the first
442 /// identifier in a nested-name-specifier of a member access expression, e.g.,
443 /// the \c T in \c x->T::member
445 /// By default, invokes TransformDecl() to transform the declaration.
446 /// Subclasses may override this function to provide alternate behavior.
447 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
448 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
451 /// \brief Transform the given nested-name-specifier with source-location
454 /// By default, transforms all of the types and declarations within the
455 /// nested-name-specifier. Subclasses may override this function to provide
456 /// alternate behavior.
457 NestedNameSpecifierLoc
458 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
459 QualType ObjectType = QualType(),
460 NamedDecl *FirstQualifierInScope = nullptr);
462 /// \brief Transform the given declaration name.
464 /// By default, transforms the types of conversion function, constructor,
465 /// and destructor names and then (if needed) rebuilds the declaration name.
466 /// Identifiers and selectors are returned unmodified. Sublcasses may
467 /// override this function to provide alternate behavior.
469 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
471 /// \brief Transform the given template name.
473 /// \param SS The nested-name-specifier that qualifies the template
474 /// name. This nested-name-specifier must already have been transformed.
476 /// \param Name The template name to transform.
478 /// \param NameLoc The source location of the template name.
480 /// \param ObjectType If we're translating a template name within a member
481 /// access expression, this is the type of the object whose member template
482 /// is being referenced.
484 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
485 /// also refers to a name within the current (lexical) scope, this is the
486 /// declaration it refers to.
488 /// By default, transforms the template name by transforming the declarations
489 /// and nested-name-specifiers that occur within the template name.
490 /// Subclasses may override this function to provide alternate behavior.
492 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
493 SourceLocation NameLoc,
494 QualType ObjectType = QualType(),
495 NamedDecl *FirstQualifierInScope = nullptr);
497 /// \brief Transform the given template argument.
499 /// By default, this operation transforms the type, expression, or
500 /// declaration stored within the template argument and constructs a
501 /// new template argument from the transformed result. Subclasses may
502 /// override this function to provide alternate behavior.
504 /// Returns true if there was an error.
505 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
506 TemplateArgumentLoc &Output);
508 /// \brief Transform the given set of template arguments.
510 /// By default, this operation transforms all of the template arguments
511 /// in the input set using \c TransformTemplateArgument(), and appends
512 /// the transformed arguments to the output list.
514 /// Note that this overload of \c TransformTemplateArguments() is merely
515 /// a convenience function. Subclasses that wish to override this behavior
516 /// should override the iterator-based member template version.
518 /// \param Inputs The set of template arguments to be transformed.
520 /// \param NumInputs The number of template arguments in \p Inputs.
522 /// \param Outputs The set of transformed template arguments output by this
525 /// Returns true if an error occurred.
526 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
528 TemplateArgumentListInfo &Outputs) {
529 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs);
532 /// \brief Transform the given set of template arguments.
534 /// By default, this operation transforms all of the template arguments
535 /// in the input set using \c TransformTemplateArgument(), and appends
536 /// the transformed arguments to the output list.
538 /// \param First An iterator to the first template argument.
540 /// \param Last An iterator one step past the last template argument.
542 /// \param Outputs The set of transformed template arguments output by this
545 /// Returns true if an error occurred.
546 template<typename InputIterator>
547 bool TransformTemplateArguments(InputIterator First,
549 TemplateArgumentListInfo &Outputs);
551 /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
552 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
553 TemplateArgumentLoc &ArgLoc);
555 /// \brief Fakes up a TypeSourceInfo for a type.
556 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
557 return SemaRef.Context.getTrivialTypeSourceInfo(T,
558 getDerived().getBaseLocation());
561 #define ABSTRACT_TYPELOC(CLASS, PARENT)
562 #define TYPELOC(CLASS, PARENT) \
563 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
564 #include "clang/AST/TypeLocNodes.def"
566 template<typename Fn>
567 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
568 FunctionProtoTypeLoc TL,
569 CXXRecordDecl *ThisContext,
570 unsigned ThisTypeQuals,
571 Fn TransformExceptionSpec);
573 bool TransformExceptionSpec(SourceLocation Loc,
574 FunctionProtoType::ExceptionSpecInfo &ESI,
575 SmallVectorImpl<QualType> &Exceptions,
578 StmtResult TransformSEHHandler(Stmt *Handler);
581 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
582 TemplateSpecializationTypeLoc TL,
583 TemplateName Template);
586 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
587 DependentTemplateSpecializationTypeLoc TL,
588 TemplateName Template,
591 QualType TransformDependentTemplateSpecializationType(
592 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
593 NestedNameSpecifierLoc QualifierLoc);
595 /// \brief Transforms the parameters of a function type into the
598 /// The result vectors should be kept in sync; null entries in the
599 /// variables vector are acceptable.
601 /// Return true on error.
602 bool TransformFunctionTypeParams(SourceLocation Loc,
603 ParmVarDecl **Params, unsigned NumParams,
604 const QualType *ParamTypes,
605 SmallVectorImpl<QualType> &PTypes,
606 SmallVectorImpl<ParmVarDecl*> *PVars);
608 /// \brief Transforms a single function-type parameter. Return null
611 /// \param indexAdjustment - A number to add to the parameter's
612 /// scope index; can be negative
613 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
615 Optional<unsigned> NumExpansions,
616 bool ExpectParameterPack);
618 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
620 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
621 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
623 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
624 /// \brief Transform the captures and body of a lambda expression.
625 ExprResult TransformLambdaScope(LambdaExpr *E, CXXMethodDecl *CallOperator,
626 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes);
628 TemplateParameterList *TransformTemplateParameterList(
629 TemplateParameterList *TPL) {
633 ExprResult TransformAddressOfOperand(Expr *E);
635 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
636 bool IsAddressOfOperand,
637 TypeSourceInfo **RecoveryTSI);
639 ExprResult TransformParenDependentScopeDeclRefExpr(
640 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
641 TypeSourceInfo **RecoveryTSI);
643 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
645 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
646 // amount of stack usage with clang.
647 #define STMT(Node, Parent) \
648 LLVM_ATTRIBUTE_NOINLINE \
649 StmtResult Transform##Node(Node *S);
650 #define EXPR(Node, Parent) \
651 LLVM_ATTRIBUTE_NOINLINE \
652 ExprResult Transform##Node(Node *E);
653 #define ABSTRACT_STMT(Stmt)
654 #include "clang/AST/StmtNodes.inc"
656 #define OPENMP_CLAUSE(Name, Class) \
657 LLVM_ATTRIBUTE_NOINLINE \
658 OMPClause *Transform ## Class(Class *S);
659 #include "clang/Basic/OpenMPKinds.def"
661 /// \brief Build a new pointer type given its pointee type.
663 /// By default, performs semantic analysis when building the pointer type.
664 /// Subclasses may override this routine to provide different behavior.
665 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
667 /// \brief Build a new block pointer type given its pointee type.
669 /// By default, performs semantic analysis when building the block pointer
670 /// type. Subclasses may override this routine to provide different behavior.
671 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
673 /// \brief Build a new reference type given the type it references.
675 /// By default, performs semantic analysis when building the
676 /// reference type. Subclasses may override this routine to provide
677 /// different behavior.
679 /// \param LValue whether the type was written with an lvalue sigil
680 /// or an rvalue sigil.
681 QualType RebuildReferenceType(QualType ReferentType,
683 SourceLocation Sigil);
685 /// \brief Build a new member pointer type given the pointee type and the
686 /// class type it refers into.
688 /// By default, performs semantic analysis when building the member pointer
689 /// type. Subclasses may override this routine to provide different behavior.
690 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
691 SourceLocation Sigil);
693 /// \brief Build a new array type given the element type, size
694 /// modifier, size of the array (if known), size expression, and index type
697 /// By default, performs semantic analysis when building the array type.
698 /// Subclasses may override this routine to provide different behavior.
699 /// Also by default, all of the other Rebuild*Array
700 QualType RebuildArrayType(QualType ElementType,
701 ArrayType::ArraySizeModifier SizeMod,
702 const llvm::APInt *Size,
704 unsigned IndexTypeQuals,
705 SourceRange BracketsRange);
707 /// \brief Build a new constant array type given the element type, size
708 /// modifier, (known) size of the array, and index type qualifiers.
710 /// By default, performs semantic analysis when building the array type.
711 /// Subclasses may override this routine to provide different behavior.
712 QualType RebuildConstantArrayType(QualType ElementType,
713 ArrayType::ArraySizeModifier SizeMod,
714 const llvm::APInt &Size,
715 unsigned IndexTypeQuals,
716 SourceRange BracketsRange);
718 /// \brief Build a new incomplete array type given the element type, size
719 /// modifier, and index type qualifiers.
721 /// By default, performs semantic analysis when building the array type.
722 /// Subclasses may override this routine to provide different behavior.
723 QualType RebuildIncompleteArrayType(QualType ElementType,
724 ArrayType::ArraySizeModifier SizeMod,
725 unsigned IndexTypeQuals,
726 SourceRange BracketsRange);
728 /// \brief Build a new variable-length array type given the element type,
729 /// size modifier, size expression, and index type qualifiers.
731 /// By default, performs semantic analysis when building the array type.
732 /// Subclasses may override this routine to provide different behavior.
733 QualType RebuildVariableArrayType(QualType ElementType,
734 ArrayType::ArraySizeModifier SizeMod,
736 unsigned IndexTypeQuals,
737 SourceRange BracketsRange);
739 /// \brief Build a new dependent-sized array type given the element type,
740 /// size modifier, size expression, and index type qualifiers.
742 /// By default, performs semantic analysis when building the array type.
743 /// Subclasses may override this routine to provide different behavior.
744 QualType RebuildDependentSizedArrayType(QualType ElementType,
745 ArrayType::ArraySizeModifier SizeMod,
747 unsigned IndexTypeQuals,
748 SourceRange BracketsRange);
750 /// \brief Build a new vector type given the element type and
751 /// number of elements.
753 /// By default, performs semantic analysis when building the vector type.
754 /// Subclasses may override this routine to provide different behavior.
755 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
756 VectorType::VectorKind VecKind);
758 /// \brief Build a new extended vector type given the element type and
759 /// number of elements.
761 /// By default, performs semantic analysis when building the vector type.
762 /// Subclasses may override this routine to provide different behavior.
763 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
764 SourceLocation AttributeLoc);
766 /// \brief Build a new potentially dependently-sized extended vector type
767 /// given the element type and number of elements.
769 /// By default, performs semantic analysis when building the vector type.
770 /// Subclasses may override this routine to provide different behavior.
771 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
773 SourceLocation AttributeLoc);
775 /// \brief Build a new function type.
777 /// By default, performs semantic analysis when building the function type.
778 /// Subclasses may override this routine to provide different behavior.
779 QualType RebuildFunctionProtoType(QualType T,
780 MutableArrayRef<QualType> ParamTypes,
781 const FunctionProtoType::ExtProtoInfo &EPI);
783 /// \brief Build a new unprototyped function type.
784 QualType RebuildFunctionNoProtoType(QualType ResultType);
786 /// \brief Rebuild an unresolved typename type, given the decl that
787 /// the UnresolvedUsingTypenameDecl was transformed to.
788 QualType RebuildUnresolvedUsingType(Decl *D);
790 /// \brief Build a new typedef type.
791 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
792 return SemaRef.Context.getTypeDeclType(Typedef);
795 /// \brief Build a new class/struct/union type.
796 QualType RebuildRecordType(RecordDecl *Record) {
797 return SemaRef.Context.getTypeDeclType(Record);
800 /// \brief Build a new Enum type.
801 QualType RebuildEnumType(EnumDecl *Enum) {
802 return SemaRef.Context.getTypeDeclType(Enum);
805 /// \brief Build a new typeof(expr) type.
807 /// By default, performs semantic analysis when building the typeof type.
808 /// Subclasses may override this routine to provide different behavior.
809 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
811 /// \brief Build a new typeof(type) type.
813 /// By default, builds a new TypeOfType with the given underlying type.
814 QualType RebuildTypeOfType(QualType Underlying);
816 /// \brief Build a new unary transform type.
817 QualType RebuildUnaryTransformType(QualType BaseType,
818 UnaryTransformType::UTTKind UKind,
821 /// \brief Build a new C++11 decltype type.
823 /// By default, performs semantic analysis when building the decltype type.
824 /// Subclasses may override this routine to provide different behavior.
825 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
827 /// \brief Build a new C++11 auto type.
829 /// By default, builds a new AutoType with the given deduced type.
830 QualType RebuildAutoType(QualType Deduced, bool IsDecltypeAuto) {
831 // Note, IsDependent is always false here: we implicitly convert an 'auto'
832 // which has been deduced to a dependent type into an undeduced 'auto', so
833 // that we'll retry deduction after the transformation.
834 return SemaRef.Context.getAutoType(Deduced, IsDecltypeAuto,
835 /*IsDependent*/ false);
838 /// \brief Build a new template specialization type.
840 /// By default, performs semantic analysis when building the template
841 /// specialization type. Subclasses may override this routine to provide
842 /// different behavior.
843 QualType RebuildTemplateSpecializationType(TemplateName Template,
844 SourceLocation TemplateLoc,
845 TemplateArgumentListInfo &Args);
847 /// \brief Build a new parenthesized type.
849 /// By default, builds a new ParenType type from the inner type.
850 /// Subclasses may override this routine to provide different behavior.
851 QualType RebuildParenType(QualType InnerType) {
852 return SemaRef.Context.getParenType(InnerType);
855 /// \brief Build a new qualified name type.
857 /// By default, builds a new ElaboratedType type from the keyword,
858 /// the nested-name-specifier and the named type.
859 /// Subclasses may override this routine to provide different behavior.
860 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
861 ElaboratedTypeKeyword Keyword,
862 NestedNameSpecifierLoc QualifierLoc,
864 return SemaRef.Context.getElaboratedType(Keyword,
865 QualifierLoc.getNestedNameSpecifier(),
869 /// \brief Build a new typename type that refers to a template-id.
871 /// By default, builds a new DependentNameType type from the
872 /// nested-name-specifier and the given type. Subclasses may override
873 /// this routine to provide different behavior.
874 QualType RebuildDependentTemplateSpecializationType(
875 ElaboratedTypeKeyword Keyword,
876 NestedNameSpecifierLoc QualifierLoc,
877 const IdentifierInfo *Name,
878 SourceLocation NameLoc,
879 TemplateArgumentListInfo &Args) {
880 // Rebuild the template name.
881 // TODO: avoid TemplateName abstraction
883 SS.Adopt(QualifierLoc);
884 TemplateName InstName
885 = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(),
888 if (InstName.isNull())
891 // If it's still dependent, make a dependent specialization.
892 if (InstName.getAsDependentTemplateName())
893 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
894 QualifierLoc.getNestedNameSpecifier(),
898 // Otherwise, make an elaborated type wrapping a non-dependent
901 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
902 if (T.isNull()) return QualType();
904 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
907 return SemaRef.Context.getElaboratedType(Keyword,
908 QualifierLoc.getNestedNameSpecifier(),
912 /// \brief Build a new typename type that refers to an identifier.
914 /// By default, performs semantic analysis when building the typename type
915 /// (or elaborated type). Subclasses may override this routine to provide
916 /// different behavior.
917 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
918 SourceLocation KeywordLoc,
919 NestedNameSpecifierLoc QualifierLoc,
920 const IdentifierInfo *Id,
921 SourceLocation IdLoc) {
923 SS.Adopt(QualifierLoc);
925 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
926 // If the name is still dependent, just build a new dependent name type.
927 if (!SemaRef.computeDeclContext(SS))
928 return SemaRef.Context.getDependentNameType(Keyword,
929 QualifierLoc.getNestedNameSpecifier(),
933 if (Keyword == ETK_None || Keyword == ETK_Typename)
934 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
937 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
939 // We had a dependent elaborated-type-specifier that has been transformed
940 // into a non-dependent elaborated-type-specifier. Find the tag we're
942 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
943 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
947 if (SemaRef.RequireCompleteDeclContext(SS, DC))
950 TagDecl *Tag = nullptr;
951 SemaRef.LookupQualifiedName(Result, DC);
952 switch (Result.getResultKind()) {
953 case LookupResult::NotFound:
954 case LookupResult::NotFoundInCurrentInstantiation:
957 case LookupResult::Found:
958 Tag = Result.getAsSingle<TagDecl>();
961 case LookupResult::FoundOverloaded:
962 case LookupResult::FoundUnresolvedValue:
963 llvm_unreachable("Tag lookup cannot find non-tags");
965 case LookupResult::Ambiguous:
966 // Let the LookupResult structure handle ambiguities.
971 // Check where the name exists but isn't a tag type and use that to emit
972 // better diagnostics.
973 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
974 SemaRef.LookupQualifiedName(Result, DC);
975 switch (Result.getResultKind()) {
976 case LookupResult::Found:
977 case LookupResult::FoundOverloaded:
978 case LookupResult::FoundUnresolvedValue: {
979 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
981 if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
982 else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
983 else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
984 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
985 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
989 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
990 << Kind << Id << DC << QualifierLoc.getSourceRange();
996 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
998 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
999 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1003 // Build the elaborated-type-specifier type.
1004 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1005 return SemaRef.Context.getElaboratedType(Keyword,
1006 QualifierLoc.getNestedNameSpecifier(),
1010 /// \brief Build a new pack expansion type.
1012 /// By default, builds a new PackExpansionType type from the given pattern.
1013 /// Subclasses may override this routine to provide different behavior.
1014 QualType RebuildPackExpansionType(QualType Pattern,
1015 SourceRange PatternRange,
1016 SourceLocation EllipsisLoc,
1017 Optional<unsigned> NumExpansions) {
1018 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1022 /// \brief Build a new atomic type given its value type.
1024 /// By default, performs semantic analysis when building the atomic type.
1025 /// Subclasses may override this routine to provide different behavior.
1026 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1028 /// \brief Build a new template name given a nested name specifier, a flag
1029 /// indicating whether the "template" keyword was provided, and the template
1030 /// that the template name refers to.
1032 /// By default, builds the new template name directly. Subclasses may override
1033 /// this routine to provide different behavior.
1034 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1036 TemplateDecl *Template);
1038 /// \brief Build a new template name given a nested name specifier and the
1039 /// name that is referred to as a template.
1041 /// By default, performs semantic analysis to determine whether the name can
1042 /// be resolved to a specific template, then builds the appropriate kind of
1043 /// template name. Subclasses may override this routine to provide different
1045 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1046 const IdentifierInfo &Name,
1047 SourceLocation NameLoc,
1048 QualType ObjectType,
1049 NamedDecl *FirstQualifierInScope);
1051 /// \brief Build a new template name given a nested name specifier and the
1052 /// overloaded operator name that is referred to as a template.
1054 /// By default, performs semantic analysis to determine whether the name can
1055 /// be resolved to a specific template, then builds the appropriate kind of
1056 /// template name. Subclasses may override this routine to provide different
1058 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1059 OverloadedOperatorKind Operator,
1060 SourceLocation NameLoc,
1061 QualType ObjectType);
1063 /// \brief Build a new template name given a template template parameter pack
1066 /// By default, performs semantic analysis to determine whether the name can
1067 /// be resolved to a specific template, then builds the appropriate kind of
1068 /// template name. Subclasses may override this routine to provide different
1070 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1071 const TemplateArgument &ArgPack) {
1072 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1075 /// \brief Build a new compound statement.
1077 /// By default, performs semantic analysis to build the new statement.
1078 /// Subclasses may override this routine to provide different behavior.
1079 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1080 MultiStmtArg Statements,
1081 SourceLocation RBraceLoc,
1083 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1087 /// \brief Build a new case statement.
1089 /// By default, performs semantic analysis to build the new statement.
1090 /// Subclasses may override this routine to provide different behavior.
1091 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1093 SourceLocation EllipsisLoc,
1095 SourceLocation ColonLoc) {
1096 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1100 /// \brief Attach the body to a new case statement.
1102 /// By default, performs semantic analysis to build the new statement.
1103 /// Subclasses may override this routine to provide different behavior.
1104 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1105 getSema().ActOnCaseStmtBody(S, Body);
1109 /// \brief Build a new default statement.
1111 /// By default, performs semantic analysis to build the new statement.
1112 /// Subclasses may override this routine to provide different behavior.
1113 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1114 SourceLocation ColonLoc,
1116 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1117 /*CurScope=*/nullptr);
1120 /// \brief Build a new label statement.
1122 /// By default, performs semantic analysis to build the new statement.
1123 /// Subclasses may override this routine to provide different behavior.
1124 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1125 SourceLocation ColonLoc, Stmt *SubStmt) {
1126 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1129 /// \brief Build a new label statement.
1131 /// By default, performs semantic analysis to build the new statement.
1132 /// Subclasses may override this routine to provide different behavior.
1133 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1134 ArrayRef<const Attr*> Attrs,
1136 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1139 /// \brief Build a new "if" statement.
1141 /// By default, performs semantic analysis to build the new statement.
1142 /// Subclasses may override this routine to provide different behavior.
1143 StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
1144 VarDecl *CondVar, Stmt *Then,
1145 SourceLocation ElseLoc, Stmt *Else) {
1146 return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
1149 /// \brief Start building a new switch statement.
1151 /// By default, performs semantic analysis to build the new statement.
1152 /// Subclasses may override this routine to provide different behavior.
1153 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1154 Expr *Cond, VarDecl *CondVar) {
1155 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
1159 /// \brief Attach the body to the switch statement.
1161 /// By default, performs semantic analysis to build the new statement.
1162 /// Subclasses may override this routine to provide different behavior.
1163 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1164 Stmt *Switch, Stmt *Body) {
1165 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1168 /// \brief Build a new while statement.
1170 /// By default, performs semantic analysis to build the new statement.
1171 /// Subclasses may override this routine to provide different behavior.
1172 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
1173 VarDecl *CondVar, Stmt *Body) {
1174 return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
1177 /// \brief Build a new do-while statement.
1179 /// By default, performs semantic analysis to build the new statement.
1180 /// Subclasses may override this routine to provide different behavior.
1181 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1182 SourceLocation WhileLoc, SourceLocation LParenLoc,
1183 Expr *Cond, SourceLocation RParenLoc) {
1184 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1188 /// \brief Build a new for statement.
1190 /// By default, performs semantic analysis to build the new statement.
1191 /// Subclasses may override this routine to provide different behavior.
1192 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1193 Stmt *Init, Sema::FullExprArg Cond,
1194 VarDecl *CondVar, Sema::FullExprArg Inc,
1195 SourceLocation RParenLoc, Stmt *Body) {
1196 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1197 CondVar, Inc, RParenLoc, Body);
1200 /// \brief Build a new goto statement.
1202 /// By default, performs semantic analysis to build the new statement.
1203 /// Subclasses may override this routine to provide different behavior.
1204 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1206 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1209 /// \brief Build a new indirect goto statement.
1211 /// By default, performs semantic analysis to build the new statement.
1212 /// Subclasses may override this routine to provide different behavior.
1213 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1214 SourceLocation StarLoc,
1216 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1219 /// \brief Build a new return statement.
1221 /// By default, performs semantic analysis to build the new statement.
1222 /// Subclasses may override this routine to provide different behavior.
1223 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1224 return getSema().BuildReturnStmt(ReturnLoc, Result);
1227 /// \brief Build a new declaration statement.
1229 /// By default, performs semantic analysis to build the new statement.
1230 /// Subclasses may override this routine to provide different behavior.
1231 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1232 SourceLocation StartLoc, SourceLocation EndLoc) {
1233 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1234 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1237 /// \brief Build a new inline asm statement.
1239 /// By default, performs semantic analysis to build the new statement.
1240 /// Subclasses may override this routine to provide different behavior.
1241 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1242 bool IsVolatile, unsigned NumOutputs,
1243 unsigned NumInputs, IdentifierInfo **Names,
1244 MultiExprArg Constraints, MultiExprArg Exprs,
1245 Expr *AsmString, MultiExprArg Clobbers,
1246 SourceLocation RParenLoc) {
1247 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1248 NumInputs, Names, Constraints, Exprs,
1249 AsmString, Clobbers, RParenLoc);
1252 /// \brief Build a new MS style inline asm statement.
1254 /// By default, performs semantic analysis to build the new statement.
1255 /// Subclasses may override this routine to provide different behavior.
1256 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1257 ArrayRef<Token> AsmToks,
1258 StringRef AsmString,
1259 unsigned NumOutputs, unsigned NumInputs,
1260 ArrayRef<StringRef> Constraints,
1261 ArrayRef<StringRef> Clobbers,
1262 ArrayRef<Expr*> Exprs,
1263 SourceLocation EndLoc) {
1264 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1265 NumOutputs, NumInputs,
1266 Constraints, Clobbers, Exprs, EndLoc);
1269 /// \brief Build a new Objective-C \@try statement.
1271 /// By default, performs semantic analysis to build the new statement.
1272 /// Subclasses may override this routine to provide different behavior.
1273 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1275 MultiStmtArg CatchStmts,
1277 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1281 /// \brief Rebuild an Objective-C exception declaration.
1283 /// By default, performs semantic analysis to build the new declaration.
1284 /// Subclasses may override this routine to provide different behavior.
1285 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1286 TypeSourceInfo *TInfo, QualType T) {
1287 return getSema().BuildObjCExceptionDecl(TInfo, T,
1288 ExceptionDecl->getInnerLocStart(),
1289 ExceptionDecl->getLocation(),
1290 ExceptionDecl->getIdentifier());
1293 /// \brief Build a new Objective-C \@catch statement.
1295 /// By default, performs semantic analysis to build the new statement.
1296 /// Subclasses may override this routine to provide different behavior.
1297 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1298 SourceLocation RParenLoc,
1301 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1305 /// \brief Build a new Objective-C \@finally statement.
1307 /// By default, performs semantic analysis to build the new statement.
1308 /// Subclasses may override this routine to provide different behavior.
1309 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1311 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1314 /// \brief Build a new Objective-C \@throw statement.
1316 /// By default, performs semantic analysis to build the new statement.
1317 /// Subclasses may override this routine to provide different behavior.
1318 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1320 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1323 /// \brief Build a new OpenMP executable directive.
1325 /// By default, performs semantic analysis to build the new statement.
1326 /// Subclasses may override this routine to provide different behavior.
1327 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1328 DeclarationNameInfo DirName,
1329 ArrayRef<OMPClause *> Clauses,
1330 Stmt *AStmt, SourceLocation StartLoc,
1331 SourceLocation EndLoc) {
1332 return getSema().ActOnOpenMPExecutableDirective(Kind, DirName, Clauses,
1333 AStmt, StartLoc, EndLoc);
1336 /// \brief Build a new OpenMP 'if' clause.
1338 /// By default, performs semantic analysis to build the new OpenMP clause.
1339 /// Subclasses may override this routine to provide different behavior.
1340 OMPClause *RebuildOMPIfClause(Expr *Condition,
1341 SourceLocation StartLoc,
1342 SourceLocation LParenLoc,
1343 SourceLocation EndLoc) {
1344 return getSema().ActOnOpenMPIfClause(Condition, StartLoc,
1348 /// \brief Build a new OpenMP 'final' clause.
1350 /// By default, performs semantic analysis to build the new OpenMP clause.
1351 /// Subclasses may override this routine to provide different behavior.
1352 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1353 SourceLocation LParenLoc,
1354 SourceLocation EndLoc) {
1355 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1359 /// \brief Build a new OpenMP 'num_threads' clause.
1361 /// By default, performs semantic analysis to build the new OpenMP clause.
1362 /// Subclasses may override this routine to provide different behavior.
1363 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1364 SourceLocation StartLoc,
1365 SourceLocation LParenLoc,
1366 SourceLocation EndLoc) {
1367 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1371 /// \brief Build a new OpenMP 'safelen' clause.
1373 /// By default, performs semantic analysis to build the new OpenMP clause.
1374 /// Subclasses may override this routine to provide different behavior.
1375 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1376 SourceLocation LParenLoc,
1377 SourceLocation EndLoc) {
1378 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1381 /// \brief Build a new OpenMP 'collapse' clause.
1383 /// By default, performs semantic analysis to build the new OpenMP clause.
1384 /// Subclasses may override this routine to provide different behavior.
1385 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1386 SourceLocation LParenLoc,
1387 SourceLocation EndLoc) {
1388 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1392 /// \brief Build a new OpenMP 'default' clause.
1394 /// By default, performs semantic analysis to build the new OpenMP clause.
1395 /// Subclasses may override this routine to provide different behavior.
1396 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1397 SourceLocation KindKwLoc,
1398 SourceLocation StartLoc,
1399 SourceLocation LParenLoc,
1400 SourceLocation EndLoc) {
1401 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1402 StartLoc, LParenLoc, EndLoc);
1405 /// \brief Build a new OpenMP 'proc_bind' clause.
1407 /// By default, performs semantic analysis to build the new OpenMP clause.
1408 /// Subclasses may override this routine to provide different behavior.
1409 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1410 SourceLocation KindKwLoc,
1411 SourceLocation StartLoc,
1412 SourceLocation LParenLoc,
1413 SourceLocation EndLoc) {
1414 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1415 StartLoc, LParenLoc, EndLoc);
1418 /// \brief Build a new OpenMP 'schedule' clause.
1420 /// By default, performs semantic analysis to build the new OpenMP clause.
1421 /// Subclasses may override this routine to provide different behavior.
1422 OMPClause *RebuildOMPScheduleClause(OpenMPScheduleClauseKind Kind,
1424 SourceLocation StartLoc,
1425 SourceLocation LParenLoc,
1426 SourceLocation KindLoc,
1427 SourceLocation CommaLoc,
1428 SourceLocation EndLoc) {
1429 return getSema().ActOnOpenMPScheduleClause(
1430 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1433 /// \brief Build a new OpenMP 'private' clause.
1435 /// By default, performs semantic analysis to build the new OpenMP clause.
1436 /// Subclasses may override this routine to provide different behavior.
1437 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1438 SourceLocation StartLoc,
1439 SourceLocation LParenLoc,
1440 SourceLocation EndLoc) {
1441 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1445 /// \brief Build a new OpenMP 'firstprivate' clause.
1447 /// By default, performs semantic analysis to build the new OpenMP clause.
1448 /// Subclasses may override this routine to provide different behavior.
1449 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1450 SourceLocation StartLoc,
1451 SourceLocation LParenLoc,
1452 SourceLocation EndLoc) {
1453 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1457 /// \brief Build a new OpenMP 'lastprivate' clause.
1459 /// By default, performs semantic analysis to build the new OpenMP clause.
1460 /// Subclasses may override this routine to provide different behavior.
1461 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1462 SourceLocation StartLoc,
1463 SourceLocation LParenLoc,
1464 SourceLocation EndLoc) {
1465 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1469 /// \brief Build a new OpenMP 'shared' clause.
1471 /// By default, performs semantic analysis to build the new OpenMP clause.
1472 /// Subclasses may override this routine to provide different behavior.
1473 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1474 SourceLocation StartLoc,
1475 SourceLocation LParenLoc,
1476 SourceLocation EndLoc) {
1477 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1481 /// \brief Build a new OpenMP 'reduction' clause.
1483 /// By default, performs semantic analysis to build the new statement.
1484 /// Subclasses may override this routine to provide different behavior.
1485 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1486 SourceLocation StartLoc,
1487 SourceLocation LParenLoc,
1488 SourceLocation ColonLoc,
1489 SourceLocation EndLoc,
1490 CXXScopeSpec &ReductionIdScopeSpec,
1491 const DeclarationNameInfo &ReductionId) {
1492 return getSema().ActOnOpenMPReductionClause(
1493 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1497 /// \brief Build a new OpenMP 'linear' clause.
1499 /// By default, performs semantic analysis to build the new OpenMP clause.
1500 /// Subclasses may override this routine to provide different behavior.
1501 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1502 SourceLocation StartLoc,
1503 SourceLocation LParenLoc,
1504 SourceLocation ColonLoc,
1505 SourceLocation EndLoc) {
1506 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1510 /// \brief Build a new OpenMP 'aligned' clause.
1512 /// By default, performs semantic analysis to build the new OpenMP clause.
1513 /// Subclasses may override this routine to provide different behavior.
1514 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1515 SourceLocation StartLoc,
1516 SourceLocation LParenLoc,
1517 SourceLocation ColonLoc,
1518 SourceLocation EndLoc) {
1519 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1520 LParenLoc, ColonLoc, EndLoc);
1523 /// \brief Build a new OpenMP 'copyin' clause.
1525 /// By default, performs semantic analysis to build the new OpenMP clause.
1526 /// Subclasses may override this routine to provide different behavior.
1527 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1528 SourceLocation StartLoc,
1529 SourceLocation LParenLoc,
1530 SourceLocation EndLoc) {
1531 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1535 /// \brief Build a new OpenMP 'copyprivate' clause.
1537 /// By default, performs semantic analysis to build the new OpenMP clause.
1538 /// Subclasses may override this routine to provide different behavior.
1539 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1540 SourceLocation StartLoc,
1541 SourceLocation LParenLoc,
1542 SourceLocation EndLoc) {
1543 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1547 /// \brief Build a new OpenMP 'flush' pseudo clause.
1549 /// By default, performs semantic analysis to build the new OpenMP clause.
1550 /// Subclasses may override this routine to provide different behavior.
1551 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1552 SourceLocation StartLoc,
1553 SourceLocation LParenLoc,
1554 SourceLocation EndLoc) {
1555 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1559 /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
1561 /// By default, performs semantic analysis to build the new statement.
1562 /// Subclasses may override this routine to provide different behavior.
1563 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1565 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1568 /// \brief Build a new Objective-C \@synchronized statement.
1570 /// By default, performs semantic analysis to build the new statement.
1571 /// Subclasses may override this routine to provide different behavior.
1572 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1573 Expr *Object, Stmt *Body) {
1574 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1577 /// \brief Build a new Objective-C \@autoreleasepool statement.
1579 /// By default, performs semantic analysis to build the new statement.
1580 /// Subclasses may override this routine to provide different behavior.
1581 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1583 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1586 /// \brief Build a new Objective-C fast enumeration statement.
1588 /// By default, performs semantic analysis to build the new statement.
1589 /// Subclasses may override this routine to provide different behavior.
1590 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1593 SourceLocation RParenLoc,
1595 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1599 if (ForEachStmt.isInvalid())
1602 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
1605 /// \brief Build a new C++ exception declaration.
1607 /// By default, performs semantic analysis to build the new decaration.
1608 /// Subclasses may override this routine to provide different behavior.
1609 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1610 TypeSourceInfo *Declarator,
1611 SourceLocation StartLoc,
1612 SourceLocation IdLoc,
1613 IdentifierInfo *Id) {
1614 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
1615 StartLoc, IdLoc, Id);
1617 getSema().CurContext->addDecl(Var);
1621 /// \brief Build a new C++ catch statement.
1623 /// By default, performs semantic analysis to build the new statement.
1624 /// Subclasses may override this routine to provide different behavior.
1625 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
1626 VarDecl *ExceptionDecl,
1628 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
1632 /// \brief Build a new C++ try statement.
1634 /// By default, performs semantic analysis to build the new statement.
1635 /// Subclasses may override this routine to provide different behavior.
1636 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
1637 ArrayRef<Stmt *> Handlers) {
1638 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
1641 /// \brief Build a new C++0x range-based for statement.
1643 /// By default, performs semantic analysis to build the new statement.
1644 /// Subclasses may override this routine to provide different behavior.
1645 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
1646 SourceLocation ColonLoc,
1647 Stmt *Range, Stmt *BeginEnd,
1648 Expr *Cond, Expr *Inc,
1650 SourceLocation RParenLoc) {
1651 // If we've just learned that the range is actually an Objective-C
1652 // collection, treat this as an Objective-C fast enumeration loop.
1653 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
1654 if (RangeStmt->isSingleDecl()) {
1655 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
1656 if (RangeVar->isInvalidDecl())
1659 Expr *RangeExpr = RangeVar->getInit();
1660 if (!RangeExpr->isTypeDependent() &&
1661 RangeExpr->getType()->isObjCObjectPointerType())
1662 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
1668 return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEnd,
1669 Cond, Inc, LoopVar, RParenLoc,
1670 Sema::BFRK_Rebuild);
1673 /// \brief Build a new C++0x range-based for statement.
1675 /// By default, performs semantic analysis to build the new statement.
1676 /// Subclasses may override this routine to provide different behavior.
1677 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
1679 NestedNameSpecifierLoc QualifierLoc,
1680 DeclarationNameInfo NameInfo,
1682 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
1683 QualifierLoc, NameInfo, Nested);
1686 /// \brief Attach body to a C++0x range-based for statement.
1688 /// By default, performs semantic analysis to finish the new statement.
1689 /// Subclasses may override this routine to provide different behavior.
1690 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
1691 return getSema().FinishCXXForRangeStmt(ForRange, Body);
1694 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
1695 Stmt *TryBlock, Stmt *Handler) {
1696 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
1699 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
1701 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
1704 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
1705 return getSema().ActOnSEHFinallyBlock(Loc, Block);
1708 /// \brief Build a new predefined expression.
1710 /// By default, performs semantic analysis to build the new expression.
1711 /// Subclasses may override this routine to provide different behavior.
1712 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
1713 PredefinedExpr::IdentType IT) {
1714 return getSema().BuildPredefinedExpr(Loc, IT);
1717 /// \brief Build a new expression that references a declaration.
1719 /// By default, performs semantic analysis to build the new expression.
1720 /// Subclasses may override this routine to provide different behavior.
1721 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
1724 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
1728 /// \brief Build a new expression that references a declaration.
1730 /// By default, performs semantic analysis to build the new expression.
1731 /// Subclasses may override this routine to provide different behavior.
1732 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
1734 const DeclarationNameInfo &NameInfo,
1735 TemplateArgumentListInfo *TemplateArgs) {
1737 SS.Adopt(QualifierLoc);
1739 // FIXME: loses template args.
1741 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
1744 /// \brief Build a new expression in parentheses.
1746 /// By default, performs semantic analysis to build the new expression.
1747 /// Subclasses may override this routine to provide different behavior.
1748 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
1749 SourceLocation RParen) {
1750 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
1753 /// \brief Build a new pseudo-destructor expression.
1755 /// By default, performs semantic analysis to build the new expression.
1756 /// Subclasses may override this routine to provide different behavior.
1757 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
1758 SourceLocation OperatorLoc,
1761 TypeSourceInfo *ScopeType,
1762 SourceLocation CCLoc,
1763 SourceLocation TildeLoc,
1764 PseudoDestructorTypeStorage Destroyed);
1766 /// \brief Build a new unary operator expression.
1768 /// By default, performs semantic analysis to build the new expression.
1769 /// Subclasses may override this routine to provide different behavior.
1770 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
1771 UnaryOperatorKind Opc,
1773 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
1776 /// \brief Build a new builtin offsetof expression.
1778 /// By default, performs semantic analysis to build the new expression.
1779 /// Subclasses may override this routine to provide different behavior.
1780 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
1781 TypeSourceInfo *Type,
1782 Sema::OffsetOfComponent *Components,
1783 unsigned NumComponents,
1784 SourceLocation RParenLoc) {
1785 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
1786 NumComponents, RParenLoc);
1789 /// \brief Build a new sizeof, alignof or vec_step expression with a
1792 /// By default, performs semantic analysis to build the new expression.
1793 /// Subclasses may override this routine to provide different behavior.
1794 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
1795 SourceLocation OpLoc,
1796 UnaryExprOrTypeTrait ExprKind,
1798 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
1801 /// \brief Build a new sizeof, alignof or vec step expression with an
1802 /// expression argument.
1804 /// By default, performs semantic analysis to build the new expression.
1805 /// Subclasses may override this routine to provide different behavior.
1806 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
1807 UnaryExprOrTypeTrait ExprKind,
1810 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
1811 if (Result.isInvalid())
1817 /// \brief Build a new array subscript expression.
1819 /// By default, performs semantic analysis to build the new expression.
1820 /// Subclasses may override this routine to provide different behavior.
1821 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
1822 SourceLocation LBracketLoc,
1824 SourceLocation RBracketLoc) {
1825 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
1830 /// \brief Build a new call expression.
1832 /// By default, performs semantic analysis to build the new expression.
1833 /// Subclasses may override this routine to provide different behavior.
1834 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
1836 SourceLocation RParenLoc,
1837 Expr *ExecConfig = nullptr) {
1838 return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
1839 Args, RParenLoc, ExecConfig);
1842 /// \brief Build a new member access expression.
1844 /// By default, performs semantic analysis to build the new expression.
1845 /// Subclasses may override this routine to provide different behavior.
1846 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
1848 NestedNameSpecifierLoc QualifierLoc,
1849 SourceLocation TemplateKWLoc,
1850 const DeclarationNameInfo &MemberNameInfo,
1852 NamedDecl *FoundDecl,
1853 const TemplateArgumentListInfo *ExplicitTemplateArgs,
1854 NamedDecl *FirstQualifierInScope) {
1855 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
1857 if (!Member->getDeclName()) {
1858 // We have a reference to an unnamed field. This is always the
1859 // base of an anonymous struct/union member access, i.e. the
1860 // field is always of record type.
1861 assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
1862 assert(Member->getType()->isRecordType() &&
1863 "unnamed member not of record type?");
1866 getSema().PerformObjectMemberConversion(BaseResult.get(),
1867 QualifierLoc.getNestedNameSpecifier(),
1869 if (BaseResult.isInvalid())
1871 Base = BaseResult.get();
1872 ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
1874 new (getSema().Context) MemberExpr(Base, isArrow,
1875 Member, MemberNameInfo,
1876 cast<FieldDecl>(Member)->getType(),
1882 SS.Adopt(QualifierLoc);
1884 Base = BaseResult.get();
1885 QualType BaseType = Base->getType();
1887 // FIXME: this involves duplicating earlier analysis in a lot of
1888 // cases; we should avoid this when possible.
1889 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
1890 R.addDecl(FoundDecl);
1893 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
1895 FirstQualifierInScope,
1896 R, ExplicitTemplateArgs);
1899 /// \brief Build a new binary operator expression.
1901 /// By default, performs semantic analysis to build the new expression.
1902 /// Subclasses may override this routine to provide different behavior.
1903 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
1904 BinaryOperatorKind Opc,
1905 Expr *LHS, Expr *RHS) {
1906 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
1909 /// \brief Build a new conditional operator expression.
1911 /// By default, performs semantic analysis to build the new expression.
1912 /// Subclasses may override this routine to provide different behavior.
1913 ExprResult RebuildConditionalOperator(Expr *Cond,
1914 SourceLocation QuestionLoc,
1916 SourceLocation ColonLoc,
1918 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
1922 /// \brief Build a new C-style cast expression.
1924 /// By default, performs semantic analysis to build the new expression.
1925 /// Subclasses may override this routine to provide different behavior.
1926 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
1927 TypeSourceInfo *TInfo,
1928 SourceLocation RParenLoc,
1930 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
1934 /// \brief Build a new compound literal expression.
1936 /// By default, performs semantic analysis to build the new expression.
1937 /// Subclasses may override this routine to provide different behavior.
1938 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
1939 TypeSourceInfo *TInfo,
1940 SourceLocation RParenLoc,
1942 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
1946 /// \brief Build a new extended vector element access expression.
1948 /// By default, performs semantic analysis to build the new expression.
1949 /// Subclasses may override this routine to provide different behavior.
1950 ExprResult RebuildExtVectorElementExpr(Expr *Base,
1951 SourceLocation OpLoc,
1952 SourceLocation AccessorLoc,
1953 IdentifierInfo &Accessor) {
1956 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
1957 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
1958 OpLoc, /*IsArrow*/ false,
1959 SS, SourceLocation(),
1960 /*FirstQualifierInScope*/ nullptr,
1962 /* TemplateArgs */ nullptr);
1965 /// \brief Build a new initializer list expression.
1967 /// By default, performs semantic analysis to build the new expression.
1968 /// Subclasses may override this routine to provide different behavior.
1969 ExprResult RebuildInitList(SourceLocation LBraceLoc,
1971 SourceLocation RBraceLoc,
1972 QualType ResultTy) {
1974 = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
1975 if (Result.isInvalid() || ResultTy->isDependentType())
1978 // Patch in the result type we were given, which may have been computed
1979 // when the initial InitListExpr was built.
1980 InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
1981 ILE->setType(ResultTy);
1985 /// \brief Build a new designated initializer expression.
1987 /// By default, performs semantic analysis to build the new expression.
1988 /// Subclasses may override this routine to provide different behavior.
1989 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
1990 MultiExprArg ArrayExprs,
1991 SourceLocation EqualOrColonLoc,
1995 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
1997 if (Result.isInvalid())
2003 /// \brief Build a new value-initialized expression.
2005 /// By default, builds the implicit value initialization without performing
2006 /// any semantic analysis. Subclasses may override this routine to provide
2007 /// different behavior.
2008 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2009 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2012 /// \brief Build a new \c va_arg expression.
2014 /// By default, performs semantic analysis to build the new expression.
2015 /// Subclasses may override this routine to provide different behavior.
2016 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2017 Expr *SubExpr, TypeSourceInfo *TInfo,
2018 SourceLocation RParenLoc) {
2019 return getSema().BuildVAArgExpr(BuiltinLoc,
2024 /// \brief Build a new expression list in parentheses.
2026 /// By default, performs semantic analysis to build the new expression.
2027 /// Subclasses may override this routine to provide different behavior.
2028 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2029 MultiExprArg SubExprs,
2030 SourceLocation RParenLoc) {
2031 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2034 /// \brief Build a new address-of-label expression.
2036 /// By default, performs semantic analysis, using the name of the label
2037 /// rather than attempting to map the label statement itself.
2038 /// Subclasses may override this routine to provide different behavior.
2039 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2040 SourceLocation LabelLoc, LabelDecl *Label) {
2041 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2044 /// \brief Build a new GNU statement expression.
2046 /// By default, performs semantic analysis to build the new expression.
2047 /// Subclasses may override this routine to provide different behavior.
2048 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2050 SourceLocation RParenLoc) {
2051 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2054 /// \brief Build a new __builtin_choose_expr expression.
2056 /// By default, performs semantic analysis to build the new expression.
2057 /// Subclasses may override this routine to provide different behavior.
2058 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2059 Expr *Cond, Expr *LHS, Expr *RHS,
2060 SourceLocation RParenLoc) {
2061 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2066 /// \brief Build a new generic selection expression.
2068 /// By default, performs semantic analysis to build the new expression.
2069 /// Subclasses may override this routine to provide different behavior.
2070 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2071 SourceLocation DefaultLoc,
2072 SourceLocation RParenLoc,
2073 Expr *ControllingExpr,
2074 ArrayRef<TypeSourceInfo *> Types,
2075 ArrayRef<Expr *> Exprs) {
2076 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2077 ControllingExpr, Types, Exprs);
2080 /// \brief Build a new overloaded operator call expression.
2082 /// By default, performs semantic analysis to build the new expression.
2083 /// The semantic analysis provides the behavior of template instantiation,
2084 /// copying with transformations that turn what looks like an overloaded
2085 /// operator call into a use of a builtin operator, performing
2086 /// argument-dependent lookup, etc. Subclasses may override this routine to
2087 /// provide different behavior.
2088 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2089 SourceLocation OpLoc,
2094 /// \brief Build a new C++ "named" cast expression, such as static_cast or
2095 /// reinterpret_cast.
2097 /// By default, this routine dispatches to one of the more-specific routines
2098 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2099 /// Subclasses may override this routine to provide different behavior.
2100 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2101 Stmt::StmtClass Class,
2102 SourceLocation LAngleLoc,
2103 TypeSourceInfo *TInfo,
2104 SourceLocation RAngleLoc,
2105 SourceLocation LParenLoc,
2107 SourceLocation RParenLoc) {
2109 case Stmt::CXXStaticCastExprClass:
2110 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2111 RAngleLoc, LParenLoc,
2112 SubExpr, RParenLoc);
2114 case Stmt::CXXDynamicCastExprClass:
2115 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2116 RAngleLoc, LParenLoc,
2117 SubExpr, RParenLoc);
2119 case Stmt::CXXReinterpretCastExprClass:
2120 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2121 RAngleLoc, LParenLoc,
2125 case Stmt::CXXConstCastExprClass:
2126 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2127 RAngleLoc, LParenLoc,
2128 SubExpr, RParenLoc);
2131 llvm_unreachable("Invalid C++ named cast");
2135 /// \brief Build a new C++ static_cast expression.
2137 /// By default, performs semantic analysis to build the new expression.
2138 /// Subclasses may override this routine to provide different behavior.
2139 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2140 SourceLocation LAngleLoc,
2141 TypeSourceInfo *TInfo,
2142 SourceLocation RAngleLoc,
2143 SourceLocation LParenLoc,
2145 SourceLocation RParenLoc) {
2146 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2148 SourceRange(LAngleLoc, RAngleLoc),
2149 SourceRange(LParenLoc, RParenLoc));
2152 /// \brief Build a new C++ dynamic_cast expression.
2154 /// By default, performs semantic analysis to build the new expression.
2155 /// Subclasses may override this routine to provide different behavior.
2156 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2157 SourceLocation LAngleLoc,
2158 TypeSourceInfo *TInfo,
2159 SourceLocation RAngleLoc,
2160 SourceLocation LParenLoc,
2162 SourceLocation RParenLoc) {
2163 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2165 SourceRange(LAngleLoc, RAngleLoc),
2166 SourceRange(LParenLoc, RParenLoc));
2169 /// \brief Build a new C++ reinterpret_cast expression.
2171 /// By default, performs semantic analysis to build the new expression.
2172 /// Subclasses may override this routine to provide different behavior.
2173 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2174 SourceLocation LAngleLoc,
2175 TypeSourceInfo *TInfo,
2176 SourceLocation RAngleLoc,
2177 SourceLocation LParenLoc,
2179 SourceLocation RParenLoc) {
2180 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2182 SourceRange(LAngleLoc, RAngleLoc),
2183 SourceRange(LParenLoc, RParenLoc));
2186 /// \brief Build a new C++ const_cast expression.
2188 /// By default, performs semantic analysis to build the new expression.
2189 /// Subclasses may override this routine to provide different behavior.
2190 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2191 SourceLocation LAngleLoc,
2192 TypeSourceInfo *TInfo,
2193 SourceLocation RAngleLoc,
2194 SourceLocation LParenLoc,
2196 SourceLocation RParenLoc) {
2197 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2199 SourceRange(LAngleLoc, RAngleLoc),
2200 SourceRange(LParenLoc, RParenLoc));
2203 /// \brief Build a new C++ functional-style cast expression.
2205 /// By default, performs semantic analysis to build the new expression.
2206 /// Subclasses may override this routine to provide different behavior.
2207 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2208 SourceLocation LParenLoc,
2210 SourceLocation RParenLoc) {
2211 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2212 MultiExprArg(&Sub, 1),
2216 /// \brief Build a new C++ typeid(type) expression.
2218 /// By default, performs semantic analysis to build the new expression.
2219 /// Subclasses may override this routine to provide different behavior.
2220 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2221 SourceLocation TypeidLoc,
2222 TypeSourceInfo *Operand,
2223 SourceLocation RParenLoc) {
2224 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2229 /// \brief Build a new C++ typeid(expr) expression.
2231 /// By default, performs semantic analysis to build the new expression.
2232 /// Subclasses may override this routine to provide different behavior.
2233 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2234 SourceLocation TypeidLoc,
2236 SourceLocation RParenLoc) {
2237 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2241 /// \brief Build a new C++ __uuidof(type) expression.
2243 /// By default, performs semantic analysis to build the new expression.
2244 /// Subclasses may override this routine to provide different behavior.
2245 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2246 SourceLocation TypeidLoc,
2247 TypeSourceInfo *Operand,
2248 SourceLocation RParenLoc) {
2249 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2253 /// \brief Build a new C++ __uuidof(expr) expression.
2255 /// By default, performs semantic analysis to build the new expression.
2256 /// Subclasses may override this routine to provide different behavior.
2257 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2258 SourceLocation TypeidLoc,
2260 SourceLocation RParenLoc) {
2261 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2265 /// \brief Build a new C++ "this" expression.
2267 /// By default, builds a new "this" expression without performing any
2268 /// semantic analysis. Subclasses may override this routine to provide
2269 /// different behavior.
2270 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2273 getSema().CheckCXXThisCapture(ThisLoc);
2274 return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
2277 /// \brief Build a new C++ throw expression.
2279 /// By default, performs semantic analysis to build the new expression.
2280 /// Subclasses may override this routine to provide different behavior.
2281 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2282 bool IsThrownVariableInScope) {
2283 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2286 /// \brief Build a new C++ default-argument expression.
2288 /// By default, builds a new default-argument expression, which does not
2289 /// require any semantic analysis. Subclasses may override this routine to
2290 /// provide different behavior.
2291 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
2292 ParmVarDecl *Param) {
2293 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
2296 /// \brief Build a new C++11 default-initialization expression.
2298 /// By default, builds a new default field initialization expression, which
2299 /// does not require any semantic analysis. Subclasses may override this
2300 /// routine to provide different behavior.
2301 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2303 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
2306 /// \brief Build a new C++ zero-initialization expression.
2308 /// By default, performs semantic analysis to build the new expression.
2309 /// Subclasses may override this routine to provide different behavior.
2310 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2311 SourceLocation LParenLoc,
2312 SourceLocation RParenLoc) {
2313 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
2317 /// \brief Build a new C++ "new" expression.
2319 /// By default, performs semantic analysis to build the new expression.
2320 /// Subclasses may override this routine to provide different behavior.
2321 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2323 SourceLocation PlacementLParen,
2324 MultiExprArg PlacementArgs,
2325 SourceLocation PlacementRParen,
2326 SourceRange TypeIdParens,
2327 QualType AllocatedType,
2328 TypeSourceInfo *AllocatedTypeInfo,
2330 SourceRange DirectInitRange,
2331 Expr *Initializer) {
2332 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2344 /// \brief Build a new C++ "delete" expression.
2346 /// By default, performs semantic analysis to build the new expression.
2347 /// Subclasses may override this routine to provide different behavior.
2348 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2349 bool IsGlobalDelete,
2352 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2356 /// \brief Build a new type trait expression.
2358 /// By default, performs semantic analysis to build the new expression.
2359 /// Subclasses may override this routine to provide different behavior.
2360 ExprResult RebuildTypeTrait(TypeTrait Trait,
2361 SourceLocation StartLoc,
2362 ArrayRef<TypeSourceInfo *> Args,
2363 SourceLocation RParenLoc) {
2364 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2367 /// \brief Build a new array type trait expression.
2369 /// By default, performs semantic analysis to build the new expression.
2370 /// Subclasses may override this routine to provide different behavior.
2371 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2372 SourceLocation StartLoc,
2373 TypeSourceInfo *TSInfo,
2375 SourceLocation RParenLoc) {
2376 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2379 /// \brief Build a new expression trait expression.
2381 /// By default, performs semantic analysis to build the new expression.
2382 /// Subclasses may override this routine to provide different behavior.
2383 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2384 SourceLocation StartLoc,
2386 SourceLocation RParenLoc) {
2387 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2390 /// \brief Build a new (previously unresolved) declaration reference
2393 /// By default, performs semantic analysis to build the new expression.
2394 /// Subclasses may override this routine to provide different behavior.
2395 ExprResult RebuildDependentScopeDeclRefExpr(
2396 NestedNameSpecifierLoc QualifierLoc,
2397 SourceLocation TemplateKWLoc,
2398 const DeclarationNameInfo &NameInfo,
2399 const TemplateArgumentListInfo *TemplateArgs,
2400 bool IsAddressOfOperand,
2401 TypeSourceInfo **RecoveryTSI) {
2403 SS.Adopt(QualifierLoc);
2405 if (TemplateArgs || TemplateKWLoc.isValid())
2406 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2409 return getSema().BuildQualifiedDeclarationNameExpr(
2410 SS, NameInfo, IsAddressOfOperand, RecoveryTSI);
2413 /// \brief Build a new template-id expression.
2415 /// By default, performs semantic analysis to build the new expression.
2416 /// Subclasses may override this routine to provide different behavior.
2417 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2418 SourceLocation TemplateKWLoc,
2421 const TemplateArgumentListInfo *TemplateArgs) {
2422 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2426 /// \brief Build a new object-construction expression.
2428 /// By default, performs semantic analysis to build the new expression.
2429 /// Subclasses may override this routine to provide different behavior.
2430 ExprResult RebuildCXXConstructExpr(QualType T,
2432 CXXConstructorDecl *Constructor,
2435 bool HadMultipleCandidates,
2436 bool ListInitialization,
2437 bool StdInitListInitialization,
2438 bool RequiresZeroInit,
2439 CXXConstructExpr::ConstructionKind ConstructKind,
2440 SourceRange ParenRange) {
2441 SmallVector<Expr*, 8> ConvertedArgs;
2442 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2446 return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
2448 HadMultipleCandidates,
2450 StdInitListInitialization,
2451 RequiresZeroInit, ConstructKind,
2455 /// \brief Build a new object-construction expression.
2457 /// By default, performs semantic analysis to build the new expression.
2458 /// Subclasses may override this routine to provide different behavior.
2459 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2460 SourceLocation LParenLoc,
2462 SourceLocation RParenLoc) {
2463 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2469 /// \brief Build a new object-construction expression.
2471 /// By default, performs semantic analysis to build the new expression.
2472 /// Subclasses may override this routine to provide different behavior.
2473 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2474 SourceLocation LParenLoc,
2476 SourceLocation RParenLoc) {
2477 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2483 /// \brief Build a new member reference expression.
2485 /// By default, performs semantic analysis to build the new expression.
2486 /// Subclasses may override this routine to provide different behavior.
2487 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2490 SourceLocation OperatorLoc,
2491 NestedNameSpecifierLoc QualifierLoc,
2492 SourceLocation TemplateKWLoc,
2493 NamedDecl *FirstQualifierInScope,
2494 const DeclarationNameInfo &MemberNameInfo,
2495 const TemplateArgumentListInfo *TemplateArgs) {
2497 SS.Adopt(QualifierLoc);
2499 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2500 OperatorLoc, IsArrow,
2502 FirstQualifierInScope,
2507 /// \brief Build a new member reference expression.
2509 /// By default, performs semantic analysis to build the new expression.
2510 /// Subclasses may override this routine to provide different behavior.
2511 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2512 SourceLocation OperatorLoc,
2514 NestedNameSpecifierLoc QualifierLoc,
2515 SourceLocation TemplateKWLoc,
2516 NamedDecl *FirstQualifierInScope,
2518 const TemplateArgumentListInfo *TemplateArgs) {
2520 SS.Adopt(QualifierLoc);
2522 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2523 OperatorLoc, IsArrow,
2525 FirstQualifierInScope,
2529 /// \brief Build a new noexcept expression.
2531 /// By default, performs semantic analysis to build the new expression.
2532 /// Subclasses may override this routine to provide different behavior.
2533 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2534 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2537 /// \brief Build a new expression to compute the length of a parameter pack.
2538 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
2539 SourceLocation PackLoc,
2540 SourceLocation RParenLoc,
2541 Optional<unsigned> Length) {
2543 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2544 OperatorLoc, Pack, PackLoc,
2545 RParenLoc, *Length);
2547 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2548 OperatorLoc, Pack, PackLoc,
2552 /// \brief Build a new Objective-C boxed expression.
2554 /// By default, performs semantic analysis to build the new expression.
2555 /// Subclasses may override this routine to provide different behavior.
2556 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
2557 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
2560 /// \brief Build a new Objective-C array literal.
2562 /// By default, performs semantic analysis to build the new expression.
2563 /// Subclasses may override this routine to provide different behavior.
2564 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
2565 Expr **Elements, unsigned NumElements) {
2566 return getSema().BuildObjCArrayLiteral(Range,
2567 MultiExprArg(Elements, NumElements));
2570 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
2571 Expr *Base, Expr *Key,
2572 ObjCMethodDecl *getterMethod,
2573 ObjCMethodDecl *setterMethod) {
2574 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
2575 getterMethod, setterMethod);
2578 /// \brief Build a new Objective-C dictionary literal.
2580 /// By default, performs semantic analysis to build the new expression.
2581 /// Subclasses may override this routine to provide different behavior.
2582 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
2583 ObjCDictionaryElement *Elements,
2584 unsigned NumElements) {
2585 return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElements);
2588 /// \brief Build a new Objective-C \@encode expression.
2590 /// By default, performs semantic analysis to build the new expression.
2591 /// Subclasses may override this routine to provide different behavior.
2592 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2593 TypeSourceInfo *EncodeTypeInfo,
2594 SourceLocation RParenLoc) {
2595 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
2598 /// \brief Build a new Objective-C class message.
2599 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2601 ArrayRef<SourceLocation> SelectorLocs,
2602 ObjCMethodDecl *Method,
2603 SourceLocation LBracLoc,
2605 SourceLocation RBracLoc) {
2606 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
2607 ReceiverTypeInfo->getType(),
2608 /*SuperLoc=*/SourceLocation(),
2609 Sel, Method, LBracLoc, SelectorLocs,
2613 /// \brief Build a new Objective-C instance message.
2614 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
2616 ArrayRef<SourceLocation> SelectorLocs,
2617 ObjCMethodDecl *Method,
2618 SourceLocation LBracLoc,
2620 SourceLocation RBracLoc) {
2621 return SemaRef.BuildInstanceMessage(Receiver,
2622 Receiver->getType(),
2623 /*SuperLoc=*/SourceLocation(),
2624 Sel, Method, LBracLoc, SelectorLocs,
2628 /// \brief Build a new Objective-C ivar reference expression.
2630 /// By default, performs semantic analysis to build the new expression.
2631 /// Subclasses may override this routine to provide different behavior.
2632 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
2633 SourceLocation IvarLoc,
2634 bool IsArrow, bool IsFreeIvar) {
2635 // FIXME: We lose track of the IsFreeIvar bit.
2637 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
2638 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2639 /*FIXME:*/IvarLoc, IsArrow,
2640 SS, SourceLocation(),
2641 /*FirstQualifierInScope=*/nullptr,
2643 /*TemplateArgs=*/nullptr);
2646 /// \brief Build a new Objective-C property reference expression.
2648 /// By default, performs semantic analysis to build the new expression.
2649 /// Subclasses may override this routine to provide different behavior.
2650 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
2651 ObjCPropertyDecl *Property,
2652 SourceLocation PropertyLoc) {
2654 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
2655 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2656 /*FIXME:*/PropertyLoc,
2658 SS, SourceLocation(),
2659 /*FirstQualifierInScope=*/nullptr,
2661 /*TemplateArgs=*/nullptr);
2664 /// \brief Build a new Objective-C property reference expression.
2666 /// By default, performs semantic analysis to build the new expression.
2667 /// Subclasses may override this routine to provide different behavior.
2668 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
2669 ObjCMethodDecl *Getter,
2670 ObjCMethodDecl *Setter,
2671 SourceLocation PropertyLoc) {
2672 // Since these expressions can only be value-dependent, we do not
2673 // need to perform semantic analysis again.
2675 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
2676 VK_LValue, OK_ObjCProperty,
2677 PropertyLoc, Base));
2680 /// \brief Build a new Objective-C "isa" expression.
2682 /// By default, performs semantic analysis to build the new expression.
2683 /// Subclasses may override this routine to provide different behavior.
2684 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
2685 SourceLocation OpLoc, bool IsArrow) {
2687 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
2688 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2690 SS, SourceLocation(),
2691 /*FirstQualifierInScope=*/nullptr,
2693 /*TemplateArgs=*/nullptr);
2696 /// \brief Build a new shuffle vector expression.
2698 /// By default, performs semantic analysis to build the new expression.
2699 /// Subclasses may override this routine to provide different behavior.
2700 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
2701 MultiExprArg SubExprs,
2702 SourceLocation RParenLoc) {
2703 // Find the declaration for __builtin_shufflevector
2704 const IdentifierInfo &Name
2705 = SemaRef.Context.Idents.get("__builtin_shufflevector");
2706 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
2707 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
2708 assert(!Lookup.empty() && "No __builtin_shufflevector?");
2710 // Build a reference to the __builtin_shufflevector builtin
2711 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
2712 Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
2713 SemaRef.Context.BuiltinFnTy,
2714 VK_RValue, BuiltinLoc);
2715 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
2716 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
2717 CK_BuiltinFnToFnPtr).get();
2719 // Build the CallExpr
2720 ExprResult TheCall = new (SemaRef.Context) CallExpr(
2721 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
2722 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
2724 // Type-check the __builtin_shufflevector expression.
2725 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
2728 /// \brief Build a new convert vector expression.
2729 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
2730 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
2731 SourceLocation RParenLoc) {
2732 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
2733 BuiltinLoc, RParenLoc);
2736 /// \brief Build a new template argument pack expansion.
2738 /// By default, performs semantic analysis to build a new pack expansion
2739 /// for a template argument. Subclasses may override this routine to provide
2740 /// different behavior.
2741 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
2742 SourceLocation EllipsisLoc,
2743 Optional<unsigned> NumExpansions) {
2744 switch (Pattern.getArgument().getKind()) {
2745 case TemplateArgument::Expression: {
2747 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
2748 EllipsisLoc, NumExpansions);
2749 if (Result.isInvalid())
2750 return TemplateArgumentLoc();
2752 return TemplateArgumentLoc(Result.get(), Result.get());
2755 case TemplateArgument::Template:
2756 return TemplateArgumentLoc(TemplateArgument(
2757 Pattern.getArgument().getAsTemplate(),
2759 Pattern.getTemplateQualifierLoc(),
2760 Pattern.getTemplateNameLoc(),
2763 case TemplateArgument::Null:
2764 case TemplateArgument::Integral:
2765 case TemplateArgument::Declaration:
2766 case TemplateArgument::Pack:
2767 case TemplateArgument::TemplateExpansion:
2768 case TemplateArgument::NullPtr:
2769 llvm_unreachable("Pack expansion pattern has no parameter packs");
2771 case TemplateArgument::Type:
2772 if (TypeSourceInfo *Expansion
2773 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
2776 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
2781 return TemplateArgumentLoc();
2784 /// \brief Build a new expression pack expansion.
2786 /// By default, performs semantic analysis to build a new pack expansion
2787 /// for an expression. Subclasses may override this routine to provide
2788 /// different behavior.
2789 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
2790 Optional<unsigned> NumExpansions) {
2791 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
2794 /// \brief Build a new C++1z fold-expression.
2796 /// By default, performs semantic analysis in order to build a new fold
2798 ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
2799 BinaryOperatorKind Operator,
2800 SourceLocation EllipsisLoc, Expr *RHS,
2801 SourceLocation RParenLoc) {
2802 return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
2806 /// \brief Build an empty C++1z fold-expression with the given operator.
2808 /// By default, produces the fallback value for the fold-expression, or
2809 /// produce an error if there is no fallback value.
2810 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
2811 BinaryOperatorKind Operator) {
2812 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
2815 /// \brief Build a new atomic operation expression.
2817 /// By default, performs semantic analysis to build the new expression.
2818 /// Subclasses may override this routine to provide different behavior.
2819 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
2820 MultiExprArg SubExprs,
2822 AtomicExpr::AtomicOp Op,
2823 SourceLocation RParenLoc) {
2824 // Just create the expression; there is not any interesting semantic
2825 // analysis here because we can't actually build an AtomicExpr until
2826 // we are sure it is semantically sound.
2827 return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
2832 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
2833 QualType ObjectType,
2834 NamedDecl *FirstQualifierInScope,
2837 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
2838 QualType ObjectType,
2839 NamedDecl *FirstQualifierInScope,
2842 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
2843 NamedDecl *FirstQualifierInScope,
2847 template<typename Derived>
2848 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
2852 switch (S->getStmtClass()) {
2853 case Stmt::NoStmtClass: break;
2855 // Transform individual statement nodes
2856 #define STMT(Node, Parent) \
2857 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
2858 #define ABSTRACT_STMT(Node)
2859 #define EXPR(Node, Parent)
2860 #include "clang/AST/StmtNodes.inc"
2862 // Transform expressions by calling TransformExpr.
2863 #define STMT(Node, Parent)
2864 #define ABSTRACT_STMT(Stmt)
2865 #define EXPR(Node, Parent) case Stmt::Node##Class:
2866 #include "clang/AST/StmtNodes.inc"
2868 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
2872 return getSema().ActOnExprStmt(E);
2879 template<typename Derived>
2880 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
2884 switch (S->getClauseKind()) {
2886 // Transform individual clause nodes
2887 #define OPENMP_CLAUSE(Name, Class) \
2888 case OMPC_ ## Name : \
2889 return getDerived().Transform ## Class(cast<Class>(S));
2890 #include "clang/Basic/OpenMPKinds.def"
2897 template<typename Derived>
2898 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
2902 switch (E->getStmtClass()) {
2903 case Stmt::NoStmtClass: break;
2904 #define STMT(Node, Parent) case Stmt::Node##Class: break;
2905 #define ABSTRACT_STMT(Stmt)
2906 #define EXPR(Node, Parent) \
2907 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
2908 #include "clang/AST/StmtNodes.inc"
2914 template<typename Derived>
2915 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
2917 // Initializers are instantiated like expressions, except that various outer
2918 // layers are stripped.
2922 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
2923 Init = ExprTemp->getSubExpr();
2925 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
2926 Init = MTE->GetTemporaryExpr();
2928 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
2929 Init = Binder->getSubExpr();
2931 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
2932 Init = ICE->getSubExprAsWritten();
2934 if (CXXStdInitializerListExpr *ILE =
2935 dyn_cast<CXXStdInitializerListExpr>(Init))
2936 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
2938 // If this is copy-initialization, we only need to reconstruct
2939 // InitListExprs. Other forms of copy-initialization will be a no-op if
2940 // the initializer is already the right type.
2941 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
2942 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
2943 return getDerived().TransformExpr(Init);
2945 // Revert value-initialization back to empty parens.
2946 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
2947 SourceRange Parens = VIE->getSourceRange();
2948 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
2952 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
2953 if (isa<ImplicitValueInitExpr>(Init))
2954 return getDerived().RebuildParenListExpr(SourceLocation(), None,
2957 // Revert initialization by constructor back to a parenthesized or braced list
2958 // of expressions. Any other form of initializer can just be reused directly.
2959 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
2960 return getDerived().TransformExpr(Init);
2962 // If the initialization implicitly converted an initializer list to a
2963 // std::initializer_list object, unwrap the std::initializer_list too.
2964 if (Construct && Construct->isStdInitListInitialization())
2965 return TransformInitializer(Construct->getArg(0), NotCopyInit);
2967 SmallVector<Expr*, 8> NewArgs;
2968 bool ArgChanged = false;
2969 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
2970 /*IsCall*/true, NewArgs, &ArgChanged))
2973 // If this was list initialization, revert to list form.
2974 if (Construct->isListInitialization())
2975 return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
2976 Construct->getLocEnd(),
2977 Construct->getType());
2979 // Build a ParenListExpr to represent anything else.
2980 SourceRange Parens = Construct->getParenOrBraceRange();
2981 if (Parens.isInvalid()) {
2982 // This was a variable declaration's initialization for which no initializer
2984 assert(NewArgs.empty() &&
2985 "no parens or braces but have direct init with arguments?");
2988 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
2992 template<typename Derived>
2993 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
2996 SmallVectorImpl<Expr *> &Outputs,
2998 for (unsigned I = 0; I != NumInputs; ++I) {
2999 // If requested, drop call arguments that need to be dropped.
3000 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3007 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3008 Expr *Pattern = Expansion->getPattern();
3010 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3011 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3012 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3014 // Determine whether the set of unexpanded parameter packs can and should
3017 bool RetainExpansion = false;
3018 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3019 Optional<unsigned> NumExpansions = OrigNumExpansions;
3020 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3021 Pattern->getSourceRange(),
3023 Expand, RetainExpansion,
3028 // The transform has determined that we should perform a simple
3029 // transformation on the pack expansion, producing another pack
3031 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3032 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3033 if (OutPattern.isInvalid())
3036 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3037 Expansion->getEllipsisLoc(),
3039 if (Out.isInvalid())
3044 Outputs.push_back(Out.get());
3048 // Record right away that the argument was changed. This needs
3049 // to happen even if the array expands to nothing.
3050 if (ArgChanged) *ArgChanged = true;
3052 // The transform has determined that we should perform an elementwise
3053 // expansion of the pattern. Do so.
3054 for (unsigned I = 0; I != *NumExpansions; ++I) {
3055 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3056 ExprResult Out = getDerived().TransformExpr(Pattern);
3057 if (Out.isInvalid())
3060 // FIXME: Can this happen? We should not try to expand the pack
3062 if (Out.get()->containsUnexpandedParameterPack()) {
3063 Out = getDerived().RebuildPackExpansion(
3064 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3065 if (Out.isInvalid())
3069 Outputs.push_back(Out.get());
3072 // If we're supposed to retain a pack expansion, do so by temporarily
3073 // forgetting the partially-substituted parameter pack.
3074 if (RetainExpansion) {
3075 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3077 ExprResult Out = getDerived().TransformExpr(Pattern);
3078 if (Out.isInvalid())
3081 Out = getDerived().RebuildPackExpansion(
3082 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3083 if (Out.isInvalid())
3086 Outputs.push_back(Out.get());
3093 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3094 : getDerived().TransformExpr(Inputs[I]);
3095 if (Result.isInvalid())
3098 if (Result.get() != Inputs[I] && ArgChanged)
3101 Outputs.push_back(Result.get());
3107 template<typename Derived>
3108 NestedNameSpecifierLoc
3109 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3110 NestedNameSpecifierLoc NNS,
3111 QualType ObjectType,
3112 NamedDecl *FirstQualifierInScope) {
3113 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3114 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3115 Qualifier = Qualifier.getPrefix())
3116 Qualifiers.push_back(Qualifier);
3119 while (!Qualifiers.empty()) {
3120 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3121 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3123 switch (QNNS->getKind()) {
3124 case NestedNameSpecifier::Identifier:
3125 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr,
3126 *QNNS->getAsIdentifier(),
3127 Q.getLocalBeginLoc(),
3129 ObjectType, false, SS,
3130 FirstQualifierInScope, false))
3131 return NestedNameSpecifierLoc();
3135 case NestedNameSpecifier::Namespace: {
3137 = cast_or_null<NamespaceDecl>(
3138 getDerived().TransformDecl(
3139 Q.getLocalBeginLoc(),
3140 QNNS->getAsNamespace()));
3141 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3145 case NestedNameSpecifier::NamespaceAlias: {
3146 NamespaceAliasDecl *Alias
3147 = cast_or_null<NamespaceAliasDecl>(
3148 getDerived().TransformDecl(Q.getLocalBeginLoc(),
3149 QNNS->getAsNamespaceAlias()));
3150 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3151 Q.getLocalEndLoc());
3155 case NestedNameSpecifier::Global:
3156 // There is no meaningful transformation that one could perform on the
3158 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3161 case NestedNameSpecifier::Super: {
3163 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3164 SourceLocation(), QNNS->getAsRecordDecl()));
3165 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3169 case NestedNameSpecifier::TypeSpecWithTemplate:
3170 case NestedNameSpecifier::TypeSpec: {
3171 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3172 FirstQualifierInScope, SS);
3175 return NestedNameSpecifierLoc();
3177 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3178 (SemaRef.getLangOpts().CPlusPlus11 &&
3179 TL.getType()->isEnumeralType())) {
3180 assert(!TL.getType().hasLocalQualifiers() &&
3181 "Can't get cv-qualifiers here");
3182 if (TL.getType()->isEnumeralType())
3183 SemaRef.Diag(TL.getBeginLoc(),
3184 diag::warn_cxx98_compat_enum_nested_name_spec);
3185 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3186 Q.getLocalEndLoc());
3189 // If the nested-name-specifier is an invalid type def, don't emit an
3190 // error because a previous error should have already been emitted.
3191 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3192 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3193 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3194 << TL.getType() << SS.getRange();
3196 return NestedNameSpecifierLoc();
3200 // The qualifier-in-scope and object type only apply to the leftmost entity.
3201 FirstQualifierInScope = nullptr;
3202 ObjectType = QualType();
3205 // Don't rebuild the nested-name-specifier if we don't have to.
3206 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3207 !getDerived().AlwaysRebuild())
3210 // If we can re-use the source-location data from the original
3211 // nested-name-specifier, do so.
3212 if (SS.location_size() == NNS.getDataLength() &&
3213 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3214 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3216 // Allocate new nested-name-specifier location information.
3217 return SS.getWithLocInContext(SemaRef.Context);
3220 template<typename Derived>
3222 TreeTransform<Derived>
3223 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3224 DeclarationName Name = NameInfo.getName();
3226 return DeclarationNameInfo();
3228 switch (Name.getNameKind()) {
3229 case DeclarationName::Identifier:
3230 case DeclarationName::ObjCZeroArgSelector:
3231 case DeclarationName::ObjCOneArgSelector:
3232 case DeclarationName::ObjCMultiArgSelector:
3233 case DeclarationName::CXXOperatorName:
3234 case DeclarationName::CXXLiteralOperatorName:
3235 case DeclarationName::CXXUsingDirective:
3238 case DeclarationName::CXXConstructorName:
3239 case DeclarationName::CXXDestructorName:
3240 case DeclarationName::CXXConversionFunctionName: {
3241 TypeSourceInfo *NewTInfo;
3242 CanQualType NewCanTy;
3243 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3244 NewTInfo = getDerived().TransformType(OldTInfo);
3246 return DeclarationNameInfo();
3247 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3251 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3252 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3254 return DeclarationNameInfo();
3255 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3258 DeclarationName NewName
3259 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3261 DeclarationNameInfo NewNameInfo(NameInfo);
3262 NewNameInfo.setName(NewName);
3263 NewNameInfo.setNamedTypeInfo(NewTInfo);
3268 llvm_unreachable("Unknown name kind.");
3271 template<typename Derived>
3273 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3275 SourceLocation NameLoc,
3276 QualType ObjectType,
3277 NamedDecl *FirstQualifierInScope) {
3278 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3279 TemplateDecl *Template = QTN->getTemplateDecl();
3280 assert(Template && "qualified template name must refer to a template");
3282 TemplateDecl *TransTemplate
3283 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3286 return TemplateName();
3288 if (!getDerived().AlwaysRebuild() &&
3289 SS.getScopeRep() == QTN->getQualifier() &&
3290 TransTemplate == Template)
3293 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3297 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3298 if (SS.getScopeRep()) {
3299 // These apply to the scope specifier, not the template.
3300 ObjectType = QualType();
3301 FirstQualifierInScope = nullptr;
3304 if (!getDerived().AlwaysRebuild() &&
3305 SS.getScopeRep() == DTN->getQualifier() &&
3306 ObjectType.isNull())
3309 if (DTN->isIdentifier()) {
3310 return getDerived().RebuildTemplateName(SS,
3311 *DTN->getIdentifier(),
3314 FirstQualifierInScope);
3317 return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
3321 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3322 TemplateDecl *TransTemplate
3323 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3326 return TemplateName();
3328 if (!getDerived().AlwaysRebuild() &&
3329 TransTemplate == Template)
3332 return TemplateName(TransTemplate);
3335 if (SubstTemplateTemplateParmPackStorage *SubstPack
3336 = Name.getAsSubstTemplateTemplateParmPack()) {
3337 TemplateTemplateParmDecl *TransParam
3338 = cast_or_null<TemplateTemplateParmDecl>(
3339 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3341 return TemplateName();
3343 if (!getDerived().AlwaysRebuild() &&
3344 TransParam == SubstPack->getParameterPack())
3347 return getDerived().RebuildTemplateName(TransParam,
3348 SubstPack->getArgumentPack());
3351 // These should be getting filtered out before they reach the AST.
3352 llvm_unreachable("overloaded function decl survived to here");
3355 template<typename Derived>
3356 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3357 const TemplateArgument &Arg,
3358 TemplateArgumentLoc &Output) {
3359 SourceLocation Loc = getDerived().getBaseLocation();
3360 switch (Arg.getKind()) {
3361 case TemplateArgument::Null:
3362 llvm_unreachable("null template argument in TreeTransform");
3365 case TemplateArgument::Type:
3366 Output = TemplateArgumentLoc(Arg,
3367 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3371 case TemplateArgument::Template:
3372 case TemplateArgument::TemplateExpansion: {
3373 NestedNameSpecifierLocBuilder Builder;
3374 TemplateName Template = Arg.getAsTemplate();
3375 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3376 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3377 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3378 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3380 if (Arg.getKind() == TemplateArgument::Template)
3381 Output = TemplateArgumentLoc(Arg,
3382 Builder.getWithLocInContext(SemaRef.Context),
3385 Output = TemplateArgumentLoc(Arg,
3386 Builder.getWithLocInContext(SemaRef.Context),
3392 case TemplateArgument::Expression:
3393 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3396 case TemplateArgument::Declaration:
3397 case TemplateArgument::Integral:
3398 case TemplateArgument::Pack:
3399 case TemplateArgument::NullPtr:
3400 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3405 template<typename Derived>
3406 bool TreeTransform<Derived>::TransformTemplateArgument(
3407 const TemplateArgumentLoc &Input,
3408 TemplateArgumentLoc &Output) {
3409 const TemplateArgument &Arg = Input.getArgument();
3410 switch (Arg.getKind()) {
3411 case TemplateArgument::Null:
3412 case TemplateArgument::Integral:
3413 case TemplateArgument::Pack:
3414 case TemplateArgument::Declaration:
3415 case TemplateArgument::NullPtr:
3416 llvm_unreachable("Unexpected TemplateArgument");
3418 case TemplateArgument::Type: {
3419 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3421 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3423 DI = getDerived().TransformType(DI);
3424 if (!DI) return true;
3426 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3430 case TemplateArgument::Template: {
3431 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3433 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3439 SS.Adopt(QualifierLoc);
3440 TemplateName Template
3441 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3442 Input.getTemplateNameLoc());
3443 if (Template.isNull())
3446 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3447 Input.getTemplateNameLoc());
3451 case TemplateArgument::TemplateExpansion:
3452 llvm_unreachable("Caller should expand pack expansions");
3454 case TemplateArgument::Expression: {
3455 // Template argument expressions are constant expressions.
3456 EnterExpressionEvaluationContext Unevaluated(getSema(),
3457 Sema::ConstantEvaluated);
3459 Expr *InputExpr = Input.getSourceExpression();
3460 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
3462 ExprResult E = getDerived().TransformExpr(InputExpr);
3463 E = SemaRef.ActOnConstantExpression(E);
3464 if (E.isInvalid()) return true;
3465 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
3470 // Work around bogus GCC warning
3474 /// \brief Iterator adaptor that invents template argument location information
3475 /// for each of the template arguments in its underlying iterator.
3476 template<typename Derived, typename InputIterator>
3477 class TemplateArgumentLocInventIterator {
3478 TreeTransform<Derived> &Self;
3482 typedef TemplateArgumentLoc value_type;
3483 typedef TemplateArgumentLoc reference;
3484 typedef typename std::iterator_traits<InputIterator>::difference_type
3486 typedef std::input_iterator_tag iterator_category;
3489 TemplateArgumentLoc Arg;
3492 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
3494 const TemplateArgumentLoc *operator->() const { return &Arg; }
3497 TemplateArgumentLocInventIterator() { }
3499 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
3501 : Self(Self), Iter(Iter) { }
3503 TemplateArgumentLocInventIterator &operator++() {
3508 TemplateArgumentLocInventIterator operator++(int) {
3509 TemplateArgumentLocInventIterator Old(*this);
3514 reference operator*() const {
3515 TemplateArgumentLoc Result;
3516 Self.InventTemplateArgumentLoc(*Iter, Result);
3520 pointer operator->() const { return pointer(**this); }
3522 friend bool operator==(const TemplateArgumentLocInventIterator &X,
3523 const TemplateArgumentLocInventIterator &Y) {
3524 return X.Iter == Y.Iter;
3527 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
3528 const TemplateArgumentLocInventIterator &Y) {
3529 return X.Iter != Y.Iter;
3533 template<typename Derived>
3534 template<typename InputIterator>
3535 bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
3537 TemplateArgumentListInfo &Outputs) {
3538 for (; First != Last; ++First) {
3539 TemplateArgumentLoc Out;
3540 TemplateArgumentLoc In = *First;
3542 if (In.getArgument().getKind() == TemplateArgument::Pack) {
3543 // Unpack argument packs, which we translate them into separate
3545 // FIXME: We could do much better if we could guarantee that the
3546 // TemplateArgumentLocInfo for the pack expansion would be usable for
3547 // all of the template arguments in the argument pack.
3548 typedef TemplateArgumentLocInventIterator<Derived,
3549 TemplateArgument::pack_iterator>
3551 if (TransformTemplateArguments(PackLocIterator(*this,
3552 In.getArgument().pack_begin()),
3553 PackLocIterator(*this,
3554 In.getArgument().pack_end()),
3561 if (In.getArgument().isPackExpansion()) {
3562 // We have a pack expansion, for which we will be substituting into
3564 SourceLocation Ellipsis;
3565 Optional<unsigned> OrigNumExpansions;
3566 TemplateArgumentLoc Pattern
3567 = getSema().getTemplateArgumentPackExpansionPattern(
3568 In, Ellipsis, OrigNumExpansions);
3570 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3571 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3572 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3574 // Determine whether the set of unexpanded parameter packs can and should
3577 bool RetainExpansion = false;
3578 Optional<unsigned> NumExpansions = OrigNumExpansions;
3579 if (getDerived().TryExpandParameterPacks(Ellipsis,
3580 Pattern.getSourceRange(),
3588 // The transform has determined that we should perform a simple
3589 // transformation on the pack expansion, producing another pack
3591 TemplateArgumentLoc OutPattern;
3592 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3593 if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
3596 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
3598 if (Out.getArgument().isNull())
3601 Outputs.addArgument(Out);
3605 // The transform has determined that we should perform an elementwise
3606 // expansion of the pattern. Do so.
3607 for (unsigned I = 0; I != *NumExpansions; ++I) {
3608 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3610 if (getDerived().TransformTemplateArgument(Pattern, Out))
3613 if (Out.getArgument().containsUnexpandedParameterPack()) {
3614 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3616 if (Out.getArgument().isNull())
3620 Outputs.addArgument(Out);
3623 // If we're supposed to retain a pack expansion, do so by temporarily
3624 // forgetting the partially-substituted parameter pack.
3625 if (RetainExpansion) {
3626 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3628 if (getDerived().TransformTemplateArgument(Pattern, Out))
3631 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3633 if (Out.getArgument().isNull())
3636 Outputs.addArgument(Out);
3643 if (getDerived().TransformTemplateArgument(In, Out))
3646 Outputs.addArgument(Out);
3653 //===----------------------------------------------------------------------===//
3654 // Type transformation
3655 //===----------------------------------------------------------------------===//
3657 template<typename Derived>
3658 QualType TreeTransform<Derived>::TransformType(QualType T) {
3659 if (getDerived().AlreadyTransformed(T))
3662 // Temporary workaround. All of these transformations should
3663 // eventually turn into transformations on TypeLocs.
3664 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
3665 getDerived().getBaseLocation());
3667 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
3672 return NewDI->getType();
3675 template<typename Derived>
3676 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
3677 // Refine the base location to the type's location.
3678 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
3679 getDerived().getBaseEntity());
3680 if (getDerived().AlreadyTransformed(DI->getType()))
3685 TypeLoc TL = DI->getTypeLoc();
3686 TLB.reserve(TL.getFullDataSize());
3688 QualType Result = getDerived().TransformType(TLB, TL);
3689 if (Result.isNull())
3692 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3695 template<typename Derived>
3697 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
3698 switch (T.getTypeLocClass()) {
3699 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3700 #define TYPELOC(CLASS, PARENT) \
3701 case TypeLoc::CLASS: \
3702 return getDerived().Transform##CLASS##Type(TLB, \
3703 T.castAs<CLASS##TypeLoc>());
3704 #include "clang/AST/TypeLocNodes.def"
3707 llvm_unreachable("unhandled type loc!");
3710 /// FIXME: By default, this routine adds type qualifiers only to types
3711 /// that can have qualifiers, and silently suppresses those qualifiers
3712 /// that are not permitted (e.g., qualifiers on reference or function
3713 /// types). This is the right thing for template instantiation, but
3714 /// probably not for other clients.
3715 template<typename Derived>
3717 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
3718 QualifiedTypeLoc T) {
3719 Qualifiers Quals = T.getType().getLocalQualifiers();
3721 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
3722 if (Result.isNull())
3725 // Silently suppress qualifiers if the result type can't be qualified.
3726 // FIXME: this is the right thing for template instantiation, but
3727 // probably not for other clients.
3728 if (Result->isFunctionType() || Result->isReferenceType())
3731 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
3733 if (Quals.hasObjCLifetime()) {
3734 if (!Result->isObjCLifetimeType() && !Result->isDependentType())
3735 Quals.removeObjCLifetime();
3736 else if (Result.getObjCLifetime()) {
3738 // A lifetime qualifier applied to a substituted template parameter
3739 // overrides the lifetime qualifier from the template argument.
3740 const AutoType *AutoTy;
3741 if (const SubstTemplateTypeParmType *SubstTypeParam
3742 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
3743 QualType Replacement = SubstTypeParam->getReplacementType();
3744 Qualifiers Qs = Replacement.getQualifiers();
3745 Qs.removeObjCLifetime();
3747 = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
3749 Result = SemaRef.Context.getSubstTemplateTypeParmType(
3750 SubstTypeParam->getReplacedParameter(),
3752 TLB.TypeWasModifiedSafely(Result);
3753 } else if ((AutoTy = dyn_cast<AutoType>(Result)) && AutoTy->isDeduced()) {
3754 // 'auto' types behave the same way as template parameters.
3755 QualType Deduced = AutoTy->getDeducedType();
3756 Qualifiers Qs = Deduced.getQualifiers();
3757 Qs.removeObjCLifetime();
3758 Deduced = SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(),
3760 Result = SemaRef.Context.getAutoType(Deduced, AutoTy->isDecltypeAuto(),
3761 AutoTy->isDependentType());
3762 TLB.TypeWasModifiedSafely(Result);
3764 // Otherwise, complain about the addition of a qualifier to an
3765 // already-qualified type.
3766 SourceRange R = T.getUnqualifiedLoc().getSourceRange();
3767 SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
3770 Quals.removeObjCLifetime();
3774 if (!Quals.empty()) {
3775 Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
3776 // BuildQualifiedType might not add qualifiers if they are invalid.
3777 if (Result.hasLocalQualifiers())
3778 TLB.push<QualifiedTypeLoc>(Result);
3779 // No location information to preserve.
3785 template<typename Derived>
3787 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
3788 QualType ObjectType,
3789 NamedDecl *UnqualLookup,
3791 if (getDerived().AlreadyTransformed(TL.getType()))
3794 TypeSourceInfo *TSI =
3795 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
3797 return TSI->getTypeLoc();
3801 template<typename Derived>
3803 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3804 QualType ObjectType,
3805 NamedDecl *UnqualLookup,
3807 if (getDerived().AlreadyTransformed(TSInfo->getType()))
3810 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
3814 template <typename Derived>
3815 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
3816 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
3818 QualType T = TL.getType();
3819 assert(!getDerived().AlreadyTransformed(T));
3824 if (isa<TemplateSpecializationType>(T)) {
3825 TemplateSpecializationTypeLoc SpecTL =
3826 TL.castAs<TemplateSpecializationTypeLoc>();
3828 TemplateName Template
3829 = getDerived().TransformTemplateName(SS,
3830 SpecTL.getTypePtr()->getTemplateName(),
3831 SpecTL.getTemplateNameLoc(),
3832 ObjectType, UnqualLookup);
3833 if (Template.isNull())
3836 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
3838 } else if (isa<DependentTemplateSpecializationType>(T)) {
3839 DependentTemplateSpecializationTypeLoc SpecTL =
3840 TL.castAs<DependentTemplateSpecializationTypeLoc>();
3842 TemplateName Template
3843 = getDerived().RebuildTemplateName(SS,
3844 *SpecTL.getTypePtr()->getIdentifier(),
3845 SpecTL.getTemplateNameLoc(),
3846 ObjectType, UnqualLookup);
3847 if (Template.isNull())
3850 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
3855 // Nothing special needs to be done for these.
3856 Result = getDerived().TransformType(TLB, TL);
3859 if (Result.isNull())
3862 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3865 template <class TyLoc> static inline
3866 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
3867 TyLoc NewT = TLB.push<TyLoc>(T.getType());
3868 NewT.setNameLoc(T.getNameLoc());
3872 template<typename Derived>
3873 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
3875 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
3876 NewT.setBuiltinLoc(T.getBuiltinLoc());
3877 if (T.needsExtraLocalData())
3878 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
3882 template<typename Derived>
3883 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
3886 return TransformTypeSpecType(TLB, T);
3889 template <typename Derived>
3890 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
3891 AdjustedTypeLoc TL) {
3892 // Adjustments applied during transformation are handled elsewhere.
3893 return getDerived().TransformType(TLB, TL.getOriginalLoc());
3896 template<typename Derived>
3897 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
3898 DecayedTypeLoc TL) {
3899 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
3900 if (OriginalType.isNull())
3903 QualType Result = TL.getType();
3904 if (getDerived().AlwaysRebuild() ||
3905 OriginalType != TL.getOriginalLoc().getType())
3906 Result = SemaRef.Context.getDecayedType(OriginalType);
3907 TLB.push<DecayedTypeLoc>(Result);
3908 // Nothing to set for DecayedTypeLoc.
3912 template<typename Derived>
3913 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
3914 PointerTypeLoc TL) {
3915 QualType PointeeType
3916 = getDerived().TransformType(TLB, TL.getPointeeLoc());
3917 if (PointeeType.isNull())
3920 QualType Result = TL.getType();
3921 if (PointeeType->getAs<ObjCObjectType>()) {
3922 // A dependent pointer type 'T *' has is being transformed such
3923 // that an Objective-C class type is being replaced for 'T'. The
3924 // resulting pointer type is an ObjCObjectPointerType, not a
3926 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
3928 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
3929 NewT.setStarLoc(TL.getStarLoc());
3933 if (getDerived().AlwaysRebuild() ||
3934 PointeeType != TL.getPointeeLoc().getType()) {
3935 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
3936 if (Result.isNull())
3940 // Objective-C ARC can add lifetime qualifiers to the type that we're
3942 TLB.TypeWasModifiedSafely(Result->getPointeeType());
3944 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
3945 NewT.setSigilLoc(TL.getSigilLoc());
3949 template<typename Derived>
3951 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
3952 BlockPointerTypeLoc TL) {
3953 QualType PointeeType
3954 = getDerived().TransformType(TLB, TL.getPointeeLoc());
3955 if (PointeeType.isNull())
3958 QualType Result = TL.getType();
3959 if (getDerived().AlwaysRebuild() ||
3960 PointeeType != TL.getPointeeLoc().getType()) {
3961 Result = getDerived().RebuildBlockPointerType(PointeeType,
3963 if (Result.isNull())
3967 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
3968 NewT.setSigilLoc(TL.getSigilLoc());
3972 /// Transforms a reference type. Note that somewhat paradoxically we
3973 /// don't care whether the type itself is an l-value type or an r-value
3974 /// type; we only care if the type was *written* as an l-value type
3975 /// or an r-value type.
3976 template<typename Derived>
3978 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
3979 ReferenceTypeLoc TL) {
3980 const ReferenceType *T = TL.getTypePtr();
3982 // Note that this works with the pointee-as-written.
3983 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
3984 if (PointeeType.isNull())
3987 QualType Result = TL.getType();
3988 if (getDerived().AlwaysRebuild() ||
3989 PointeeType != T->getPointeeTypeAsWritten()) {
3990 Result = getDerived().RebuildReferenceType(PointeeType,
3991 T->isSpelledAsLValue(),
3993 if (Result.isNull())
3997 // Objective-C ARC can add lifetime qualifiers to the type that we're
3999 TLB.TypeWasModifiedSafely(
4000 Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4002 // r-value references can be rebuilt as l-value references.
4003 ReferenceTypeLoc NewTL;
4004 if (isa<LValueReferenceType>(Result))
4005 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4007 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4008 NewTL.setSigilLoc(TL.getSigilLoc());
4013 template<typename Derived>
4015 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4016 LValueReferenceTypeLoc TL) {
4017 return TransformReferenceType(TLB, TL);
4020 template<typename Derived>
4022 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4023 RValueReferenceTypeLoc TL) {
4024 return TransformReferenceType(TLB, TL);
4027 template<typename Derived>
4029 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4030 MemberPointerTypeLoc TL) {
4031 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4032 if (PointeeType.isNull())
4035 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4036 TypeSourceInfo *NewClsTInfo = nullptr;
4038 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4043 const MemberPointerType *T = TL.getTypePtr();
4044 QualType OldClsType = QualType(T->getClass(), 0);
4045 QualType NewClsType;
4047 NewClsType = NewClsTInfo->getType();
4049 NewClsType = getDerived().TransformType(OldClsType);
4050 if (NewClsType.isNull())
4054 QualType Result = TL.getType();
4055 if (getDerived().AlwaysRebuild() ||
4056 PointeeType != T->getPointeeType() ||
4057 NewClsType != OldClsType) {
4058 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4060 if (Result.isNull())
4064 // If we had to adjust the pointee type when building a member pointer, make
4065 // sure to push TypeLoc info for it.
4066 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4067 if (MPT && PointeeType != MPT->getPointeeType()) {
4068 assert(isa<AdjustedType>(MPT->getPointeeType()));
4069 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4072 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4073 NewTL.setSigilLoc(TL.getSigilLoc());
4074 NewTL.setClassTInfo(NewClsTInfo);
4079 template<typename Derived>
4081 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4082 ConstantArrayTypeLoc TL) {
4083 const ConstantArrayType *T = TL.getTypePtr();
4084 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4085 if (ElementType.isNull())
4088 QualType Result = TL.getType();
4089 if (getDerived().AlwaysRebuild() ||
4090 ElementType != T->getElementType()) {
4091 Result = getDerived().RebuildConstantArrayType(ElementType,
4092 T->getSizeModifier(),
4094 T->getIndexTypeCVRQualifiers(),
4095 TL.getBracketsRange());
4096 if (Result.isNull())
4100 // We might have either a ConstantArrayType or a VariableArrayType now:
4101 // a ConstantArrayType is allowed to have an element type which is a
4102 // VariableArrayType if the type is dependent. Fortunately, all array
4103 // types have the same location layout.
4104 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4105 NewTL.setLBracketLoc(TL.getLBracketLoc());
4106 NewTL.setRBracketLoc(TL.getRBracketLoc());
4108 Expr *Size = TL.getSizeExpr();
4110 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4111 Sema::ConstantEvaluated);
4112 Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4113 Size = SemaRef.ActOnConstantExpression(Size).get();
4115 NewTL.setSizeExpr(Size);
4120 template<typename Derived>
4121 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4122 TypeLocBuilder &TLB,
4123 IncompleteArrayTypeLoc TL) {
4124 const IncompleteArrayType *T = TL.getTypePtr();
4125 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4126 if (ElementType.isNull())
4129 QualType Result = TL.getType();
4130 if (getDerived().AlwaysRebuild() ||
4131 ElementType != T->getElementType()) {
4132 Result = getDerived().RebuildIncompleteArrayType(ElementType,
4133 T->getSizeModifier(),
4134 T->getIndexTypeCVRQualifiers(),
4135 TL.getBracketsRange());
4136 if (Result.isNull())
4140 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4141 NewTL.setLBracketLoc(TL.getLBracketLoc());
4142 NewTL.setRBracketLoc(TL.getRBracketLoc());
4143 NewTL.setSizeExpr(nullptr);
4148 template<typename Derived>
4150 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4151 VariableArrayTypeLoc TL) {
4152 const VariableArrayType *T = TL.getTypePtr();
4153 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4154 if (ElementType.isNull())
4157 ExprResult SizeResult
4158 = getDerived().TransformExpr(T->getSizeExpr());
4159 if (SizeResult.isInvalid())
4162 Expr *Size = SizeResult.get();
4164 QualType Result = TL.getType();
4165 if (getDerived().AlwaysRebuild() ||
4166 ElementType != T->getElementType() ||
4167 Size != T->getSizeExpr()) {
4168 Result = getDerived().RebuildVariableArrayType(ElementType,
4169 T->getSizeModifier(),
4171 T->getIndexTypeCVRQualifiers(),
4172 TL.getBracketsRange());
4173 if (Result.isNull())
4177 // We might have constant size array now, but fortunately it has the same
4179 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4180 NewTL.setLBracketLoc(TL.getLBracketLoc());
4181 NewTL.setRBracketLoc(TL.getRBracketLoc());
4182 NewTL.setSizeExpr(Size);
4187 template<typename Derived>
4189 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4190 DependentSizedArrayTypeLoc TL) {
4191 const DependentSizedArrayType *T = TL.getTypePtr();
4192 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4193 if (ElementType.isNull())
4196 // Array bounds are constant expressions.
4197 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4198 Sema::ConstantEvaluated);
4200 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4201 Expr *origSize = TL.getSizeExpr();
4202 if (!origSize) origSize = T->getSizeExpr();
4204 ExprResult sizeResult
4205 = getDerived().TransformExpr(origSize);
4206 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4207 if (sizeResult.isInvalid())
4210 Expr *size = sizeResult.get();
4212 QualType Result = TL.getType();
4213 if (getDerived().AlwaysRebuild() ||
4214 ElementType != T->getElementType() ||
4216 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4217 T->getSizeModifier(),
4219 T->getIndexTypeCVRQualifiers(),
4220 TL.getBracketsRange());
4221 if (Result.isNull())
4225 // We might have any sort of array type now, but fortunately they
4226 // all have the same location layout.
4227 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4228 NewTL.setLBracketLoc(TL.getLBracketLoc());
4229 NewTL.setRBracketLoc(TL.getRBracketLoc());
4230 NewTL.setSizeExpr(size);
4235 template<typename Derived>
4236 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4237 TypeLocBuilder &TLB,
4238 DependentSizedExtVectorTypeLoc TL) {
4239 const DependentSizedExtVectorType *T = TL.getTypePtr();
4241 // FIXME: ext vector locs should be nested
4242 QualType ElementType = getDerived().TransformType(T->getElementType());
4243 if (ElementType.isNull())
4246 // Vector sizes are constant expressions.
4247 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4248 Sema::ConstantEvaluated);
4250 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4251 Size = SemaRef.ActOnConstantExpression(Size);
4252 if (Size.isInvalid())
4255 QualType Result = TL.getType();
4256 if (getDerived().AlwaysRebuild() ||
4257 ElementType != T->getElementType() ||
4258 Size.get() != T->getSizeExpr()) {
4259 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4261 T->getAttributeLoc());
4262 if (Result.isNull())
4266 // Result might be dependent or not.
4267 if (isa<DependentSizedExtVectorType>(Result)) {
4268 DependentSizedExtVectorTypeLoc NewTL
4269 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4270 NewTL.setNameLoc(TL.getNameLoc());
4272 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4273 NewTL.setNameLoc(TL.getNameLoc());
4279 template<typename Derived>
4280 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
4282 const VectorType *T = TL.getTypePtr();
4283 QualType ElementType = getDerived().TransformType(T->getElementType());
4284 if (ElementType.isNull())
4287 QualType Result = TL.getType();
4288 if (getDerived().AlwaysRebuild() ||
4289 ElementType != T->getElementType()) {
4290 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
4291 T->getVectorKind());
4292 if (Result.isNull())
4296 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4297 NewTL.setNameLoc(TL.getNameLoc());
4302 template<typename Derived>
4303 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
4304 ExtVectorTypeLoc TL) {
4305 const VectorType *T = TL.getTypePtr();
4306 QualType ElementType = getDerived().TransformType(T->getElementType());
4307 if (ElementType.isNull())
4310 QualType Result = TL.getType();
4311 if (getDerived().AlwaysRebuild() ||
4312 ElementType != T->getElementType()) {
4313 Result = getDerived().RebuildExtVectorType(ElementType,
4314 T->getNumElements(),
4315 /*FIXME*/ SourceLocation());
4316 if (Result.isNull())
4320 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4321 NewTL.setNameLoc(TL.getNameLoc());
4326 template <typename Derived>
4327 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
4328 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
4329 bool ExpectParameterPack) {
4330 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
4331 TypeSourceInfo *NewDI = nullptr;
4333 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
4334 // If we're substituting into a pack expansion type and we know the
4335 // length we want to expand to, just substitute for the pattern.
4336 TypeLoc OldTL = OldDI->getTypeLoc();
4337 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
4340 TypeLoc NewTL = OldDI->getTypeLoc();
4341 TLB.reserve(NewTL.getFullDataSize());
4343 QualType Result = getDerived().TransformType(TLB,
4344 OldExpansionTL.getPatternLoc());
4345 if (Result.isNull())
4348 Result = RebuildPackExpansionType(Result,
4349 OldExpansionTL.getPatternLoc().getSourceRange(),
4350 OldExpansionTL.getEllipsisLoc(),
4352 if (Result.isNull())
4355 PackExpansionTypeLoc NewExpansionTL
4356 = TLB.push<PackExpansionTypeLoc>(Result);
4357 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
4358 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
4360 NewDI = getDerived().TransformType(OldDI);
4364 if (NewDI == OldDI && indexAdjustment == 0)
4367 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
4368 OldParm->getDeclContext(),
4369 OldParm->getInnerLocStart(),
4370 OldParm->getLocation(),
4371 OldParm->getIdentifier(),
4374 OldParm->getStorageClass(),
4375 /* DefArg */ nullptr);
4376 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
4377 OldParm->getFunctionScopeIndex() + indexAdjustment);
4381 template<typename Derived>
4382 bool TreeTransform<Derived>::
4383 TransformFunctionTypeParams(SourceLocation Loc,
4384 ParmVarDecl **Params, unsigned NumParams,
4385 const QualType *ParamTypes,
4386 SmallVectorImpl<QualType> &OutParamTypes,
4387 SmallVectorImpl<ParmVarDecl*> *PVars) {
4388 int indexAdjustment = 0;
4390 for (unsigned i = 0; i != NumParams; ++i) {
4391 if (ParmVarDecl *OldParm = Params[i]) {
4392 assert(OldParm->getFunctionScopeIndex() == i);
4394 Optional<unsigned> NumExpansions;
4395 ParmVarDecl *NewParm = nullptr;
4396 if (OldParm->isParameterPack()) {
4397 // We have a function parameter pack that may need to be expanded.
4398 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4400 // Find the parameter packs that could be expanded.
4401 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
4402 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
4403 TypeLoc Pattern = ExpansionTL.getPatternLoc();
4404 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
4405 assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
4407 // Determine whether we should expand the parameter packs.
4408 bool ShouldExpand = false;
4409 bool RetainExpansion = false;
4410 Optional<unsigned> OrigNumExpansions =
4411 ExpansionTL.getTypePtr()->getNumExpansions();
4412 NumExpansions = OrigNumExpansions;
4413 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
4414 Pattern.getSourceRange(),
4423 // Expand the function parameter pack into multiple, separate
4425 getDerived().ExpandingFunctionParameterPack(OldParm);
4426 for (unsigned I = 0; I != *NumExpansions; ++I) {
4427 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4428 ParmVarDecl *NewParm
4429 = getDerived().TransformFunctionTypeParam(OldParm,
4432 /*ExpectParameterPack=*/false);
4436 OutParamTypes.push_back(NewParm->getType());
4438 PVars->push_back(NewParm);
4441 // If we're supposed to retain a pack expansion, do so by temporarily
4442 // forgetting the partially-substituted parameter pack.
4443 if (RetainExpansion) {
4444 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4445 ParmVarDecl *NewParm
4446 = getDerived().TransformFunctionTypeParam(OldParm,
4449 /*ExpectParameterPack=*/false);
4453 OutParamTypes.push_back(NewParm->getType());
4455 PVars->push_back(NewParm);
4458 // The next parameter should have the same adjustment as the
4459 // last thing we pushed, but we post-incremented indexAdjustment
4460 // on every push. Also, if we push nothing, the adjustment should
4464 // We're done with the pack expansion.
4468 // We'll substitute the parameter now without expanding the pack
4470 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4471 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
4474 /*ExpectParameterPack=*/true);
4476 NewParm = getDerived().TransformFunctionTypeParam(
4477 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
4483 OutParamTypes.push_back(NewParm->getType());
4485 PVars->push_back(NewParm);
4489 // Deal with the possibility that we don't have a parameter
4490 // declaration for this parameter.
4491 QualType OldType = ParamTypes[i];
4492 bool IsPackExpansion = false;
4493 Optional<unsigned> NumExpansions;
4495 if (const PackExpansionType *Expansion
4496 = dyn_cast<PackExpansionType>(OldType)) {
4497 // We have a function parameter pack that may need to be expanded.
4498 QualType Pattern = Expansion->getPattern();
4499 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4500 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4502 // Determine whether we should expand the parameter packs.
4503 bool ShouldExpand = false;
4504 bool RetainExpansion = false;
4505 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
4514 // Expand the function parameter pack into multiple, separate
4516 for (unsigned I = 0; I != *NumExpansions; ++I) {
4517 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4518 QualType NewType = getDerived().TransformType(Pattern);
4519 if (NewType.isNull())
4522 OutParamTypes.push_back(NewType);
4524 PVars->push_back(nullptr);
4527 // We're done with the pack expansion.
4531 // If we're supposed to retain a pack expansion, do so by temporarily
4532 // forgetting the partially-substituted parameter pack.
4533 if (RetainExpansion) {
4534 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4535 QualType NewType = getDerived().TransformType(Pattern);
4536 if (NewType.isNull())
4539 OutParamTypes.push_back(NewType);
4541 PVars->push_back(nullptr);
4544 // We'll substitute the parameter now without expanding the pack
4546 OldType = Expansion->getPattern();
4547 IsPackExpansion = true;
4548 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4549 NewType = getDerived().TransformType(OldType);
4551 NewType = getDerived().TransformType(OldType);
4554 if (NewType.isNull())
4557 if (IsPackExpansion)
4558 NewType = getSema().Context.getPackExpansionType(NewType,
4561 OutParamTypes.push_back(NewType);
4563 PVars->push_back(nullptr);
4568 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
4569 if (ParmVarDecl *parm = (*PVars)[i])
4570 assert(parm->getFunctionScopeIndex() == i);
4577 template<typename Derived>
4579 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
4580 FunctionProtoTypeLoc TL) {
4581 SmallVector<QualType, 4> ExceptionStorage;
4582 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
4583 return getDerived().TransformFunctionProtoType(
4584 TLB, TL, nullptr, 0,
4585 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
4586 return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
4587 ExceptionStorage, Changed);
4591 template<typename Derived> template<typename Fn>
4592 QualType TreeTransform<Derived>::TransformFunctionProtoType(
4593 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
4594 unsigned ThisTypeQuals, Fn TransformExceptionSpec) {
4595 // Transform the parameters and return type.
4597 // We are required to instantiate the params and return type in source order.
4598 // When the function has a trailing return type, we instantiate the
4599 // parameters before the return type, since the return type can then refer
4600 // to the parameters themselves (via decltype, sizeof, etc.).
4602 SmallVector<QualType, 4> ParamTypes;
4603 SmallVector<ParmVarDecl*, 4> ParamDecls;
4604 const FunctionProtoType *T = TL.getTypePtr();
4606 QualType ResultType;
4608 if (T->hasTrailingReturn()) {
4609 if (getDerived().TransformFunctionTypeParams(
4610 TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
4611 TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
4615 // C++11 [expr.prim.general]p3:
4616 // If a declaration declares a member function or member function
4617 // template of a class X, the expression this is a prvalue of type
4618 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4619 // and the end of the function-definition, member-declarator, or
4621 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
4623 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4624 if (ResultType.isNull())
4629 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4630 if (ResultType.isNull())
4633 if (getDerived().TransformFunctionTypeParams(
4634 TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
4635 TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
4639 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
4641 bool EPIChanged = false;
4642 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
4645 // FIXME: Need to transform ConsumedParameters for variadic template
4648 QualType Result = TL.getType();
4649 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
4650 T->getNumParams() != ParamTypes.size() ||
4651 !std::equal(T->param_type_begin(), T->param_type_end(),
4652 ParamTypes.begin()) || EPIChanged) {
4653 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
4654 if (Result.isNull())
4658 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
4659 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4660 NewTL.setLParenLoc(TL.getLParenLoc());
4661 NewTL.setRParenLoc(TL.getRParenLoc());
4662 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4663 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
4664 NewTL.setParam(i, ParamDecls[i]);
4669 template<typename Derived>
4670 bool TreeTransform<Derived>::TransformExceptionSpec(
4671 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
4672 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
4673 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
4675 // Instantiate a dynamic noexcept expression, if any.
4676 if (ESI.Type == EST_ComputedNoexcept) {
4677 EnterExpressionEvaluationContext Unevaluated(getSema(),
4678 Sema::ConstantEvaluated);
4679 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
4680 if (NoexceptExpr.isInvalid())
4683 NoexceptExpr = getSema().CheckBooleanCondition(
4684 NoexceptExpr.get(), NoexceptExpr.get()->getLocStart());
4685 if (NoexceptExpr.isInvalid())
4688 if (!NoexceptExpr.get()->isValueDependent()) {
4689 NoexceptExpr = getSema().VerifyIntegerConstantExpression(
4690 NoexceptExpr.get(), nullptr,
4691 diag::err_noexcept_needs_constant_expression,
4692 /*AllowFold*/false);
4693 if (NoexceptExpr.isInvalid())
4697 if (ESI.NoexceptExpr != NoexceptExpr.get())
4699 ESI.NoexceptExpr = NoexceptExpr.get();
4702 if (ESI.Type != EST_Dynamic)
4705 // Instantiate a dynamic exception specification's type.
4706 for (QualType T : ESI.Exceptions) {
4707 if (const PackExpansionType *PackExpansion =
4708 T->getAs<PackExpansionType>()) {
4711 // We have a pack expansion. Instantiate it.
4712 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4713 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
4715 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4717 // Determine whether the set of unexpanded parameter packs can and
4720 bool Expand = false;
4721 bool RetainExpansion = false;
4722 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
4723 // FIXME: Track the location of the ellipsis (and track source location
4724 // information for the types in the exception specification in general).
4725 if (getDerived().TryExpandParameterPacks(
4726 Loc, SourceRange(), Unexpanded, Expand,
4727 RetainExpansion, NumExpansions))
4731 // We can't expand this pack expansion into separate arguments yet;
4732 // just substitute into the pattern and create a new pack expansion
4734 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4735 QualType U = getDerived().TransformType(PackExpansion->getPattern());
4739 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
4740 Exceptions.push_back(U);
4744 // Substitute into the pack expansion pattern for each slice of the
4746 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
4747 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
4749 QualType U = getDerived().TransformType(PackExpansion->getPattern());
4750 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
4753 Exceptions.push_back(U);
4756 QualType U = getDerived().TransformType(T);
4757 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
4762 Exceptions.push_back(U);
4766 ESI.Exceptions = Exceptions;
4770 template<typename Derived>
4771 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
4772 TypeLocBuilder &TLB,
4773 FunctionNoProtoTypeLoc TL) {
4774 const FunctionNoProtoType *T = TL.getTypePtr();
4775 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4776 if (ResultType.isNull())
4779 QualType Result = TL.getType();
4780 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
4781 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
4783 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
4784 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4785 NewTL.setLParenLoc(TL.getLParenLoc());
4786 NewTL.setRParenLoc(TL.getRParenLoc());
4787 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4792 template<typename Derived> QualType
4793 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
4794 UnresolvedUsingTypeLoc TL) {
4795 const UnresolvedUsingType *T = TL.getTypePtr();
4796 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
4800 QualType Result = TL.getType();
4801 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
4802 Result = getDerived().RebuildUnresolvedUsingType(D);
4803 if (Result.isNull())
4807 // We might get an arbitrary type spec type back. We should at
4808 // least always get a type spec type, though.
4809 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
4810 NewTL.setNameLoc(TL.getNameLoc());
4815 template<typename Derived>
4816 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
4817 TypedefTypeLoc TL) {
4818 const TypedefType *T = TL.getTypePtr();
4819 TypedefNameDecl *Typedef
4820 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4825 QualType Result = TL.getType();
4826 if (getDerived().AlwaysRebuild() ||
4827 Typedef != T->getDecl()) {
4828 Result = getDerived().RebuildTypedefType(Typedef);
4829 if (Result.isNull())
4833 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
4834 NewTL.setNameLoc(TL.getNameLoc());
4839 template<typename Derived>
4840 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
4841 TypeOfExprTypeLoc TL) {
4842 // typeof expressions are not potentially evaluated contexts
4843 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4844 Sema::ReuseLambdaContextDecl);
4846 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
4850 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
4854 QualType Result = TL.getType();
4855 if (getDerived().AlwaysRebuild() ||
4856 E.get() != TL.getUnderlyingExpr()) {
4857 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
4858 if (Result.isNull())
4863 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
4864 NewTL.setTypeofLoc(TL.getTypeofLoc());
4865 NewTL.setLParenLoc(TL.getLParenLoc());
4866 NewTL.setRParenLoc(TL.getRParenLoc());
4871 template<typename Derived>
4872 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
4874 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
4875 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
4879 QualType Result = TL.getType();
4880 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
4881 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
4882 if (Result.isNull())
4886 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
4887 NewTL.setTypeofLoc(TL.getTypeofLoc());
4888 NewTL.setLParenLoc(TL.getLParenLoc());
4889 NewTL.setRParenLoc(TL.getRParenLoc());
4890 NewTL.setUnderlyingTInfo(New_Under_TI);
4895 template<typename Derived>
4896 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
4897 DecltypeTypeLoc TL) {
4898 const DecltypeType *T = TL.getTypePtr();
4900 // decltype expressions are not potentially evaluated contexts
4901 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4902 nullptr, /*IsDecltype=*/ true);
4904 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
4908 E = getSema().ActOnDecltypeExpression(E.get());
4912 QualType Result = TL.getType();
4913 if (getDerived().AlwaysRebuild() ||
4914 E.get() != T->getUnderlyingExpr()) {
4915 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
4916 if (Result.isNull())
4921 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
4922 NewTL.setNameLoc(TL.getNameLoc());
4927 template<typename Derived>
4928 QualType TreeTransform<Derived>::TransformUnaryTransformType(
4929 TypeLocBuilder &TLB,
4930 UnaryTransformTypeLoc TL) {
4931 QualType Result = TL.getType();
4932 if (Result->isDependentType()) {
4933 const UnaryTransformType *T = TL.getTypePtr();
4935 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
4936 Result = getDerived().RebuildUnaryTransformType(NewBase,
4939 if (Result.isNull())
4943 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
4944 NewTL.setKWLoc(TL.getKWLoc());
4945 NewTL.setParensRange(TL.getParensRange());
4946 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
4950 template<typename Derived>
4951 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
4953 const AutoType *T = TL.getTypePtr();
4954 QualType OldDeduced = T->getDeducedType();
4955 QualType NewDeduced;
4956 if (!OldDeduced.isNull()) {
4957 NewDeduced = getDerived().TransformType(OldDeduced);
4958 if (NewDeduced.isNull())
4962 QualType Result = TL.getType();
4963 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
4964 T->isDependentType()) {
4965 Result = getDerived().RebuildAutoType(NewDeduced, T->isDecltypeAuto());
4966 if (Result.isNull())
4970 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4971 NewTL.setNameLoc(TL.getNameLoc());
4976 template<typename Derived>
4977 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
4979 const RecordType *T = TL.getTypePtr();
4981 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4986 QualType Result = TL.getType();
4987 if (getDerived().AlwaysRebuild() ||
4988 Record != T->getDecl()) {
4989 Result = getDerived().RebuildRecordType(Record);
4990 if (Result.isNull())
4994 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
4995 NewTL.setNameLoc(TL.getNameLoc());
5000 template<typename Derived>
5001 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5003 const EnumType *T = TL.getTypePtr();
5005 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5010 QualType Result = TL.getType();
5011 if (getDerived().AlwaysRebuild() ||
5012 Enum != T->getDecl()) {
5013 Result = getDerived().RebuildEnumType(Enum);
5014 if (Result.isNull())
5018 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5019 NewTL.setNameLoc(TL.getNameLoc());
5024 template<typename Derived>
5025 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5026 TypeLocBuilder &TLB,
5027 InjectedClassNameTypeLoc TL) {
5028 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5029 TL.getTypePtr()->getDecl());
5030 if (!D) return QualType();
5032 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5033 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5037 template<typename Derived>
5038 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5039 TypeLocBuilder &TLB,
5040 TemplateTypeParmTypeLoc TL) {
5041 return TransformTypeSpecType(TLB, TL);
5044 template<typename Derived>
5045 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5046 TypeLocBuilder &TLB,
5047 SubstTemplateTypeParmTypeLoc TL) {
5048 const SubstTemplateTypeParmType *T = TL.getTypePtr();
5050 // Substitute into the replacement type, which itself might involve something
5051 // that needs to be transformed. This only tends to occur with default
5052 // template arguments of template template parameters.
5053 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5054 QualType Replacement = getDerived().TransformType(T->getReplacementType());
5055 if (Replacement.isNull())
5058 // Always canonicalize the replacement type.
5059 Replacement = SemaRef.Context.getCanonicalType(Replacement);
5061 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5064 // Propagate type-source information.
5065 SubstTemplateTypeParmTypeLoc NewTL
5066 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5067 NewTL.setNameLoc(TL.getNameLoc());
5072 template<typename Derived>
5073 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5074 TypeLocBuilder &TLB,
5075 SubstTemplateTypeParmPackTypeLoc TL) {
5076 return TransformTypeSpecType(TLB, TL);
5079 template<typename Derived>
5080 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5081 TypeLocBuilder &TLB,
5082 TemplateSpecializationTypeLoc TL) {
5083 const TemplateSpecializationType *T = TL.getTypePtr();
5085 // The nested-name-specifier never matters in a TemplateSpecializationType,
5086 // because we can't have a dependent nested-name-specifier anyway.
5088 TemplateName Template
5089 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5090 TL.getTemplateNameLoc());
5091 if (Template.isNull())
5094 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5097 template<typename Derived>
5098 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5100 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5101 if (ValueType.isNull())
5104 QualType Result = TL.getType();
5105 if (getDerived().AlwaysRebuild() ||
5106 ValueType != TL.getValueLoc().getType()) {
5107 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5108 if (Result.isNull())
5112 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5113 NewTL.setKWLoc(TL.getKWLoc());
5114 NewTL.setLParenLoc(TL.getLParenLoc());
5115 NewTL.setRParenLoc(TL.getRParenLoc());
5120 /// \brief Simple iterator that traverses the template arguments in a
5121 /// container that provides a \c getArgLoc() member function.
5123 /// This iterator is intended to be used with the iterator form of
5124 /// \c TreeTransform<Derived>::TransformTemplateArguments().
5125 template<typename ArgLocContainer>
5126 class TemplateArgumentLocContainerIterator {
5127 ArgLocContainer *Container;
5131 typedef TemplateArgumentLoc value_type;
5132 typedef TemplateArgumentLoc reference;
5133 typedef int difference_type;
5134 typedef std::input_iterator_tag iterator_category;
5137 TemplateArgumentLoc Arg;
5140 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5142 const TemplateArgumentLoc *operator->() const {
5148 TemplateArgumentLocContainerIterator() {}
5150 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5152 : Container(&Container), Index(Index) { }
5154 TemplateArgumentLocContainerIterator &operator++() {
5159 TemplateArgumentLocContainerIterator operator++(int) {
5160 TemplateArgumentLocContainerIterator Old(*this);
5165 TemplateArgumentLoc operator*() const {
5166 return Container->getArgLoc(Index);
5169 pointer operator->() const {
5170 return pointer(Container->getArgLoc(Index));
5173 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5174 const TemplateArgumentLocContainerIterator &Y) {
5175 return X.Container == Y.Container && X.Index == Y.Index;
5178 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
5179 const TemplateArgumentLocContainerIterator &Y) {
5185 template <typename Derived>
5186 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5187 TypeLocBuilder &TLB,
5188 TemplateSpecializationTypeLoc TL,
5189 TemplateName Template) {
5190 TemplateArgumentListInfo NewTemplateArgs;
5191 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5192 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5193 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
5195 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5196 ArgIterator(TL, TL.getNumArgs()),
5200 // FIXME: maybe don't rebuild if all the template arguments are the same.
5203 getDerived().RebuildTemplateSpecializationType(Template,
5204 TL.getTemplateNameLoc(),
5207 if (!Result.isNull()) {
5208 // Specializations of template template parameters are represented as
5209 // TemplateSpecializationTypes, and substitution of type alias templates
5210 // within a dependent context can transform them into
5211 // DependentTemplateSpecializationTypes.
5212 if (isa<DependentTemplateSpecializationType>(Result)) {
5213 DependentTemplateSpecializationTypeLoc NewTL
5214 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5215 NewTL.setElaboratedKeywordLoc(SourceLocation());
5216 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
5217 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5218 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5219 NewTL.setLAngleLoc(TL.getLAngleLoc());
5220 NewTL.setRAngleLoc(TL.getRAngleLoc());
5221 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5222 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5226 TemplateSpecializationTypeLoc NewTL
5227 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5228 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5229 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5230 NewTL.setLAngleLoc(TL.getLAngleLoc());
5231 NewTL.setRAngleLoc(TL.getRAngleLoc());
5232 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5233 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5239 template <typename Derived>
5240 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
5241 TypeLocBuilder &TLB,
5242 DependentTemplateSpecializationTypeLoc TL,
5243 TemplateName Template,
5245 TemplateArgumentListInfo NewTemplateArgs;
5246 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5247 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5248 typedef TemplateArgumentLocContainerIterator<
5249 DependentTemplateSpecializationTypeLoc> ArgIterator;
5250 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5251 ArgIterator(TL, TL.getNumArgs()),
5255 // FIXME: maybe don't rebuild if all the template arguments are the same.
5257 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
5259 = getSema().Context.getDependentTemplateSpecializationType(
5260 TL.getTypePtr()->getKeyword(),
5261 DTN->getQualifier(),
5262 DTN->getIdentifier(),
5265 DependentTemplateSpecializationTypeLoc NewTL
5266 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5267 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5268 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
5269 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5270 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5271 NewTL.setLAngleLoc(TL.getLAngleLoc());
5272 NewTL.setRAngleLoc(TL.getRAngleLoc());
5273 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5274 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5279 = getDerived().RebuildTemplateSpecializationType(Template,
5280 TL.getTemplateNameLoc(),
5283 if (!Result.isNull()) {
5284 /// FIXME: Wrap this in an elaborated-type-specifier?
5285 TemplateSpecializationTypeLoc NewTL
5286 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5287 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5288 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5289 NewTL.setLAngleLoc(TL.getLAngleLoc());
5290 NewTL.setRAngleLoc(TL.getRAngleLoc());
5291 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5292 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5298 template<typename Derived>
5300 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
5301 ElaboratedTypeLoc TL) {
5302 const ElaboratedType *T = TL.getTypePtr();
5304 NestedNameSpecifierLoc QualifierLoc;
5305 // NOTE: the qualifier in an ElaboratedType is optional.
5306 if (TL.getQualifierLoc()) {
5308 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5313 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
5314 if (NamedT.isNull())
5317 // C++0x [dcl.type.elab]p2:
5318 // If the identifier resolves to a typedef-name or the simple-template-id
5319 // resolves to an alias template specialization, the
5320 // elaborated-type-specifier is ill-formed.
5321 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
5322 if (const TemplateSpecializationType *TST =
5323 NamedT->getAs<TemplateSpecializationType>()) {
5324 TemplateName Template = TST->getTemplateName();
5325 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
5326 Template.getAsTemplateDecl())) {
5327 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
5328 diag::err_tag_reference_non_tag) << 4;
5329 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
5334 QualType Result = TL.getType();
5335 if (getDerived().AlwaysRebuild() ||
5336 QualifierLoc != TL.getQualifierLoc() ||
5337 NamedT != T->getNamedType()) {
5338 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
5340 QualifierLoc, NamedT);
5341 if (Result.isNull())
5345 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5346 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5347 NewTL.setQualifierLoc(QualifierLoc);
5351 template<typename Derived>
5352 QualType TreeTransform<Derived>::TransformAttributedType(
5353 TypeLocBuilder &TLB,
5354 AttributedTypeLoc TL) {
5355 const AttributedType *oldType = TL.getTypePtr();
5356 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
5357 if (modifiedType.isNull())
5360 QualType result = TL.getType();
5362 // FIXME: dependent operand expressions?
5363 if (getDerived().AlwaysRebuild() ||
5364 modifiedType != oldType->getModifiedType()) {
5365 // TODO: this is really lame; we should really be rebuilding the
5366 // equivalent type from first principles.
5367 QualType equivalentType
5368 = getDerived().TransformType(oldType->getEquivalentType());
5369 if (equivalentType.isNull())
5371 result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
5376 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
5377 newTL.setAttrNameLoc(TL.getAttrNameLoc());
5378 if (TL.hasAttrOperand())
5379 newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5380 if (TL.hasAttrExprOperand())
5381 newTL.setAttrExprOperand(TL.getAttrExprOperand());
5382 else if (TL.hasAttrEnumOperand())
5383 newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
5388 template<typename Derived>
5390 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
5392 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
5396 QualType Result = TL.getType();
5397 if (getDerived().AlwaysRebuild() ||
5398 Inner != TL.getInnerLoc().getType()) {
5399 Result = getDerived().RebuildParenType(Inner);
5400 if (Result.isNull())
5404 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
5405 NewTL.setLParenLoc(TL.getLParenLoc());
5406 NewTL.setRParenLoc(TL.getRParenLoc());
5410 template<typename Derived>
5411 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
5412 DependentNameTypeLoc TL) {
5413 const DependentNameType *T = TL.getTypePtr();
5415 NestedNameSpecifierLoc QualifierLoc
5416 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5421 = getDerived().RebuildDependentNameType(T->getKeyword(),
5422 TL.getElaboratedKeywordLoc(),
5426 if (Result.isNull())
5429 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5430 QualType NamedT = ElabT->getNamedType();
5431 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5433 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5434 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5435 NewTL.setQualifierLoc(QualifierLoc);
5437 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5438 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5439 NewTL.setQualifierLoc(QualifierLoc);
5440 NewTL.setNameLoc(TL.getNameLoc());
5445 template<typename Derived>
5446 QualType TreeTransform<Derived>::
5447 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5448 DependentTemplateSpecializationTypeLoc TL) {
5449 NestedNameSpecifierLoc QualifierLoc;
5450 if (TL.getQualifierLoc()) {
5452 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5458 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
5461 template<typename Derived>
5462 QualType TreeTransform<Derived>::
5463 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5464 DependentTemplateSpecializationTypeLoc TL,
5465 NestedNameSpecifierLoc QualifierLoc) {
5466 const DependentTemplateSpecializationType *T = TL.getTypePtr();
5468 TemplateArgumentListInfo NewTemplateArgs;
5469 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5470 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5472 typedef TemplateArgumentLocContainerIterator<
5473 DependentTemplateSpecializationTypeLoc> ArgIterator;
5474 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5475 ArgIterator(TL, TL.getNumArgs()),
5480 = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
5483 TL.getTemplateNameLoc(),
5485 if (Result.isNull())
5488 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
5489 QualType NamedT = ElabT->getNamedType();
5491 // Copy information relevant to the template specialization.
5492 TemplateSpecializationTypeLoc NamedTL
5493 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5494 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5495 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5496 NamedTL.setLAngleLoc(TL.getLAngleLoc());
5497 NamedTL.setRAngleLoc(TL.getRAngleLoc());
5498 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5499 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5501 // Copy information relevant to the elaborated type.
5502 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5503 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5504 NewTL.setQualifierLoc(QualifierLoc);
5505 } else if (isa<DependentTemplateSpecializationType>(Result)) {
5506 DependentTemplateSpecializationTypeLoc SpecTL
5507 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5508 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5509 SpecTL.setQualifierLoc(QualifierLoc);
5510 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5511 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5512 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5513 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5514 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5515 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5517 TemplateSpecializationTypeLoc SpecTL
5518 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5519 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5520 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5521 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5522 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5523 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5524 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5529 template<typename Derived>
5530 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
5531 PackExpansionTypeLoc TL) {
5533 = getDerived().TransformType(TLB, TL.getPatternLoc());
5534 if (Pattern.isNull())
5537 QualType Result = TL.getType();
5538 if (getDerived().AlwaysRebuild() ||
5539 Pattern != TL.getPatternLoc().getType()) {
5540 Result = getDerived().RebuildPackExpansionType(Pattern,
5541 TL.getPatternLoc().getSourceRange(),
5542 TL.getEllipsisLoc(),
5543 TL.getTypePtr()->getNumExpansions());
5544 if (Result.isNull())
5548 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
5549 NewT.setEllipsisLoc(TL.getEllipsisLoc());
5553 template<typename Derived>
5555 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
5556 ObjCInterfaceTypeLoc TL) {
5557 // ObjCInterfaceType is never dependent.
5558 TLB.pushFullCopy(TL);
5559 return TL.getType();
5562 template<typename Derived>
5564 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
5565 ObjCObjectTypeLoc TL) {
5566 // ObjCObjectType is never dependent.
5567 TLB.pushFullCopy(TL);
5568 return TL.getType();
5571 template<typename Derived>
5573 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
5574 ObjCObjectPointerTypeLoc TL) {
5575 // ObjCObjectPointerType is never dependent.
5576 TLB.pushFullCopy(TL);
5577 return TL.getType();
5580 //===----------------------------------------------------------------------===//
5581 // Statement transformation
5582 //===----------------------------------------------------------------------===//
5583 template<typename Derived>
5585 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
5589 template<typename Derived>
5591 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
5592 return getDerived().TransformCompoundStmt(S, false);
5595 template<typename Derived>
5597 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
5599 Sema::CompoundScopeRAII CompoundScope(getSema());
5601 bool SubStmtInvalid = false;
5602 bool SubStmtChanged = false;
5603 SmallVector<Stmt*, 8> Statements;
5604 for (auto *B : S->body()) {
5605 StmtResult Result = getDerived().TransformStmt(B);
5606 if (Result.isInvalid()) {
5607 // Immediately fail if this was a DeclStmt, since it's very
5608 // likely that this will cause problems for future statements.
5609 if (isa<DeclStmt>(B))
5612 // Otherwise, just keep processing substatements and fail later.
5613 SubStmtInvalid = true;
5617 SubStmtChanged = SubStmtChanged || Result.get() != B;
5618 Statements.push_back(Result.getAs<Stmt>());
5624 if (!getDerived().AlwaysRebuild() &&
5628 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
5634 template<typename Derived>
5636 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
5637 ExprResult LHS, RHS;
5639 EnterExpressionEvaluationContext Unevaluated(SemaRef,
5640 Sema::ConstantEvaluated);
5642 // Transform the left-hand case value.
5643 LHS = getDerived().TransformExpr(S->getLHS());
5644 LHS = SemaRef.ActOnConstantExpression(LHS);
5645 if (LHS.isInvalid())
5648 // Transform the right-hand case value (for the GNU case-range extension).
5649 RHS = getDerived().TransformExpr(S->getRHS());
5650 RHS = SemaRef.ActOnConstantExpression(RHS);
5651 if (RHS.isInvalid())
5655 // Build the case statement.
5656 // Case statements are always rebuilt so that they will attached to their
5657 // transformed switch statement.
5658 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
5660 S->getEllipsisLoc(),
5663 if (Case.isInvalid())
5666 // Transform the statement following the case
5667 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5668 if (SubStmt.isInvalid())
5671 // Attach the body to the case statement
5672 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
5675 template<typename Derived>
5677 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
5678 // Transform the statement following the default case
5679 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5680 if (SubStmt.isInvalid())
5683 // Default statements are always rebuilt
5684 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
5688 template<typename Derived>
5690 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
5691 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5692 if (SubStmt.isInvalid())
5695 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
5701 // FIXME: Pass the real colon location in.
5702 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
5703 cast<LabelDecl>(LD), SourceLocation(),
5707 template <typename Derived>
5708 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
5712 switch (R->getKind()) {
5713 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
5715 #define PRAGMA_SPELLING_ATTR(X) \
5717 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
5718 #include "clang/Basic/AttrList.inc"
5724 template <typename Derived>
5725 StmtResult TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
5726 bool AttrsChanged = false;
5727 SmallVector<const Attr *, 1> Attrs;
5729 // Visit attributes and keep track if any are transformed.
5730 for (const auto *I : S->getAttrs()) {
5731 const Attr *R = getDerived().TransformAttr(I);
5732 AttrsChanged |= (I != R);
5736 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5737 if (SubStmt.isInvalid())
5740 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
5743 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
5747 template<typename Derived>
5749 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
5750 // Transform the condition
5752 VarDecl *ConditionVar = nullptr;
5753 if (S->getConditionVariable()) {
5755 = cast_or_null<VarDecl>(
5756 getDerived().TransformDefinition(
5757 S->getConditionVariable()->getLocation(),
5758 S->getConditionVariable()));
5762 Cond = getDerived().TransformExpr(S->getCond());
5764 if (Cond.isInvalid())
5767 // Convert the condition to a boolean value.
5769 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr, S->getIfLoc(),
5771 if (CondE.isInvalid())
5778 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5779 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5782 // Transform the "then" branch.
5783 StmtResult Then = getDerived().TransformStmt(S->getThen());
5784 if (Then.isInvalid())
5787 // Transform the "else" branch.
5788 StmtResult Else = getDerived().TransformStmt(S->getElse());
5789 if (Else.isInvalid())
5792 if (!getDerived().AlwaysRebuild() &&
5793 FullCond.get() == S->getCond() &&
5794 ConditionVar == S->getConditionVariable() &&
5795 Then.get() == S->getThen() &&
5796 Else.get() == S->getElse())
5799 return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
5801 S->getElseLoc(), Else.get());
5804 template<typename Derived>
5806 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
5807 // Transform the condition.
5809 VarDecl *ConditionVar = nullptr;
5810 if (S->getConditionVariable()) {
5812 = cast_or_null<VarDecl>(
5813 getDerived().TransformDefinition(
5814 S->getConditionVariable()->getLocation(),
5815 S->getConditionVariable()));
5819 Cond = getDerived().TransformExpr(S->getCond());
5821 if (Cond.isInvalid())
5825 // Rebuild the switch statement.
5827 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
5829 if (Switch.isInvalid())
5832 // Transform the body of the switch statement.
5833 StmtResult Body = getDerived().TransformStmt(S->getBody());
5834 if (Body.isInvalid())
5837 // Complete the switch statement.
5838 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
5842 template<typename Derived>
5844 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
5845 // Transform the condition
5847 VarDecl *ConditionVar = nullptr;
5848 if (S->getConditionVariable()) {
5850 = cast_or_null<VarDecl>(
5851 getDerived().TransformDefinition(
5852 S->getConditionVariable()->getLocation(),
5853 S->getConditionVariable()));
5857 Cond = getDerived().TransformExpr(S->getCond());
5859 if (Cond.isInvalid())
5863 // Convert the condition to a boolean value.
5864 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
5867 if (CondE.isInvalid())
5873 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5874 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5877 // Transform the body
5878 StmtResult Body = getDerived().TransformStmt(S->getBody());
5879 if (Body.isInvalid())
5882 if (!getDerived().AlwaysRebuild() &&
5883 FullCond.get() == S->getCond() &&
5884 ConditionVar == S->getConditionVariable() &&
5885 Body.get() == S->getBody())
5888 return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
5889 ConditionVar, Body.get());
5892 template<typename Derived>
5894 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
5895 // Transform the body
5896 StmtResult Body = getDerived().TransformStmt(S->getBody());
5897 if (Body.isInvalid())
5900 // Transform the condition
5901 ExprResult Cond = getDerived().TransformExpr(S->getCond());
5902 if (Cond.isInvalid())
5905 if (!getDerived().AlwaysRebuild() &&
5906 Cond.get() == S->getCond() &&
5907 Body.get() == S->getBody())
5910 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
5911 /*FIXME:*/S->getWhileLoc(), Cond.get(),
5915 template<typename Derived>
5917 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
5918 // Transform the initialization statement
5919 StmtResult Init = getDerived().TransformStmt(S->getInit());
5920 if (Init.isInvalid())
5923 // Transform the condition
5925 VarDecl *ConditionVar = nullptr;
5926 if (S->getConditionVariable()) {
5928 = cast_or_null<VarDecl>(
5929 getDerived().TransformDefinition(
5930 S->getConditionVariable()->getLocation(),
5931 S->getConditionVariable()));
5935 Cond = getDerived().TransformExpr(S->getCond());
5937 if (Cond.isInvalid())
5941 // Convert the condition to a boolean value.
5942 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
5945 if (CondE.isInvalid())
5952 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5953 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5956 // Transform the increment
5957 ExprResult Inc = getDerived().TransformExpr(S->getInc());
5958 if (Inc.isInvalid())
5961 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
5962 if (S->getInc() && !FullInc.get())
5965 // Transform the body
5966 StmtResult Body = getDerived().TransformStmt(S->getBody());
5967 if (Body.isInvalid())
5970 if (!getDerived().AlwaysRebuild() &&
5971 Init.get() == S->getInit() &&
5972 FullCond.get() == S->getCond() &&
5973 Inc.get() == S->getInc() &&
5974 Body.get() == S->getBody())
5977 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
5978 Init.get(), FullCond, ConditionVar,
5979 FullInc, S->getRParenLoc(), Body.get());
5982 template<typename Derived>
5984 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
5985 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
5990 // Goto statements must always be rebuilt, to resolve the label.
5991 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
5992 cast<LabelDecl>(LD));
5995 template<typename Derived>
5997 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
5998 ExprResult Target = getDerived().TransformExpr(S->getTarget());
5999 if (Target.isInvalid())
6001 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6003 if (!getDerived().AlwaysRebuild() &&
6004 Target.get() == S->getTarget())
6007 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6011 template<typename Derived>
6013 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6017 template<typename Derived>
6019 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6023 template<typename Derived>
6025 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
6026 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
6027 /*NotCopyInit*/false);
6028 if (Result.isInvalid())
6031 // FIXME: We always rebuild the return statement because there is no way
6032 // to tell whether the return type of the function has changed.
6033 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
6036 template<typename Derived>
6038 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
6039 bool DeclChanged = false;
6040 SmallVector<Decl *, 4> Decls;
6041 for (auto *D : S->decls()) {
6042 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
6046 if (Transformed != D)
6049 Decls.push_back(Transformed);
6052 if (!getDerived().AlwaysRebuild() && !DeclChanged)
6055 return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
6058 template<typename Derived>
6060 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
6062 SmallVector<Expr*, 8> Constraints;
6063 SmallVector<Expr*, 8> Exprs;
6064 SmallVector<IdentifierInfo *, 4> Names;
6066 ExprResult AsmString;
6067 SmallVector<Expr*, 8> Clobbers;
6069 bool ExprsChanged = false;
6071 // Go through the outputs.
6072 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
6073 Names.push_back(S->getOutputIdentifier(I));
6075 // No need to transform the constraint literal.
6076 Constraints.push_back(S->getOutputConstraintLiteral(I));
6078 // Transform the output expr.
6079 Expr *OutputExpr = S->getOutputExpr(I);
6080 ExprResult Result = getDerived().TransformExpr(OutputExpr);
6081 if (Result.isInvalid())
6084 ExprsChanged |= Result.get() != OutputExpr;
6086 Exprs.push_back(Result.get());
6089 // Go through the inputs.
6090 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
6091 Names.push_back(S->getInputIdentifier(I));
6093 // No need to transform the constraint literal.
6094 Constraints.push_back(S->getInputConstraintLiteral(I));
6096 // Transform the input expr.
6097 Expr *InputExpr = S->getInputExpr(I);
6098 ExprResult Result = getDerived().TransformExpr(InputExpr);
6099 if (Result.isInvalid())
6102 ExprsChanged |= Result.get() != InputExpr;
6104 Exprs.push_back(Result.get());
6107 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
6110 // Go through the clobbers.
6111 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
6112 Clobbers.push_back(S->getClobberStringLiteral(I));
6114 // No need to transform the asm string literal.
6115 AsmString = S->getAsmString();
6116 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
6117 S->isVolatile(), S->getNumOutputs(),
6118 S->getNumInputs(), Names.data(),
6119 Constraints, Exprs, AsmString.get(),
6120 Clobbers, S->getRParenLoc());
6123 template<typename Derived>
6125 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
6126 ArrayRef<Token> AsmToks =
6127 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
6129 bool HadError = false, HadChange = false;
6131 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
6132 SmallVector<Expr*, 8> TransformedExprs;
6133 TransformedExprs.reserve(SrcExprs.size());
6134 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
6135 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
6136 if (!Result.isUsable()) {
6139 HadChange |= (Result.get() != SrcExprs[i]);
6140 TransformedExprs.push_back(Result.get());
6144 if (HadError) return StmtError();
6145 if (!HadChange && !getDerived().AlwaysRebuild())
6148 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
6149 AsmToks, S->getAsmString(),
6150 S->getNumOutputs(), S->getNumInputs(),
6151 S->getAllConstraints(), S->getClobbers(),
6152 TransformedExprs, S->getEndLoc());
6155 template<typename Derived>
6157 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
6158 // Transform the body of the @try.
6159 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
6160 if (TryBody.isInvalid())
6163 // Transform the @catch statements (if present).
6164 bool AnyCatchChanged = false;
6165 SmallVector<Stmt*, 8> CatchStmts;
6166 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
6167 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
6168 if (Catch.isInvalid())
6170 if (Catch.get() != S->getCatchStmt(I))
6171 AnyCatchChanged = true;
6172 CatchStmts.push_back(Catch.get());
6175 // Transform the @finally statement (if present).
6177 if (S->getFinallyStmt()) {
6178 Finally = getDerived().TransformStmt(S->getFinallyStmt());
6179 if (Finally.isInvalid())
6183 // If nothing changed, just retain this statement.
6184 if (!getDerived().AlwaysRebuild() &&
6185 TryBody.get() == S->getTryBody() &&
6187 Finally.get() == S->getFinallyStmt())
6190 // Build a new statement.
6191 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
6192 CatchStmts, Finally.get());
6195 template<typename Derived>
6197 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
6198 // Transform the @catch parameter, if there is one.
6199 VarDecl *Var = nullptr;
6200 if (VarDecl *FromVar = S->getCatchParamDecl()) {
6201 TypeSourceInfo *TSInfo = nullptr;
6202 if (FromVar->getTypeSourceInfo()) {
6203 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
6210 T = TSInfo->getType();
6212 T = getDerived().TransformType(FromVar->getType());
6217 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
6222 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
6223 if (Body.isInvalid())
6226 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
6231 template<typename Derived>
6233 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
6234 // Transform the body.
6235 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
6236 if (Body.isInvalid())
6239 // If nothing changed, just retain this statement.
6240 if (!getDerived().AlwaysRebuild() &&
6241 Body.get() == S->getFinallyBody())
6244 // Build a new statement.
6245 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
6249 template<typename Derived>
6251 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
6253 if (S->getThrowExpr()) {
6254 Operand = getDerived().TransformExpr(S->getThrowExpr());
6255 if (Operand.isInvalid())
6259 if (!getDerived().AlwaysRebuild() &&
6260 Operand.get() == S->getThrowExpr())
6263 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
6266 template<typename Derived>
6268 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
6269 ObjCAtSynchronizedStmt *S) {
6270 // Transform the object we are locking.
6271 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
6272 if (Object.isInvalid())
6275 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
6277 if (Object.isInvalid())
6280 // Transform the body.
6281 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
6282 if (Body.isInvalid())
6285 // If nothing change, just retain the current statement.
6286 if (!getDerived().AlwaysRebuild() &&
6287 Object.get() == S->getSynchExpr() &&
6288 Body.get() == S->getSynchBody())
6291 // Build a new statement.
6292 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
6293 Object.get(), Body.get());
6296 template<typename Derived>
6298 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
6299 ObjCAutoreleasePoolStmt *S) {
6300 // Transform the body.
6301 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
6302 if (Body.isInvalid())
6305 // If nothing changed, just retain this statement.
6306 if (!getDerived().AlwaysRebuild() &&
6307 Body.get() == S->getSubStmt())
6310 // Build a new statement.
6311 return getDerived().RebuildObjCAutoreleasePoolStmt(
6312 S->getAtLoc(), Body.get());
6315 template<typename Derived>
6317 TreeTransform<Derived>::TransformObjCForCollectionStmt(
6318 ObjCForCollectionStmt *S) {
6319 // Transform the element statement.
6320 StmtResult Element = getDerived().TransformStmt(S->getElement());
6321 if (Element.isInvalid())
6324 // Transform the collection expression.
6325 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
6326 if (Collection.isInvalid())
6329 // Transform the body.
6330 StmtResult Body = getDerived().TransformStmt(S->getBody());
6331 if (Body.isInvalid())
6334 // If nothing changed, just retain this statement.
6335 if (!getDerived().AlwaysRebuild() &&
6336 Element.get() == S->getElement() &&
6337 Collection.get() == S->getCollection() &&
6338 Body.get() == S->getBody())
6341 // Build a new statement.
6342 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
6349 template <typename Derived>
6350 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
6351 // Transform the exception declaration, if any.
6352 VarDecl *Var = nullptr;
6353 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
6355 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
6359 Var = getDerived().RebuildExceptionDecl(
6360 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
6361 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
6362 if (!Var || Var->isInvalidDecl())
6366 // Transform the actual exception handler.
6367 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
6368 if (Handler.isInvalid())
6371 if (!getDerived().AlwaysRebuild() && !Var &&
6372 Handler.get() == S->getHandlerBlock())
6375 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
6378 template <typename Derived>
6379 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
6380 // Transform the try block itself.
6381 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
6382 if (TryBlock.isInvalid())
6385 // Transform the handlers.
6386 bool HandlerChanged = false;
6387 SmallVector<Stmt *, 8> Handlers;
6388 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
6389 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
6390 if (Handler.isInvalid())
6393 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
6394 Handlers.push_back(Handler.getAs<Stmt>());
6397 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
6401 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
6405 template<typename Derived>
6407 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
6408 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
6409 if (Range.isInvalid())
6412 StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
6413 if (BeginEnd.isInvalid())
6416 ExprResult Cond = getDerived().TransformExpr(S->getCond());
6417 if (Cond.isInvalid())
6420 Cond = SemaRef.CheckBooleanCondition(Cond.get(), S->getColonLoc());
6421 if (Cond.isInvalid())
6424 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
6426 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6427 if (Inc.isInvalid())
6430 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
6432 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
6433 if (LoopVar.isInvalid())
6436 StmtResult NewStmt = S;
6437 if (getDerived().AlwaysRebuild() ||
6438 Range.get() != S->getRangeStmt() ||
6439 BeginEnd.get() != S->getBeginEndStmt() ||
6440 Cond.get() != S->getCond() ||
6441 Inc.get() != S->getInc() ||
6442 LoopVar.get() != S->getLoopVarStmt()) {
6443 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6444 S->getColonLoc(), Range.get(),
6445 BeginEnd.get(), Cond.get(),
6446 Inc.get(), LoopVar.get(),
6448 if (NewStmt.isInvalid())
6452 StmtResult Body = getDerived().TransformStmt(S->getBody());
6453 if (Body.isInvalid())
6456 // Body has changed but we didn't rebuild the for-range statement. Rebuild
6457 // it now so we have a new statement to attach the body to.
6458 if (Body.get() != S->getBody() && NewStmt.get() == S) {
6459 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6460 S->getColonLoc(), Range.get(),
6461 BeginEnd.get(), Cond.get(),
6462 Inc.get(), LoopVar.get(),
6464 if (NewStmt.isInvalid())
6468 if (NewStmt.get() == S)
6471 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
6474 template<typename Derived>
6476 TreeTransform<Derived>::TransformMSDependentExistsStmt(
6477 MSDependentExistsStmt *S) {
6478 // Transform the nested-name-specifier, if any.
6479 NestedNameSpecifierLoc QualifierLoc;
6480 if (S->getQualifierLoc()) {
6482 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
6487 // Transform the declaration name.
6488 DeclarationNameInfo NameInfo = S->getNameInfo();
6489 if (NameInfo.getName()) {
6490 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
6491 if (!NameInfo.getName())
6495 // Check whether anything changed.
6496 if (!getDerived().AlwaysRebuild() &&
6497 QualifierLoc == S->getQualifierLoc() &&
6498 NameInfo.getName() == S->getNameInfo().getName())
6501 // Determine whether this name exists, if we can.
6503 SS.Adopt(QualifierLoc);
6504 bool Dependent = false;
6505 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
6506 case Sema::IER_Exists:
6507 if (S->isIfExists())
6510 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6512 case Sema::IER_DoesNotExist:
6513 if (S->isIfNotExists())
6516 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6518 case Sema::IER_Dependent:
6522 case Sema::IER_Error:
6526 // We need to continue with the instantiation, so do so now.
6527 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
6528 if (SubStmt.isInvalid())
6531 // If we have resolved the name, just transform to the substatement.
6535 // The name is still dependent, so build a dependent expression again.
6536 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
6543 template<typename Derived>
6545 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
6546 NestedNameSpecifierLoc QualifierLoc;
6547 if (E->getQualifierLoc()) {
6549 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6554 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
6555 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
6559 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
6560 if (Base.isInvalid())
6563 return new (SemaRef.getASTContext())
6564 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
6565 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
6566 QualifierLoc, E->getMemberLoc());
6569 template <typename Derived>
6570 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
6571 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
6572 if (TryBlock.isInvalid())
6575 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
6576 if (Handler.isInvalid())
6579 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
6580 Handler.get() == S->getHandler())
6583 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
6584 TryBlock.get(), Handler.get());
6587 template <typename Derived>
6588 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
6589 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
6590 if (Block.isInvalid())
6593 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
6596 template <typename Derived>
6597 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
6598 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
6599 if (FilterExpr.isInvalid())
6602 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
6603 if (Block.isInvalid())
6606 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
6610 template <typename Derived>
6611 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
6612 if (isa<SEHFinallyStmt>(Handler))
6613 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
6615 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
6618 template<typename Derived>
6620 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
6624 //===----------------------------------------------------------------------===//
6625 // OpenMP directive transformation
6626 //===----------------------------------------------------------------------===//
6627 template <typename Derived>
6628 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
6629 OMPExecutableDirective *D) {
6631 // Transform the clauses
6632 llvm::SmallVector<OMPClause *, 16> TClauses;
6633 ArrayRef<OMPClause *> Clauses = D->clauses();
6634 TClauses.reserve(Clauses.size());
6635 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
6638 OMPClause *Clause = getDerived().TransformOMPClause(*I);
6640 TClauses.push_back(Clause);
6642 TClauses.push_back(nullptr);
6645 StmtResult AssociatedStmt;
6646 if (D->hasAssociatedStmt()) {
6647 if (!D->getAssociatedStmt()) {
6650 AssociatedStmt = getDerived().TransformStmt(D->getAssociatedStmt());
6651 if (AssociatedStmt.isInvalid()) {
6655 if (TClauses.size() != Clauses.size()) {
6659 // Transform directive name for 'omp critical' directive.
6660 DeclarationNameInfo DirName;
6661 if (D->getDirectiveKind() == OMPD_critical) {
6662 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
6663 DirName = getDerived().TransformDeclarationNameInfo(DirName);
6666 return getDerived().RebuildOMPExecutableDirective(
6667 D->getDirectiveKind(), DirName, TClauses, AssociatedStmt.get(),
6668 D->getLocStart(), D->getLocEnd());
6671 template <typename Derived>
6673 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
6674 DeclarationNameInfo DirName;
6675 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
6677 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6678 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6682 template <typename Derived>
6684 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
6685 DeclarationNameInfo DirName;
6686 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
6688 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6689 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6693 template <typename Derived>
6695 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
6696 DeclarationNameInfo DirName;
6697 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
6699 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6700 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6704 template <typename Derived>
6706 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
6707 DeclarationNameInfo DirName;
6708 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
6710 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6711 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6715 template <typename Derived>
6717 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
6718 DeclarationNameInfo DirName;
6719 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
6721 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6722 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6726 template <typename Derived>
6728 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
6729 DeclarationNameInfo DirName;
6730 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
6732 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6733 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6737 template <typename Derived>
6739 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
6740 DeclarationNameInfo DirName;
6741 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
6743 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6744 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6748 template <typename Derived>
6750 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
6751 DeclarationNameInfo DirName;
6752 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
6754 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6755 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6759 template <typename Derived>
6761 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
6762 getDerived().getSema().StartOpenMPDSABlock(
6763 OMPD_critical, D->getDirectiveName(), nullptr, D->getLocStart());
6764 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6765 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6769 template <typename Derived>
6770 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
6771 OMPParallelForDirective *D) {
6772 DeclarationNameInfo DirName;
6773 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
6774 nullptr, D->getLocStart());
6775 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6776 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6780 template <typename Derived>
6781 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
6782 OMPParallelForSimdDirective *D) {
6783 DeclarationNameInfo DirName;
6784 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
6785 nullptr, D->getLocStart());
6786 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6787 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6791 template <typename Derived>
6792 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
6793 OMPParallelSectionsDirective *D) {
6794 DeclarationNameInfo DirName;
6795 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
6796 nullptr, D->getLocStart());
6797 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6798 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6802 template <typename Derived>
6804 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
6805 DeclarationNameInfo DirName;
6806 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
6808 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6809 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6813 template <typename Derived>
6814 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
6815 OMPTaskyieldDirective *D) {
6816 DeclarationNameInfo DirName;
6817 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
6819 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6820 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6824 template <typename Derived>
6826 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
6827 DeclarationNameInfo DirName;
6828 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
6830 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6831 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6835 template <typename Derived>
6837 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
6838 DeclarationNameInfo DirName;
6839 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
6841 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6842 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6846 template <typename Derived>
6848 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
6849 DeclarationNameInfo DirName;
6850 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
6852 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6853 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6857 template <typename Derived>
6859 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
6860 DeclarationNameInfo DirName;
6861 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
6863 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6864 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6868 template <typename Derived>
6870 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
6871 DeclarationNameInfo DirName;
6872 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
6874 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6875 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6879 template <typename Derived>
6881 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
6882 DeclarationNameInfo DirName;
6883 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
6885 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6886 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6890 template <typename Derived>
6892 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
6893 DeclarationNameInfo DirName;
6894 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
6896 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6897 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6901 //===----------------------------------------------------------------------===//
6902 // OpenMP clause transformation
6903 //===----------------------------------------------------------------------===//
6904 template <typename Derived>
6905 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
6906 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
6907 if (Cond.isInvalid())
6909 return getDerived().RebuildOMPIfClause(Cond.get(), C->getLocStart(),
6910 C->getLParenLoc(), C->getLocEnd());
6913 template <typename Derived>
6914 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
6915 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
6916 if (Cond.isInvalid())
6918 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getLocStart(),
6919 C->getLParenLoc(), C->getLocEnd());
6922 template <typename Derived>
6924 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
6925 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
6926 if (NumThreads.isInvalid())
6928 return getDerived().RebuildOMPNumThreadsClause(
6929 NumThreads.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
6932 template <typename Derived>
6934 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
6935 ExprResult E = getDerived().TransformExpr(C->getSafelen());
6938 return getDerived().RebuildOMPSafelenClause(
6939 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
6942 template <typename Derived>
6944 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
6945 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
6948 return getDerived().RebuildOMPCollapseClause(
6949 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
6952 template <typename Derived>
6954 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
6955 return getDerived().RebuildOMPDefaultClause(
6956 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getLocStart(),
6957 C->getLParenLoc(), C->getLocEnd());
6960 template <typename Derived>
6962 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
6963 return getDerived().RebuildOMPProcBindClause(
6964 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getLocStart(),
6965 C->getLParenLoc(), C->getLocEnd());
6968 template <typename Derived>
6970 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
6971 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
6974 return getDerived().RebuildOMPScheduleClause(
6975 C->getScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
6976 C->getScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
6979 template <typename Derived>
6981 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
6982 // No need to rebuild this clause, no template-dependent parameters.
6986 template <typename Derived>
6988 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
6989 // No need to rebuild this clause, no template-dependent parameters.
6993 template <typename Derived>
6995 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
6996 // No need to rebuild this clause, no template-dependent parameters.
7000 template <typename Derived>
7002 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
7003 // No need to rebuild this clause, no template-dependent parameters.
7007 template <typename Derived>
7008 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
7009 // No need to rebuild this clause, no template-dependent parameters.
7013 template <typename Derived>
7014 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
7015 // No need to rebuild this clause, no template-dependent parameters.
7019 template <typename Derived>
7021 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
7022 // No need to rebuild this clause, no template-dependent parameters.
7026 template <typename Derived>
7028 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
7029 // No need to rebuild this clause, no template-dependent parameters.
7033 template <typename Derived>
7035 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
7036 // No need to rebuild this clause, no template-dependent parameters.
7040 template <typename Derived>
7042 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
7043 llvm::SmallVector<Expr *, 16> Vars;
7044 Vars.reserve(C->varlist_size());
7045 for (auto *VE : C->varlists()) {
7046 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7047 if (EVar.isInvalid())
7049 Vars.push_back(EVar.get());
7051 return getDerived().RebuildOMPPrivateClause(
7052 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7055 template <typename Derived>
7056 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
7057 OMPFirstprivateClause *C) {
7058 llvm::SmallVector<Expr *, 16> Vars;
7059 Vars.reserve(C->varlist_size());
7060 for (auto *VE : C->varlists()) {
7061 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7062 if (EVar.isInvalid())
7064 Vars.push_back(EVar.get());
7066 return getDerived().RebuildOMPFirstprivateClause(
7067 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7070 template <typename Derived>
7072 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
7073 llvm::SmallVector<Expr *, 16> Vars;
7074 Vars.reserve(C->varlist_size());
7075 for (auto *VE : C->varlists()) {
7076 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7077 if (EVar.isInvalid())
7079 Vars.push_back(EVar.get());
7081 return getDerived().RebuildOMPLastprivateClause(
7082 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7085 template <typename Derived>
7087 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
7088 llvm::SmallVector<Expr *, 16> Vars;
7089 Vars.reserve(C->varlist_size());
7090 for (auto *VE : C->varlists()) {
7091 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7092 if (EVar.isInvalid())
7094 Vars.push_back(EVar.get());
7096 return getDerived().RebuildOMPSharedClause(Vars, C->getLocStart(),
7097 C->getLParenLoc(), C->getLocEnd());
7100 template <typename Derived>
7102 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
7103 llvm::SmallVector<Expr *, 16> Vars;
7104 Vars.reserve(C->varlist_size());
7105 for (auto *VE : C->varlists()) {
7106 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7107 if (EVar.isInvalid())
7109 Vars.push_back(EVar.get());
7111 CXXScopeSpec ReductionIdScopeSpec;
7112 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
7114 DeclarationNameInfo NameInfo = C->getNameInfo();
7115 if (NameInfo.getName()) {
7116 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7117 if (!NameInfo.getName())
7120 return getDerived().RebuildOMPReductionClause(
7121 Vars, C->getLocStart(), C->getLParenLoc(), C->getColonLoc(),
7122 C->getLocEnd(), ReductionIdScopeSpec, NameInfo);
7125 template <typename Derived>
7127 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
7128 llvm::SmallVector<Expr *, 16> Vars;
7129 Vars.reserve(C->varlist_size());
7130 for (auto *VE : C->varlists()) {
7131 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7132 if (EVar.isInvalid())
7134 Vars.push_back(EVar.get());
7136 ExprResult Step = getDerived().TransformExpr(C->getStep());
7137 if (Step.isInvalid())
7139 return getDerived().RebuildOMPLinearClause(Vars, Step.get(), C->getLocStart(),
7141 C->getColonLoc(), C->getLocEnd());
7144 template <typename Derived>
7146 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
7147 llvm::SmallVector<Expr *, 16> Vars;
7148 Vars.reserve(C->varlist_size());
7149 for (auto *VE : C->varlists()) {
7150 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7151 if (EVar.isInvalid())
7153 Vars.push_back(EVar.get());
7155 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
7156 if (Alignment.isInvalid())
7158 return getDerived().RebuildOMPAlignedClause(
7159 Vars, Alignment.get(), C->getLocStart(), C->getLParenLoc(),
7160 C->getColonLoc(), C->getLocEnd());
7163 template <typename Derived>
7165 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
7166 llvm::SmallVector<Expr *, 16> Vars;
7167 Vars.reserve(C->varlist_size());
7168 for (auto *VE : C->varlists()) {
7169 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7170 if (EVar.isInvalid())
7172 Vars.push_back(EVar.get());
7174 return getDerived().RebuildOMPCopyinClause(Vars, C->getLocStart(),
7175 C->getLParenLoc(), C->getLocEnd());
7178 template <typename Derived>
7180 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
7181 llvm::SmallVector<Expr *, 16> Vars;
7182 Vars.reserve(C->varlist_size());
7183 for (auto *VE : C->varlists()) {
7184 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7185 if (EVar.isInvalid())
7187 Vars.push_back(EVar.get());
7189 return getDerived().RebuildOMPCopyprivateClause(
7190 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7193 template <typename Derived>
7194 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
7195 llvm::SmallVector<Expr *, 16> Vars;
7196 Vars.reserve(C->varlist_size());
7197 for (auto *VE : C->varlists()) {
7198 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7199 if (EVar.isInvalid())
7201 Vars.push_back(EVar.get());
7203 return getDerived().RebuildOMPFlushClause(Vars, C->getLocStart(),
7204 C->getLParenLoc(), C->getLocEnd());
7207 //===----------------------------------------------------------------------===//
7208 // Expression transformation
7209 //===----------------------------------------------------------------------===//
7210 template<typename Derived>
7212 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
7213 if (!E->isTypeDependent())
7216 return getDerived().RebuildPredefinedExpr(E->getLocation(),
7220 template<typename Derived>
7222 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
7223 NestedNameSpecifierLoc QualifierLoc;
7224 if (E->getQualifierLoc()) {
7226 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7232 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
7237 DeclarationNameInfo NameInfo = E->getNameInfo();
7238 if (NameInfo.getName()) {
7239 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7240 if (!NameInfo.getName())
7244 if (!getDerived().AlwaysRebuild() &&
7245 QualifierLoc == E->getQualifierLoc() &&
7246 ND == E->getDecl() &&
7247 NameInfo.getName() == E->getDecl()->getDeclName() &&
7248 !E->hasExplicitTemplateArgs()) {
7250 // Mark it referenced in the new context regardless.
7251 // FIXME: this is a bit instantiation-specific.
7252 SemaRef.MarkDeclRefReferenced(E);
7257 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
7258 if (E->hasExplicitTemplateArgs()) {
7259 TemplateArgs = &TransArgs;
7260 TransArgs.setLAngleLoc(E->getLAngleLoc());
7261 TransArgs.setRAngleLoc(E->getRAngleLoc());
7262 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7263 E->getNumTemplateArgs(),
7268 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
7272 template<typename Derived>
7274 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
7278 template<typename Derived>
7280 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
7284 template<typename Derived>
7286 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
7290 template<typename Derived>
7292 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
7296 template<typename Derived>
7298 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
7302 template<typename Derived>
7304 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
7305 if (FunctionDecl *FD = E->getDirectCallee())
7306 SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
7307 return SemaRef.MaybeBindToTemporary(E);
7310 template<typename Derived>
7312 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
7313 ExprResult ControllingExpr =
7314 getDerived().TransformExpr(E->getControllingExpr());
7315 if (ControllingExpr.isInvalid())
7318 SmallVector<Expr *, 4> AssocExprs;
7319 SmallVector<TypeSourceInfo *, 4> AssocTypes;
7320 for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
7321 TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
7323 TypeSourceInfo *AssocType = getDerived().TransformType(TS);
7326 AssocTypes.push_back(AssocType);
7328 AssocTypes.push_back(nullptr);
7331 ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
7332 if (AssocExpr.isInvalid())
7334 AssocExprs.push_back(AssocExpr.get());
7337 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
7340 ControllingExpr.get(),
7345 template<typename Derived>
7347 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
7348 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
7349 if (SubExpr.isInvalid())
7352 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
7355 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
7359 /// \brief The operand of a unary address-of operator has special rules: it's
7360 /// allowed to refer to a non-static member of a class even if there's no 'this'
7361 /// object available.
7362 template<typename Derived>
7364 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
7365 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
7366 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
7368 return getDerived().TransformExpr(E);
7371 template<typename Derived>
7373 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
7375 if (E->getOpcode() == UO_AddrOf)
7376 SubExpr = TransformAddressOfOperand(E->getSubExpr());
7378 SubExpr = TransformExpr(E->getSubExpr());
7379 if (SubExpr.isInvalid())
7382 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
7385 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
7390 template<typename Derived>
7392 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
7393 // Transform the type.
7394 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
7398 // Transform all of the components into components similar to what the
7400 // FIXME: It would be slightly more efficient in the non-dependent case to
7401 // just map FieldDecls, rather than requiring the rebuilder to look for
7402 // the fields again. However, __builtin_offsetof is rare enough in
7403 // template code that we don't care.
7404 bool ExprChanged = false;
7405 typedef Sema::OffsetOfComponent Component;
7406 typedef OffsetOfExpr::OffsetOfNode Node;
7407 SmallVector<Component, 4> Components;
7408 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
7409 const Node &ON = E->getComponent(I);
7411 Comp.isBrackets = true;
7412 Comp.LocStart = ON.getSourceRange().getBegin();
7413 Comp.LocEnd = ON.getSourceRange().getEnd();
7414 switch (ON.getKind()) {
7416 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
7417 ExprResult Index = getDerived().TransformExpr(FromIndex);
7418 if (Index.isInvalid())
7421 ExprChanged = ExprChanged || Index.get() != FromIndex;
7422 Comp.isBrackets = true;
7423 Comp.U.E = Index.get();
7428 case Node::Identifier:
7429 Comp.isBrackets = false;
7430 Comp.U.IdentInfo = ON.getFieldName();
7431 if (!Comp.U.IdentInfo)
7437 // Will be recomputed during the rebuild.
7441 Components.push_back(Comp);
7444 // If nothing changed, retain the existing expression.
7445 if (!getDerived().AlwaysRebuild() &&
7446 Type == E->getTypeSourceInfo() &&
7450 // Build a new offsetof expression.
7451 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
7452 Components.data(), Components.size(),
7456 template<typename Derived>
7458 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
7459 assert(getDerived().AlreadyTransformed(E->getType()) &&
7460 "opaque value expression requires transformation");
7464 template<typename Derived>
7466 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
7470 template<typename Derived>
7472 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
7473 // Rebuild the syntactic form. The original syntactic form has
7474 // opaque-value expressions in it, so strip those away and rebuild
7475 // the result. This is a really awful way of doing this, but the
7476 // better solution (rebuilding the semantic expressions and
7477 // rebinding OVEs as necessary) doesn't work; we'd need
7478 // TreeTransform to not strip away implicit conversions.
7479 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
7480 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
7481 if (result.isInvalid()) return ExprError();
7483 // If that gives us a pseudo-object result back, the pseudo-object
7484 // expression must have been an lvalue-to-rvalue conversion which we
7486 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
7487 result = SemaRef.checkPseudoObjectRValue(result.get());
7492 template<typename Derived>
7494 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
7495 UnaryExprOrTypeTraitExpr *E) {
7496 if (E->isArgumentType()) {
7497 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
7499 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
7503 if (!getDerived().AlwaysRebuild() && OldT == NewT)
7506 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
7508 E->getSourceRange());
7511 // C++0x [expr.sizeof]p1:
7512 // The operand is either an expression, which is an unevaluated operand
7514 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
7515 Sema::ReuseLambdaContextDecl);
7517 // Try to recover if we have something like sizeof(T::X) where X is a type.
7518 // Notably, there must be *exactly* one set of parens if X is a type.
7519 TypeSourceInfo *RecoveryTSI = nullptr;
7521 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
7523 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
7524 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
7525 PE, DRE, false, &RecoveryTSI);
7527 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
7530 return getDerived().RebuildUnaryExprOrTypeTrait(
7531 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
7532 } else if (SubExpr.isInvalid())
7535 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
7538 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
7539 E->getOperatorLoc(),
7541 E->getSourceRange());
7544 template<typename Derived>
7546 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
7547 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7548 if (LHS.isInvalid())
7551 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7552 if (RHS.isInvalid())
7556 if (!getDerived().AlwaysRebuild() &&
7557 LHS.get() == E->getLHS() &&
7558 RHS.get() == E->getRHS())
7561 return getDerived().RebuildArraySubscriptExpr(LHS.get(),
7562 /*FIXME:*/E->getLHS()->getLocStart(),
7564 E->getRBracketLoc());
7567 template<typename Derived>
7569 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
7570 // Transform the callee.
7571 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
7572 if (Callee.isInvalid())
7575 // Transform arguments.
7576 bool ArgChanged = false;
7577 SmallVector<Expr*, 8> Args;
7578 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
7582 if (!getDerived().AlwaysRebuild() &&
7583 Callee.get() == E->getCallee() &&
7585 return SemaRef.MaybeBindToTemporary(E);
7587 // FIXME: Wrong source location information for the '('.
7588 SourceLocation FakeLParenLoc
7589 = ((Expr *)Callee.get())->getSourceRange().getBegin();
7590 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
7595 template<typename Derived>
7597 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
7598 ExprResult Base = getDerived().TransformExpr(E->getBase());
7599 if (Base.isInvalid())
7602 NestedNameSpecifierLoc QualifierLoc;
7603 if (E->hasQualifier()) {
7605 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7610 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
7613 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
7614 E->getMemberDecl()));
7618 NamedDecl *FoundDecl = E->getFoundDecl();
7619 if (FoundDecl == E->getMemberDecl()) {
7622 FoundDecl = cast_or_null<NamedDecl>(
7623 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
7628 if (!getDerived().AlwaysRebuild() &&
7629 Base.get() == E->getBase() &&
7630 QualifierLoc == E->getQualifierLoc() &&
7631 Member == E->getMemberDecl() &&
7632 FoundDecl == E->getFoundDecl() &&
7633 !E->hasExplicitTemplateArgs()) {
7635 // Mark it referenced in the new context regardless.
7636 // FIXME: this is a bit instantiation-specific.
7637 SemaRef.MarkMemberReferenced(E);
7642 TemplateArgumentListInfo TransArgs;
7643 if (E->hasExplicitTemplateArgs()) {
7644 TransArgs.setLAngleLoc(E->getLAngleLoc());
7645 TransArgs.setRAngleLoc(E->getRAngleLoc());
7646 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7647 E->getNumTemplateArgs(),
7652 // FIXME: Bogus source location for the operator
7653 SourceLocation FakeOperatorLoc =
7654 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
7656 // FIXME: to do this check properly, we will need to preserve the
7657 // first-qualifier-in-scope here, just in case we had a dependent
7658 // base (and therefore couldn't do the check) and a
7659 // nested-name-qualifier (and therefore could do the lookup).
7660 NamedDecl *FirstQualifierInScope = nullptr;
7662 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
7666 E->getMemberNameInfo(),
7669 (E->hasExplicitTemplateArgs()
7670 ? &TransArgs : nullptr),
7671 FirstQualifierInScope);
7674 template<typename Derived>
7676 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
7677 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7678 if (LHS.isInvalid())
7681 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7682 if (RHS.isInvalid())
7685 if (!getDerived().AlwaysRebuild() &&
7686 LHS.get() == E->getLHS() &&
7687 RHS.get() == E->getRHS())
7690 Sema::FPContractStateRAII FPContractState(getSema());
7691 getSema().FPFeatures.fp_contract = E->isFPContractable();
7693 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
7694 LHS.get(), RHS.get());
7697 template<typename Derived>
7699 TreeTransform<Derived>::TransformCompoundAssignOperator(
7700 CompoundAssignOperator *E) {
7701 return getDerived().TransformBinaryOperator(E);
7704 template<typename Derived>
7705 ExprResult TreeTransform<Derived>::
7706 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
7707 // Just rebuild the common and RHS expressions and see whether we
7710 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
7711 if (commonExpr.isInvalid())
7714 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
7715 if (rhs.isInvalid())
7718 if (!getDerived().AlwaysRebuild() &&
7719 commonExpr.get() == e->getCommon() &&
7720 rhs.get() == e->getFalseExpr())
7723 return getDerived().RebuildConditionalOperator(commonExpr.get(),
7724 e->getQuestionLoc(),
7730 template<typename Derived>
7732 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
7733 ExprResult Cond = getDerived().TransformExpr(E->getCond());
7734 if (Cond.isInvalid())
7737 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7738 if (LHS.isInvalid())
7741 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7742 if (RHS.isInvalid())
7745 if (!getDerived().AlwaysRebuild() &&
7746 Cond.get() == E->getCond() &&
7747 LHS.get() == E->getLHS() &&
7748 RHS.get() == E->getRHS())
7751 return getDerived().RebuildConditionalOperator(Cond.get(),
7752 E->getQuestionLoc(),
7758 template<typename Derived>
7760 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
7761 // Implicit casts are eliminated during transformation, since they
7762 // will be recomputed by semantic analysis after transformation.
7763 return getDerived().TransformExpr(E->getSubExprAsWritten());
7766 template<typename Derived>
7768 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
7769 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
7774 = getDerived().TransformExpr(E->getSubExprAsWritten());
7775 if (SubExpr.isInvalid())
7778 if (!getDerived().AlwaysRebuild() &&
7779 Type == E->getTypeInfoAsWritten() &&
7780 SubExpr.get() == E->getSubExpr())
7783 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
7789 template<typename Derived>
7791 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
7792 TypeSourceInfo *OldT = E->getTypeSourceInfo();
7793 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
7797 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
7798 if (Init.isInvalid())
7801 if (!getDerived().AlwaysRebuild() &&
7803 Init.get() == E->getInitializer())
7804 return SemaRef.MaybeBindToTemporary(E);
7806 // Note: the expression type doesn't necessarily match the
7807 // type-as-written, but that's okay, because it should always be
7808 // derivable from the initializer.
7810 return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
7811 /*FIXME:*/E->getInitializer()->getLocEnd(),
7815 template<typename Derived>
7817 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
7818 ExprResult Base = getDerived().TransformExpr(E->getBase());
7819 if (Base.isInvalid())
7822 if (!getDerived().AlwaysRebuild() &&
7823 Base.get() == E->getBase())
7826 // FIXME: Bad source location
7827 SourceLocation FakeOperatorLoc =
7828 SemaRef.getLocForEndOfToken(E->getBase()->getLocEnd());
7829 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
7830 E->getAccessorLoc(),
7834 template<typename Derived>
7836 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
7837 bool InitChanged = false;
7839 SmallVector<Expr*, 4> Inits;
7840 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
7841 Inits, &InitChanged))
7844 if (!getDerived().AlwaysRebuild() && !InitChanged)
7847 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
7848 E->getRBraceLoc(), E->getType());
7851 template<typename Derived>
7853 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
7856 // transform the initializer value
7857 ExprResult Init = getDerived().TransformExpr(E->getInit());
7858 if (Init.isInvalid())
7861 // transform the designators.
7862 SmallVector<Expr*, 4> ArrayExprs;
7863 bool ExprChanged = false;
7864 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
7865 DEnd = E->designators_end();
7867 if (D->isFieldDesignator()) {
7868 Desig.AddDesignator(Designator::getField(D->getFieldName(),
7874 if (D->isArrayDesignator()) {
7875 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
7876 if (Index.isInvalid())
7879 Desig.AddDesignator(Designator::getArray(Index.get(),
7880 D->getLBracketLoc()));
7882 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
7883 ArrayExprs.push_back(Index.get());
7887 assert(D->isArrayRangeDesignator() && "New kind of designator?");
7889 = getDerived().TransformExpr(E->getArrayRangeStart(*D));
7890 if (Start.isInvalid())
7893 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
7894 if (End.isInvalid())
7897 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
7899 D->getLBracketLoc(),
7900 D->getEllipsisLoc()));
7902 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
7903 End.get() != E->getArrayRangeEnd(*D);
7905 ArrayExprs.push_back(Start.get());
7906 ArrayExprs.push_back(End.get());
7909 if (!getDerived().AlwaysRebuild() &&
7910 Init.get() == E->getInit() &&
7914 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
7915 E->getEqualOrColonLoc(),
7916 E->usesGNUSyntax(), Init.get());
7919 template<typename Derived>
7921 TreeTransform<Derived>::TransformImplicitValueInitExpr(
7922 ImplicitValueInitExpr *E) {
7923 TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
7925 // FIXME: Will we ever have proper type location here? Will we actually
7926 // need to transform the type?
7927 QualType T = getDerived().TransformType(E->getType());
7931 if (!getDerived().AlwaysRebuild() &&
7935 return getDerived().RebuildImplicitValueInitExpr(T);
7938 template<typename Derived>
7940 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
7941 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
7945 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
7946 if (SubExpr.isInvalid())
7949 if (!getDerived().AlwaysRebuild() &&
7950 TInfo == E->getWrittenTypeInfo() &&
7951 SubExpr.get() == E->getSubExpr())
7954 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
7955 TInfo, E->getRParenLoc());
7958 template<typename Derived>
7960 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
7961 bool ArgumentChanged = false;
7962 SmallVector<Expr*, 4> Inits;
7963 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
7967 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
7972 /// \brief Transform an address-of-label expression.
7974 /// By default, the transformation of an address-of-label expression always
7975 /// rebuilds the expression, so that the label identifier can be resolved to
7976 /// the corresponding label statement by semantic analysis.
7977 template<typename Derived>
7979 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
7980 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
7985 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
7986 cast<LabelDecl>(LD));
7989 template<typename Derived>
7991 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
7992 SemaRef.ActOnStartStmtExpr();
7994 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
7995 if (SubStmt.isInvalid()) {
7996 SemaRef.ActOnStmtExprError();
8000 if (!getDerived().AlwaysRebuild() &&
8001 SubStmt.get() == E->getSubStmt()) {
8002 // Calling this an 'error' is unintuitive, but it does the right thing.
8003 SemaRef.ActOnStmtExprError();
8004 return SemaRef.MaybeBindToTemporary(E);
8007 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
8012 template<typename Derived>
8014 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
8015 ExprResult Cond = getDerived().TransformExpr(E->getCond());
8016 if (Cond.isInvalid())
8019 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
8020 if (LHS.isInvalid())
8023 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
8024 if (RHS.isInvalid())
8027 if (!getDerived().AlwaysRebuild() &&
8028 Cond.get() == E->getCond() &&
8029 LHS.get() == E->getLHS() &&
8030 RHS.get() == E->getRHS())
8033 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
8034 Cond.get(), LHS.get(), RHS.get(),
8038 template<typename Derived>
8040 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
8044 template<typename Derived>
8046 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8047 switch (E->getOperator()) {
8051 case OO_Array_Delete:
8052 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
8055 // This is a call to an object's operator().
8056 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
8058 // Transform the object itself.
8059 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
8060 if (Object.isInvalid())
8063 // FIXME: Poor location information
8064 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
8065 static_cast<Expr *>(Object.get())->getLocEnd());
8067 // Transform the call arguments.
8068 SmallVector<Expr*, 8> Args;
8069 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
8073 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
8078 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8080 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
8081 #include "clang/Basic/OperatorKinds.def"
8086 case OO_Conditional:
8087 llvm_unreachable("conditional operator is not actually overloadable");
8090 case NUM_OVERLOADED_OPERATORS:
8091 llvm_unreachable("not an overloaded operator?");
8094 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
8095 if (Callee.isInvalid())
8099 if (E->getOperator() == OO_Amp)
8100 First = getDerived().TransformAddressOfOperand(E->getArg(0));
8102 First = getDerived().TransformExpr(E->getArg(0));
8103 if (First.isInvalid())
8107 if (E->getNumArgs() == 2) {
8108 Second = getDerived().TransformExpr(E->getArg(1));
8109 if (Second.isInvalid())
8113 if (!getDerived().AlwaysRebuild() &&
8114 Callee.get() == E->getCallee() &&
8115 First.get() == E->getArg(0) &&
8116 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
8117 return SemaRef.MaybeBindToTemporary(E);
8119 Sema::FPContractStateRAII FPContractState(getSema());
8120 getSema().FPFeatures.fp_contract = E->isFPContractable();
8122 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
8123 E->getOperatorLoc(),
8129 template<typename Derived>
8131 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
8132 return getDerived().TransformCallExpr(E);
8135 template<typename Derived>
8137 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
8138 // Transform the callee.
8139 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
8140 if (Callee.isInvalid())
8143 // Transform exec config.
8144 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
8148 // Transform arguments.
8149 bool ArgChanged = false;
8150 SmallVector<Expr*, 8> Args;
8151 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
8155 if (!getDerived().AlwaysRebuild() &&
8156 Callee.get() == E->getCallee() &&
8158 return SemaRef.MaybeBindToTemporary(E);
8160 // FIXME: Wrong source location information for the '('.
8161 SourceLocation FakeLParenLoc
8162 = ((Expr *)Callee.get())->getSourceRange().getBegin();
8163 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
8165 E->getRParenLoc(), EC.get());
8168 template<typename Derived>
8170 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
8171 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
8176 = getDerived().TransformExpr(E->getSubExprAsWritten());
8177 if (SubExpr.isInvalid())
8180 if (!getDerived().AlwaysRebuild() &&
8181 Type == E->getTypeInfoAsWritten() &&
8182 SubExpr.get() == E->getSubExpr())
8184 return getDerived().RebuildCXXNamedCastExpr(
8185 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
8186 Type, E->getAngleBrackets().getEnd(),
8187 // FIXME. this should be '(' location
8188 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
8191 template<typename Derived>
8193 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
8194 return getDerived().TransformCXXNamedCastExpr(E);
8197 template<typename Derived>
8199 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
8200 return getDerived().TransformCXXNamedCastExpr(E);
8203 template<typename Derived>
8205 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
8206 CXXReinterpretCastExpr *E) {
8207 return getDerived().TransformCXXNamedCastExpr(E);
8210 template<typename Derived>
8212 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
8213 return getDerived().TransformCXXNamedCastExpr(E);
8216 template<typename Derived>
8218 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
8219 CXXFunctionalCastExpr *E) {
8220 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
8225 = getDerived().TransformExpr(E->getSubExprAsWritten());
8226 if (SubExpr.isInvalid())
8229 if (!getDerived().AlwaysRebuild() &&
8230 Type == E->getTypeInfoAsWritten() &&
8231 SubExpr.get() == E->getSubExpr())
8234 return getDerived().RebuildCXXFunctionalCastExpr(Type,
8240 template<typename Derived>
8242 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
8243 if (E->isTypeOperand()) {
8244 TypeSourceInfo *TInfo
8245 = getDerived().TransformType(E->getTypeOperandSourceInfo());
8249 if (!getDerived().AlwaysRebuild() &&
8250 TInfo == E->getTypeOperandSourceInfo())
8253 return getDerived().RebuildCXXTypeidExpr(E->getType(),
8259 // We don't know whether the subexpression is potentially evaluated until
8260 // after we perform semantic analysis. We speculatively assume it is
8261 // unevaluated; it will get fixed later if the subexpression is in fact
8262 // potentially evaluated.
8263 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
8264 Sema::ReuseLambdaContextDecl);
8266 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
8267 if (SubExpr.isInvalid())
8270 if (!getDerived().AlwaysRebuild() &&
8271 SubExpr.get() == E->getExprOperand())
8274 return getDerived().RebuildCXXTypeidExpr(E->getType(),
8280 template<typename Derived>
8282 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
8283 if (E->isTypeOperand()) {
8284 TypeSourceInfo *TInfo
8285 = getDerived().TransformType(E->getTypeOperandSourceInfo());
8289 if (!getDerived().AlwaysRebuild() &&
8290 TInfo == E->getTypeOperandSourceInfo())
8293 return getDerived().RebuildCXXUuidofExpr(E->getType(),
8299 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8301 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
8302 if (SubExpr.isInvalid())
8305 if (!getDerived().AlwaysRebuild() &&
8306 SubExpr.get() == E->getExprOperand())
8309 return getDerived().RebuildCXXUuidofExpr(E->getType(),
8315 template<typename Derived>
8317 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
8321 template<typename Derived>
8323 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
8324 CXXNullPtrLiteralExpr *E) {
8328 template<typename Derived>
8330 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
8331 QualType T = getSema().getCurrentThisType();
8333 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
8334 // Make sure that we capture 'this'.
8335 getSema().CheckCXXThisCapture(E->getLocStart());
8339 return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
8342 template<typename Derived>
8344 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
8345 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8346 if (SubExpr.isInvalid())
8349 if (!getDerived().AlwaysRebuild() &&
8350 SubExpr.get() == E->getSubExpr())
8353 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
8354 E->isThrownVariableInScope());
8357 template<typename Derived>
8359 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
8361 = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
8366 if (!getDerived().AlwaysRebuild() &&
8367 Param == E->getParam())
8370 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
8373 template<typename Derived>
8375 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
8377 = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
8382 if (!getDerived().AlwaysRebuild() && Field == E->getField())
8385 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
8388 template<typename Derived>
8390 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
8391 CXXScalarValueInitExpr *E) {
8392 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
8396 if (!getDerived().AlwaysRebuild() &&
8397 T == E->getTypeSourceInfo())
8400 return getDerived().RebuildCXXScalarValueInitExpr(T,
8401 /*FIXME:*/T->getTypeLoc().getEndLoc(),
8405 template<typename Derived>
8407 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
8408 // Transform the type that we're allocating
8409 TypeSourceInfo *AllocTypeInfo
8410 = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
8414 // Transform the size of the array we're allocating (if any).
8415 ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
8416 if (ArraySize.isInvalid())
8419 // Transform the placement arguments (if any).
8420 bool ArgumentChanged = false;
8421 SmallVector<Expr*, 8> PlacementArgs;
8422 if (getDerived().TransformExprs(E->getPlacementArgs(),
8423 E->getNumPlacementArgs(), true,
8424 PlacementArgs, &ArgumentChanged))
8427 // Transform the initializer (if any).
8428 Expr *OldInit = E->getInitializer();
8431 NewInit = getDerived().TransformInitializer(OldInit, true);
8432 if (NewInit.isInvalid())
8435 // Transform new operator and delete operator.
8436 FunctionDecl *OperatorNew = nullptr;
8437 if (E->getOperatorNew()) {
8438 OperatorNew = cast_or_null<FunctionDecl>(
8439 getDerived().TransformDecl(E->getLocStart(),
8440 E->getOperatorNew()));
8445 FunctionDecl *OperatorDelete = nullptr;
8446 if (E->getOperatorDelete()) {
8447 OperatorDelete = cast_or_null<FunctionDecl>(
8448 getDerived().TransformDecl(E->getLocStart(),
8449 E->getOperatorDelete()));
8450 if (!OperatorDelete)
8454 if (!getDerived().AlwaysRebuild() &&
8455 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
8456 ArraySize.get() == E->getArraySize() &&
8457 NewInit.get() == OldInit &&
8458 OperatorNew == E->getOperatorNew() &&
8459 OperatorDelete == E->getOperatorDelete() &&
8461 // Mark any declarations we need as referenced.
8462 // FIXME: instantiation-specific.
8464 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
8466 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
8468 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
8469 QualType ElementType
8470 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
8471 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
8472 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
8473 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
8474 SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
8482 QualType AllocType = AllocTypeInfo->getType();
8483 if (!ArraySize.get()) {
8484 // If no array size was specified, but the new expression was
8485 // instantiated with an array type (e.g., "new T" where T is
8486 // instantiated with "int[4]"), extract the outer bound from the
8487 // array type as our array size. We do this with constant and
8488 // dependently-sized array types.
8489 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
8492 } else if (const ConstantArrayType *ConsArrayT
8493 = dyn_cast<ConstantArrayType>(ArrayT)) {
8494 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
8495 SemaRef.Context.getSizeType(),
8496 /*FIXME:*/ E->getLocStart());
8497 AllocType = ConsArrayT->getElementType();
8498 } else if (const DependentSizedArrayType *DepArrayT
8499 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
8500 if (DepArrayT->getSizeExpr()) {
8501 ArraySize = DepArrayT->getSizeExpr();
8502 AllocType = DepArrayT->getElementType();
8507 return getDerived().RebuildCXXNewExpr(E->getLocStart(),
8509 /*FIXME:*/E->getLocStart(),
8511 /*FIXME:*/E->getLocStart(),
8512 E->getTypeIdParens(),
8516 E->getDirectInitRange(),
8520 template<typename Derived>
8522 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
8523 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
8524 if (Operand.isInvalid())
8527 // Transform the delete operator, if known.
8528 FunctionDecl *OperatorDelete = nullptr;
8529 if (E->getOperatorDelete()) {
8530 OperatorDelete = cast_or_null<FunctionDecl>(
8531 getDerived().TransformDecl(E->getLocStart(),
8532 E->getOperatorDelete()));
8533 if (!OperatorDelete)
8537 if (!getDerived().AlwaysRebuild() &&
8538 Operand.get() == E->getArgument() &&
8539 OperatorDelete == E->getOperatorDelete()) {
8540 // Mark any declarations we need as referenced.
8541 // FIXME: instantiation-specific.
8543 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
8545 if (!E->getArgument()->isTypeDependent()) {
8546 QualType Destroyed = SemaRef.Context.getBaseElementType(
8547 E->getDestroyedType());
8548 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
8549 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
8550 SemaRef.MarkFunctionReferenced(E->getLocStart(),
8551 SemaRef.LookupDestructor(Record));
8558 return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
8559 E->isGlobalDelete(),
8564 template<typename Derived>
8566 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
8567 CXXPseudoDestructorExpr *E) {
8568 ExprResult Base = getDerived().TransformExpr(E->getBase());
8569 if (Base.isInvalid())
8572 ParsedType ObjectTypePtr;
8573 bool MayBePseudoDestructor = false;
8574 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
8575 E->getOperatorLoc(),
8576 E->isArrow()? tok::arrow : tok::period,
8578 MayBePseudoDestructor);
8579 if (Base.isInvalid())
8582 QualType ObjectType = ObjectTypePtr.get();
8583 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
8586 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
8591 SS.Adopt(QualifierLoc);
8593 PseudoDestructorTypeStorage Destroyed;
8594 if (E->getDestroyedTypeInfo()) {
8595 TypeSourceInfo *DestroyedTypeInfo
8596 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
8597 ObjectType, nullptr, SS);
8598 if (!DestroyedTypeInfo)
8600 Destroyed = DestroyedTypeInfo;
8601 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
8602 // We aren't likely to be able to resolve the identifier down to a type
8603 // now anyway, so just retain the identifier.
8604 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
8605 E->getDestroyedTypeLoc());
8607 // Look for a destructor known with the given name.
8608 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
8609 *E->getDestroyedTypeIdentifier(),
8610 E->getDestroyedTypeLoc(),
8618 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
8619 E->getDestroyedTypeLoc());
8622 TypeSourceInfo *ScopeTypeInfo = nullptr;
8623 if (E->getScopeTypeInfo()) {
8624 CXXScopeSpec EmptySS;
8625 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
8626 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
8631 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
8632 E->getOperatorLoc(),
8636 E->getColonColonLoc(),
8641 template<typename Derived>
8643 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
8644 UnresolvedLookupExpr *Old) {
8645 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
8646 Sema::LookupOrdinaryName);
8648 // Transform all the decls.
8649 for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
8650 E = Old->decls_end(); I != E; ++I) {
8651 NamedDecl *InstD = static_cast<NamedDecl*>(
8652 getDerived().TransformDecl(Old->getNameLoc(),
8655 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
8656 // This can happen because of dependent hiding.
8657 if (isa<UsingShadowDecl>(*I))
8665 // Expand using declarations.
8666 if (isa<UsingDecl>(InstD)) {
8667 UsingDecl *UD = cast<UsingDecl>(InstD);
8668 for (auto *I : UD->shadows())
8676 // Resolve a kind, but don't do any further analysis. If it's
8677 // ambiguous, the callee needs to deal with it.
8680 // Rebuild the nested-name qualifier, if present.
8682 if (Old->getQualifierLoc()) {
8683 NestedNameSpecifierLoc QualifierLoc
8684 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
8688 SS.Adopt(QualifierLoc);
8691 if (Old->getNamingClass()) {
8692 CXXRecordDecl *NamingClass
8693 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
8695 Old->getNamingClass()));
8701 R.setNamingClass(NamingClass);
8704 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
8706 // If we have neither explicit template arguments, nor the template keyword,
8707 // it's a normal declaration name.
8708 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid())
8709 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
8711 // If we have template arguments, rebuild them, then rebuild the
8712 // templateid expression.
8713 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
8714 if (Old->hasExplicitTemplateArgs() &&
8715 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
8716 Old->getNumTemplateArgs(),
8722 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
8723 Old->requiresADL(), &TransArgs);
8726 template<typename Derived>
8728 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
8729 bool ArgChanged = false;
8730 SmallVector<TypeSourceInfo *, 4> Args;
8731 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
8732 TypeSourceInfo *From = E->getArg(I);
8733 TypeLoc FromTL = From->getTypeLoc();
8734 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
8736 TLB.reserve(FromTL.getFullDataSize());
8737 QualType To = getDerived().TransformType(TLB, FromTL);
8741 if (To == From->getType())
8742 Args.push_back(From);
8744 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8752 // We have a pack expansion. Instantiate it.
8753 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
8754 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
8755 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
8756 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
8758 // Determine whether the set of unexpanded parameter packs can and should
8761 bool RetainExpansion = false;
8762 Optional<unsigned> OrigNumExpansions =
8763 ExpansionTL.getTypePtr()->getNumExpansions();
8764 Optional<unsigned> NumExpansions = OrigNumExpansions;
8765 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
8766 PatternTL.getSourceRange(),
8768 Expand, RetainExpansion,
8773 // The transform has determined that we should perform a simple
8774 // transformation on the pack expansion, producing another pack
8776 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
8779 TLB.reserve(From->getTypeLoc().getFullDataSize());
8781 QualType To = getDerived().TransformType(TLB, PatternTL);
8785 To = getDerived().RebuildPackExpansionType(To,
8786 PatternTL.getSourceRange(),
8787 ExpansionTL.getEllipsisLoc(),
8792 PackExpansionTypeLoc ToExpansionTL
8793 = TLB.push<PackExpansionTypeLoc>(To);
8794 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
8795 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8799 // Expand the pack expansion by substituting for each argument in the
8801 for (unsigned I = 0; I != *NumExpansions; ++I) {
8802 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
8804 TLB.reserve(PatternTL.getFullDataSize());
8805 QualType To = getDerived().TransformType(TLB, PatternTL);
8809 if (To->containsUnexpandedParameterPack()) {
8810 To = getDerived().RebuildPackExpansionType(To,
8811 PatternTL.getSourceRange(),
8812 ExpansionTL.getEllipsisLoc(),
8817 PackExpansionTypeLoc ToExpansionTL
8818 = TLB.push<PackExpansionTypeLoc>(To);
8819 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
8822 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8825 if (!RetainExpansion)
8828 // If we're supposed to retain a pack expansion, do so by temporarily
8829 // forgetting the partially-substituted parameter pack.
8830 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
8833 TLB.reserve(From->getTypeLoc().getFullDataSize());
8835 QualType To = getDerived().TransformType(TLB, PatternTL);
8839 To = getDerived().RebuildPackExpansionType(To,
8840 PatternTL.getSourceRange(),
8841 ExpansionTL.getEllipsisLoc(),
8846 PackExpansionTypeLoc ToExpansionTL
8847 = TLB.push<PackExpansionTypeLoc>(To);
8848 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
8849 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8852 if (!getDerived().AlwaysRebuild() && !ArgChanged)
8855 return getDerived().RebuildTypeTrait(E->getTrait(),
8861 template<typename Derived>
8863 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
8864 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
8868 if (!getDerived().AlwaysRebuild() &&
8869 T == E->getQueriedTypeSourceInfo())
8874 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8875 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
8876 if (SubExpr.isInvalid())
8879 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
8883 return getDerived().RebuildArrayTypeTrait(E->getTrait(),
8890 template<typename Derived>
8892 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
8895 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8896 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
8897 if (SubExpr.isInvalid())
8900 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
8904 return getDerived().RebuildExpressionTrait(
8905 E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
8908 template <typename Derived>
8909 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
8910 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
8911 TypeSourceInfo **RecoveryTSI) {
8912 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
8913 DRE, AddrTaken, RecoveryTSI);
8915 // Propagate both errors and recovered types, which return ExprEmpty.
8916 if (!NewDRE.isUsable())
8919 // We got an expr, wrap it up in parens.
8920 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
8922 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
8926 template <typename Derived>
8927 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
8928 DependentScopeDeclRefExpr *E) {
8929 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
8933 template<typename Derived>
8935 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
8936 DependentScopeDeclRefExpr *E,
8937 bool IsAddressOfOperand,
8938 TypeSourceInfo **RecoveryTSI) {
8939 assert(E->getQualifierLoc());
8940 NestedNameSpecifierLoc QualifierLoc
8941 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8944 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
8946 // TODO: If this is a conversion-function-id, verify that the
8947 // destination type name (if present) resolves the same way after
8948 // instantiation as it did in the local scope.
8950 DeclarationNameInfo NameInfo
8951 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
8952 if (!NameInfo.getName())
8955 if (!E->hasExplicitTemplateArgs()) {
8956 if (!getDerived().AlwaysRebuild() &&
8957 QualifierLoc == E->getQualifierLoc() &&
8958 // Note: it is sufficient to compare the Name component of NameInfo:
8959 // if name has not changed, DNLoc has not changed either.
8960 NameInfo.getName() == E->getDeclName())
8963 return getDerived().RebuildDependentScopeDeclRefExpr(
8964 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
8965 IsAddressOfOperand, RecoveryTSI);
8968 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
8969 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
8970 E->getNumTemplateArgs(),
8974 return getDerived().RebuildDependentScopeDeclRefExpr(
8975 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
8979 template<typename Derived>
8981 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
8982 // CXXConstructExprs other than for list-initialization and
8983 // CXXTemporaryObjectExpr are always implicit, so when we have
8984 // a 1-argument construction we just transform that argument.
8985 if ((E->getNumArgs() == 1 ||
8986 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
8987 (!getDerived().DropCallArgument(E->getArg(0))) &&
8988 !E->isListInitialization())
8989 return getDerived().TransformExpr(E->getArg(0));
8991 TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
8993 QualType T = getDerived().TransformType(E->getType());
8997 CXXConstructorDecl *Constructor
8998 = cast_or_null<CXXConstructorDecl>(
8999 getDerived().TransformDecl(E->getLocStart(),
9000 E->getConstructor()));
9004 bool ArgumentChanged = false;
9005 SmallVector<Expr*, 8> Args;
9006 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9010 if (!getDerived().AlwaysRebuild() &&
9011 T == E->getType() &&
9012 Constructor == E->getConstructor() &&
9014 // Mark the constructor as referenced.
9015 // FIXME: Instantiation-specific
9016 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
9020 return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
9021 Constructor, E->isElidable(),
9023 E->hadMultipleCandidates(),
9024 E->isListInitialization(),
9025 E->isStdInitListInitialization(),
9026 E->requiresZeroInitialization(),
9027 E->getConstructionKind(),
9028 E->getParenOrBraceRange());
9031 /// \brief Transform a C++ temporary-binding expression.
9033 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
9034 /// transform the subexpression and return that.
9035 template<typename Derived>
9037 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
9038 return getDerived().TransformExpr(E->getSubExpr());
9041 /// \brief Transform a C++ expression that contains cleanups that should
9042 /// be run after the expression is evaluated.
9044 /// Since ExprWithCleanups nodes are implicitly generated, we
9045 /// just transform the subexpression and return that.
9046 template<typename Derived>
9048 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
9049 return getDerived().TransformExpr(E->getSubExpr());
9052 template<typename Derived>
9054 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
9055 CXXTemporaryObjectExpr *E) {
9056 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9060 CXXConstructorDecl *Constructor
9061 = cast_or_null<CXXConstructorDecl>(
9062 getDerived().TransformDecl(E->getLocStart(),
9063 E->getConstructor()));
9067 bool ArgumentChanged = false;
9068 SmallVector<Expr*, 8> Args;
9069 Args.reserve(E->getNumArgs());
9070 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9074 if (!getDerived().AlwaysRebuild() &&
9075 T == E->getTypeSourceInfo() &&
9076 Constructor == E->getConstructor() &&
9078 // FIXME: Instantiation-specific
9079 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
9080 return SemaRef.MaybeBindToTemporary(E);
9083 // FIXME: Pass in E->isListInitialization().
9084 return getDerived().RebuildCXXTemporaryObjectExpr(T,
9085 /*FIXME:*/T->getTypeLoc().getEndLoc(),
9090 template<typename Derived>
9092 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
9093 // Transform any init-capture expressions before entering the scope of the
9094 // lambda body, because they are not semantically within that scope.
9095 SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
9096 InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
9097 E->explicit_capture_begin());
9098 for (LambdaExpr::capture_iterator C = E->capture_begin(),
9099 CEnd = E->capture_end();
9101 if (!C->isInitCapture())
9103 EnterExpressionEvaluationContext EEEC(getSema(),
9104 Sema::PotentiallyEvaluated);
9105 ExprResult NewExprInitResult = getDerived().TransformInitializer(
9106 C->getCapturedVar()->getInit(),
9107 C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
9109 if (NewExprInitResult.isInvalid())
9111 Expr *NewExprInit = NewExprInitResult.get();
9113 VarDecl *OldVD = C->getCapturedVar();
9114 QualType NewInitCaptureType =
9115 getSema().performLambdaInitCaptureInitialization(C->getLocation(),
9116 OldVD->getType()->isReferenceType(), OldVD->getIdentifier(),
9118 NewExprInitResult = NewExprInit;
9119 InitCaptureExprsAndTypes[C - E->capture_begin()] =
9120 std::make_pair(NewExprInitResult, NewInitCaptureType);
9123 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
9124 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
9126 // Transform the template parameters, and add them to the current
9127 // instantiation scope. The null case is handled correctly.
9128 LSI->GLTemplateParameterList = getDerived().TransformTemplateParameterList(
9129 E->getTemplateParameterList());
9131 // Transform the type of the original lambda's call operator.
9132 // The transformation MUST be done in the CurrentInstantiationScope since
9133 // it introduces a mapping of the original to the newly created
9134 // transformed parameters.
9135 TypeSourceInfo *NewCallOpTSI = nullptr;
9137 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
9138 FunctionProtoTypeLoc OldCallOpFPTL =
9139 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
9141 TypeLocBuilder NewCallOpTLBuilder;
9142 SmallVector<QualType, 4> ExceptionStorage;
9143 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
9144 QualType NewCallOpType = TransformFunctionProtoType(
9145 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, 0,
9146 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
9147 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
9148 ExceptionStorage, Changed);
9150 if (NewCallOpType.isNull())
9152 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
9156 // Create the local class that will describe the lambda.
9157 CXXRecordDecl *Class
9158 = getSema().createLambdaClosureType(E->getIntroducerRange(),
9160 /*KnownDependent=*/false,
9161 E->getCaptureDefault());
9162 getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
9164 // Build the call operator.
9165 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
9166 Class, E->getIntroducerRange(), NewCallOpTSI,
9167 E->getCallOperator()->getLocEnd(),
9168 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams());
9169 LSI->CallOperator = NewCallOperator;
9171 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
9173 // TransformLambdaScope will manage the function scope, so we can disable the
9175 FuncScopeCleanup.disable();
9177 return getDerived().TransformLambdaScope(E, NewCallOperator,
9178 InitCaptureExprsAndTypes);
9181 template<typename Derived>
9183 TreeTransform<Derived>::TransformLambdaScope(LambdaExpr *E,
9184 CXXMethodDecl *CallOperator,
9185 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
9186 bool Invalid = false;
9188 // Introduce the context of the call operator.
9189 Sema::ContextRAII SavedContext(getSema(), CallOperator,
9190 /*NewThisContext*/false);
9192 LambdaScopeInfo *const LSI = getSema().getCurLambda();
9193 // Enter the scope of the lambda.
9194 getSema().buildLambdaScope(LSI, CallOperator, E->getIntroducerRange(),
9195 E->getCaptureDefault(),
9196 E->getCaptureDefaultLoc(),
9197 E->hasExplicitParameters(),
9198 E->hasExplicitResultType(),
9201 // Transform captures.
9202 bool FinishedExplicitCaptures = false;
9203 for (LambdaExpr::capture_iterator C = E->capture_begin(),
9204 CEnd = E->capture_end();
9206 // When we hit the first implicit capture, tell Sema that we've finished
9207 // the list of explicit captures.
9208 if (!FinishedExplicitCaptures && C->isImplicit()) {
9209 getSema().finishLambdaExplicitCaptures(LSI);
9210 FinishedExplicitCaptures = true;
9213 // Capturing 'this' is trivial.
9214 if (C->capturesThis()) {
9215 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
9218 // Captured expression will be recaptured during captured variables
9220 if (C->capturesVLAType())
9223 // Rebuild init-captures, including the implied field declaration.
9224 if (C->isInitCapture()) {
9226 InitCaptureInfoTy InitExprTypePair =
9227 InitCaptureExprsAndTypes[C - E->capture_begin()];
9228 ExprResult Init = InitExprTypePair.first;
9229 QualType InitQualType = InitExprTypePair.second;
9230 if (Init.isInvalid() || InitQualType.isNull()) {
9234 VarDecl *OldVD = C->getCapturedVar();
9235 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
9236 OldVD->getLocation(), InitExprTypePair.second,
9237 OldVD->getIdentifier(), Init.get());
9241 getDerived().transformedLocalDecl(OldVD, NewVD);
9243 getSema().buildInitCaptureField(LSI, NewVD);
9247 assert(C->capturesVariable() && "unexpected kind of lambda capture");
9249 // Determine the capture kind for Sema.
9250 Sema::TryCaptureKind Kind
9251 = C->isImplicit()? Sema::TryCapture_Implicit
9252 : C->getCaptureKind() == LCK_ByCopy
9253 ? Sema::TryCapture_ExplicitByVal
9254 : Sema::TryCapture_ExplicitByRef;
9255 SourceLocation EllipsisLoc;
9256 if (C->isPackExpansion()) {
9257 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
9258 bool ShouldExpand = false;
9259 bool RetainExpansion = false;
9260 Optional<unsigned> NumExpansions;
9261 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
9264 ShouldExpand, RetainExpansion,
9271 // The transform has determined that we should perform an expansion;
9272 // transform and capture each of the arguments.
9273 // expansion of the pattern. Do so.
9274 VarDecl *Pack = C->getCapturedVar();
9275 for (unsigned I = 0; I != *NumExpansions; ++I) {
9276 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
9277 VarDecl *CapturedVar
9278 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
9285 // Capture the transformed variable.
9286 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
9289 // FIXME: Retain a pack expansion if RetainExpansion is true.
9294 EllipsisLoc = C->getEllipsisLoc();
9297 // Transform the captured variable.
9298 VarDecl *CapturedVar
9299 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
9300 C->getCapturedVar()));
9301 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
9306 // Capture the transformed variable.
9307 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
9309 if (!FinishedExplicitCaptures)
9310 getSema().finishLambdaExplicitCaptures(LSI);
9313 // Enter a new evaluation context to insulate the lambda from any
9314 // cleanups from the enclosing full-expression.
9315 getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
9318 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
9319 /*IsInstantiation=*/true);
9323 // Instantiate the body of the lambda expression.
9324 StmtResult Body = getDerived().TransformStmt(E->getBody());
9325 if (Body.isInvalid()) {
9326 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
9327 /*IsInstantiation=*/true);
9331 return getSema().ActOnLambdaExpr(E->getLocStart(), Body.get(),
9332 /*CurScope=*/nullptr,
9333 /*IsInstantiation=*/true);
9336 template<typename Derived>
9338 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
9339 CXXUnresolvedConstructExpr *E) {
9340 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9344 bool ArgumentChanged = false;
9345 SmallVector<Expr*, 8> Args;
9346 Args.reserve(E->arg_size());
9347 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
9351 if (!getDerived().AlwaysRebuild() &&
9352 T == E->getTypeSourceInfo() &&
9356 // FIXME: we're faking the locations of the commas
9357 return getDerived().RebuildCXXUnresolvedConstructExpr(T,
9363 template<typename Derived>
9365 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
9366 CXXDependentScopeMemberExpr *E) {
9367 // Transform the base of the expression.
9368 ExprResult Base((Expr*) nullptr);
9371 QualType ObjectType;
9372 if (!E->isImplicitAccess()) {
9373 OldBase = E->getBase();
9374 Base = getDerived().TransformExpr(OldBase);
9375 if (Base.isInvalid())
9378 // Start the member reference and compute the object's type.
9379 ParsedType ObjectTy;
9380 bool MayBePseudoDestructor = false;
9381 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
9382 E->getOperatorLoc(),
9383 E->isArrow()? tok::arrow : tok::period,
9385 MayBePseudoDestructor);
9386 if (Base.isInvalid())
9389 ObjectType = ObjectTy.get();
9390 BaseType = ((Expr*) Base.get())->getType();
9393 BaseType = getDerived().TransformType(E->getBaseType());
9394 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
9397 // Transform the first part of the nested-name-specifier that qualifies
9399 NamedDecl *FirstQualifierInScope
9400 = getDerived().TransformFirstQualifierInScope(
9401 E->getFirstQualifierFoundInScope(),
9402 E->getQualifierLoc().getBeginLoc());
9404 NestedNameSpecifierLoc QualifierLoc;
9405 if (E->getQualifier()) {
9407 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
9409 FirstQualifierInScope);
9414 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9416 // TODO: If this is a conversion-function-id, verify that the
9417 // destination type name (if present) resolves the same way after
9418 // instantiation as it did in the local scope.
9420 DeclarationNameInfo NameInfo
9421 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
9422 if (!NameInfo.getName())
9425 if (!E->hasExplicitTemplateArgs()) {
9426 // This is a reference to a member without an explicitly-specified
9427 // template argument list. Optimize for this common case.
9428 if (!getDerived().AlwaysRebuild() &&
9429 Base.get() == OldBase &&
9430 BaseType == E->getBaseType() &&
9431 QualifierLoc == E->getQualifierLoc() &&
9432 NameInfo.getName() == E->getMember() &&
9433 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
9436 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
9439 E->getOperatorLoc(),
9442 FirstQualifierInScope,
9444 /*TemplateArgs*/nullptr);
9447 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
9448 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9449 E->getNumTemplateArgs(),
9453 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
9456 E->getOperatorLoc(),
9459 FirstQualifierInScope,
9464 template<typename Derived>
9466 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
9467 // Transform the base of the expression.
9468 ExprResult Base((Expr*) nullptr);
9470 if (!Old->isImplicitAccess()) {
9471 Base = getDerived().TransformExpr(Old->getBase());
9472 if (Base.isInvalid())
9474 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
9476 if (Base.isInvalid())
9478 BaseType = Base.get()->getType();
9480 BaseType = getDerived().TransformType(Old->getBaseType());
9483 NestedNameSpecifierLoc QualifierLoc;
9484 if (Old->getQualifierLoc()) {
9486 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
9491 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
9493 LookupResult R(SemaRef, Old->getMemberNameInfo(),
9494 Sema::LookupOrdinaryName);
9496 // Transform all the decls.
9497 for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
9498 E = Old->decls_end(); I != E; ++I) {
9499 NamedDecl *InstD = static_cast<NamedDecl*>(
9500 getDerived().TransformDecl(Old->getMemberLoc(),
9503 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
9504 // This can happen because of dependent hiding.
9505 if (isa<UsingShadowDecl>(*I))
9513 // Expand using declarations.
9514 if (isa<UsingDecl>(InstD)) {
9515 UsingDecl *UD = cast<UsingDecl>(InstD);
9516 for (auto *I : UD->shadows())
9526 // Determine the naming class.
9527 if (Old->getNamingClass()) {
9528 CXXRecordDecl *NamingClass
9529 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
9530 Old->getMemberLoc(),
9531 Old->getNamingClass()));
9535 R.setNamingClass(NamingClass);
9538 TemplateArgumentListInfo TransArgs;
9539 if (Old->hasExplicitTemplateArgs()) {
9540 TransArgs.setLAngleLoc(Old->getLAngleLoc());
9541 TransArgs.setRAngleLoc(Old->getRAngleLoc());
9542 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
9543 Old->getNumTemplateArgs(),
9548 // FIXME: to do this check properly, we will need to preserve the
9549 // first-qualifier-in-scope here, just in case we had a dependent
9550 // base (and therefore couldn't do the check) and a
9551 // nested-name-qualifier (and therefore could do the lookup).
9552 NamedDecl *FirstQualifierInScope = nullptr;
9554 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
9556 Old->getOperatorLoc(),
9560 FirstQualifierInScope,
9562 (Old->hasExplicitTemplateArgs()
9563 ? &TransArgs : nullptr));
9566 template<typename Derived>
9568 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
9569 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
9570 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
9571 if (SubExpr.isInvalid())
9574 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
9577 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
9580 template<typename Derived>
9582 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
9583 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
9584 if (Pattern.isInvalid())
9587 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
9590 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
9591 E->getNumExpansions());
9594 template<typename Derived>
9596 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
9597 // If E is not value-dependent, then nothing will change when we transform it.
9598 // Note: This is an instantiation-centric view.
9599 if (!E->isValueDependent())
9602 // Note: None of the implementations of TryExpandParameterPacks can ever
9603 // produce a diagnostic when given only a single unexpanded parameter pack,
9605 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
9606 bool ShouldExpand = false;
9607 bool RetainExpansion = false;
9608 Optional<unsigned> NumExpansions;
9609 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
9611 ShouldExpand, RetainExpansion,
9615 if (RetainExpansion)
9618 NamedDecl *Pack = E->getPack();
9619 if (!ShouldExpand) {
9620 Pack = cast_or_null<NamedDecl>(getDerived().TransformDecl(E->getPackLoc(),
9627 // We now know the length of the parameter pack, so build a new expression
9628 // that stores that length.
9629 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
9630 E->getPackLoc(), E->getRParenLoc(),
9634 template<typename Derived>
9636 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
9637 SubstNonTypeTemplateParmPackExpr *E) {
9638 // Default behavior is to do nothing with this transformation.
9642 template<typename Derived>
9644 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
9645 SubstNonTypeTemplateParmExpr *E) {
9646 // Default behavior is to do nothing with this transformation.
9650 template<typename Derived>
9652 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
9653 // Default behavior is to do nothing with this transformation.
9657 template<typename Derived>
9659 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
9660 MaterializeTemporaryExpr *E) {
9661 return getDerived().TransformExpr(E->GetTemporaryExpr());
9664 template<typename Derived>
9666 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
9667 Expr *Pattern = E->getPattern();
9669 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
9670 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
9671 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
9673 // Determine whether the set of unexpanded parameter packs can and should
9676 bool RetainExpansion = false;
9677 Optional<unsigned> NumExpansions;
9678 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
9679 Pattern->getSourceRange(),
9681 Expand, RetainExpansion,
9686 // Do not expand any packs here, just transform and rebuild a fold
9688 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
9691 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
9692 if (LHS.isInvalid())
9696 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
9697 if (RHS.isInvalid())
9700 if (!getDerived().AlwaysRebuild() &&
9701 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
9704 return getDerived().RebuildCXXFoldExpr(
9705 E->getLocStart(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
9706 RHS.get(), E->getLocEnd());
9709 // The transform has determined that we should perform an elementwise
9710 // expansion of the pattern. Do so.
9711 ExprResult Result = getDerived().TransformExpr(E->getInit());
9712 if (Result.isInvalid())
9714 bool LeftFold = E->isLeftFold();
9716 // If we're retaining an expansion for a right fold, it is the innermost
9717 // component and takes the init (if any).
9718 if (!LeftFold && RetainExpansion) {
9719 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
9721 ExprResult Out = getDerived().TransformExpr(Pattern);
9722 if (Out.isInvalid())
9725 Result = getDerived().RebuildCXXFoldExpr(
9726 E->getLocStart(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
9727 Result.get(), E->getLocEnd());
9728 if (Result.isInvalid())
9732 for (unsigned I = 0; I != *NumExpansions; ++I) {
9733 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
9734 getSema(), LeftFold ? I : *NumExpansions - I - 1);
9735 ExprResult Out = getDerived().TransformExpr(Pattern);
9736 if (Out.isInvalid())
9739 if (Out.get()->containsUnexpandedParameterPack()) {
9740 // We still have a pack; retain a pack expansion for this slice.
9741 Result = getDerived().RebuildCXXFoldExpr(
9743 LeftFold ? Result.get() : Out.get(),
9744 E->getOperator(), E->getEllipsisLoc(),
9745 LeftFold ? Out.get() : Result.get(),
9747 } else if (Result.isUsable()) {
9748 // We've got down to a single element; build a binary operator.
9749 Result = getDerived().RebuildBinaryOperator(
9750 E->getEllipsisLoc(), E->getOperator(),
9751 LeftFold ? Result.get() : Out.get(),
9752 LeftFold ? Out.get() : Result.get());
9756 if (Result.isInvalid())
9760 // If we're retaining an expansion for a left fold, it is the outermost
9761 // component and takes the complete expansion so far as its init (if any).
9762 if (LeftFold && RetainExpansion) {
9763 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
9765 ExprResult Out = getDerived().TransformExpr(Pattern);
9766 if (Out.isInvalid())
9769 Result = getDerived().RebuildCXXFoldExpr(
9770 E->getLocStart(), Result.get(),
9771 E->getOperator(), E->getEllipsisLoc(),
9772 Out.get(), E->getLocEnd());
9773 if (Result.isInvalid())
9777 // If we had no init and an empty pack, and we're not retaining an expansion,
9778 // then produce a fallback value or error.
9779 if (Result.isUnset())
9780 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
9786 template<typename Derived>
9788 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
9789 CXXStdInitializerListExpr *E) {
9790 return getDerived().TransformExpr(E->getSubExpr());
9793 template<typename Derived>
9795 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
9796 return SemaRef.MaybeBindToTemporary(E);
9799 template<typename Derived>
9801 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
9805 template<typename Derived>
9807 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
9808 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9809 if (SubExpr.isInvalid())
9812 if (!getDerived().AlwaysRebuild() &&
9813 SubExpr.get() == E->getSubExpr())
9816 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
9819 template<typename Derived>
9821 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
9822 // Transform each of the elements.
9823 SmallVector<Expr *, 8> Elements;
9824 bool ArgChanged = false;
9825 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
9826 /*IsCall=*/false, Elements, &ArgChanged))
9829 if (!getDerived().AlwaysRebuild() && !ArgChanged)
9830 return SemaRef.MaybeBindToTemporary(E);
9832 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
9837 template<typename Derived>
9839 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
9840 ObjCDictionaryLiteral *E) {
9841 // Transform each of the elements.
9842 SmallVector<ObjCDictionaryElement, 8> Elements;
9843 bool ArgChanged = false;
9844 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
9845 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
9847 if (OrigElement.isPackExpansion()) {
9848 // This key/value element is a pack expansion.
9849 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
9850 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
9851 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
9852 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
9854 // Determine whether the set of unexpanded parameter packs can
9855 // and should be expanded.
9857 bool RetainExpansion = false;
9858 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
9859 Optional<unsigned> NumExpansions = OrigNumExpansions;
9860 SourceRange PatternRange(OrigElement.Key->getLocStart(),
9861 OrigElement.Value->getLocEnd());
9862 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
9865 Expand, RetainExpansion,
9870 // The transform has determined that we should perform a simple
9871 // transformation on the pack expansion, producing another pack
9873 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
9874 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
9875 if (Key.isInvalid())
9878 if (Key.get() != OrigElement.Key)
9881 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
9882 if (Value.isInvalid())
9885 if (Value.get() != OrigElement.Value)
9888 ObjCDictionaryElement Expansion = {
9889 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
9891 Elements.push_back(Expansion);
9895 // Record right away that the argument was changed. This needs
9896 // to happen even if the array expands to nothing.
9899 // The transform has determined that we should perform an elementwise
9900 // expansion of the pattern. Do so.
9901 for (unsigned I = 0; I != *NumExpansions; ++I) {
9902 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
9903 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
9904 if (Key.isInvalid())
9907 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
9908 if (Value.isInvalid())
9911 ObjCDictionaryElement Element = {
9912 Key.get(), Value.get(), SourceLocation(), NumExpansions
9915 // If any unexpanded parameter packs remain, we still have a
9917 // FIXME: Can this really happen?
9918 if (Key.get()->containsUnexpandedParameterPack() ||
9919 Value.get()->containsUnexpandedParameterPack())
9920 Element.EllipsisLoc = OrigElement.EllipsisLoc;
9922 Elements.push_back(Element);
9925 // FIXME: Retain a pack expansion if RetainExpansion is true.
9927 // We've finished with this pack expansion.
9931 // Transform and check key.
9932 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
9933 if (Key.isInvalid())
9936 if (Key.get() != OrigElement.Key)
9939 // Transform and check value.
9941 = getDerived().TransformExpr(OrigElement.Value);
9942 if (Value.isInvalid())
9945 if (Value.get() != OrigElement.Value)
9948 ObjCDictionaryElement Element = {
9949 Key.get(), Value.get(), SourceLocation(), None
9951 Elements.push_back(Element);
9954 if (!getDerived().AlwaysRebuild() && !ArgChanged)
9955 return SemaRef.MaybeBindToTemporary(E);
9957 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
9962 template<typename Derived>
9964 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
9965 TypeSourceInfo *EncodedTypeInfo
9966 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
9967 if (!EncodedTypeInfo)
9970 if (!getDerived().AlwaysRebuild() &&
9971 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
9974 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
9979 template<typename Derived>
9980 ExprResult TreeTransform<Derived>::
9981 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
9982 // This is a kind of implicit conversion, and it needs to get dropped
9983 // and recomputed for the same general reasons that ImplicitCastExprs
9984 // do, as well a more specific one: this expression is only valid when
9985 // it appears *immediately* as an argument expression.
9986 return getDerived().TransformExpr(E->getSubExpr());
9989 template<typename Derived>
9990 ExprResult TreeTransform<Derived>::
9991 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
9992 TypeSourceInfo *TSInfo
9993 = getDerived().TransformType(E->getTypeInfoAsWritten());
9997 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
9998 if (Result.isInvalid())
10001 if (!getDerived().AlwaysRebuild() &&
10002 TSInfo == E->getTypeInfoAsWritten() &&
10003 Result.get() == E->getSubExpr())
10006 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
10007 E->getBridgeKeywordLoc(), TSInfo,
10011 template<typename Derived>
10013 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
10014 // Transform arguments.
10015 bool ArgChanged = false;
10016 SmallVector<Expr*, 8> Args;
10017 Args.reserve(E->getNumArgs());
10018 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
10020 return ExprError();
10022 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
10023 // Class message: transform the receiver type.
10024 TypeSourceInfo *ReceiverTypeInfo
10025 = getDerived().TransformType(E->getClassReceiverTypeInfo());
10026 if (!ReceiverTypeInfo)
10027 return ExprError();
10029 // If nothing changed, just retain the existing message send.
10030 if (!getDerived().AlwaysRebuild() &&
10031 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
10032 return SemaRef.MaybeBindToTemporary(E);
10034 // Build a new class message send.
10035 SmallVector<SourceLocation, 16> SelLocs;
10036 E->getSelectorLocs(SelLocs);
10037 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
10040 E->getMethodDecl(),
10046 // Instance message: transform the receiver
10047 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
10048 "Only class and instance messages may be instantiated");
10049 ExprResult Receiver
10050 = getDerived().TransformExpr(E->getInstanceReceiver());
10051 if (Receiver.isInvalid())
10052 return ExprError();
10054 // If nothing changed, just retain the existing message send.
10055 if (!getDerived().AlwaysRebuild() &&
10056 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
10057 return SemaRef.MaybeBindToTemporary(E);
10059 // Build a new instance message send.
10060 SmallVector<SourceLocation, 16> SelLocs;
10061 E->getSelectorLocs(SelLocs);
10062 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
10065 E->getMethodDecl(),
10071 template<typename Derived>
10073 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
10077 template<typename Derived>
10079 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
10083 template<typename Derived>
10085 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
10086 // Transform the base expression.
10087 ExprResult Base = getDerived().TransformExpr(E->getBase());
10088 if (Base.isInvalid())
10089 return ExprError();
10091 // We don't need to transform the ivar; it will never change.
10093 // If nothing changed, just retain the existing expression.
10094 if (!getDerived().AlwaysRebuild() &&
10095 Base.get() == E->getBase())
10098 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
10100 E->isArrow(), E->isFreeIvar());
10103 template<typename Derived>
10105 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
10106 // 'super' and types never change. Property never changes. Just
10107 // retain the existing expression.
10108 if (!E->isObjectReceiver())
10111 // Transform the base expression.
10112 ExprResult Base = getDerived().TransformExpr(E->getBase());
10113 if (Base.isInvalid())
10114 return ExprError();
10116 // We don't need to transform the property; it will never change.
10118 // If nothing changed, just retain the existing expression.
10119 if (!getDerived().AlwaysRebuild() &&
10120 Base.get() == E->getBase())
10123 if (E->isExplicitProperty())
10124 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10125 E->getExplicitProperty(),
10128 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10129 SemaRef.Context.PseudoObjectTy,
10130 E->getImplicitPropertyGetter(),
10131 E->getImplicitPropertySetter(),
10135 template<typename Derived>
10137 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
10138 // Transform the base expression.
10139 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
10140 if (Base.isInvalid())
10141 return ExprError();
10143 // Transform the key expression.
10144 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
10145 if (Key.isInvalid())
10146 return ExprError();
10148 // If nothing changed, just retain the existing expression.
10149 if (!getDerived().AlwaysRebuild() &&
10150 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
10153 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
10154 Base.get(), Key.get(),
10155 E->getAtIndexMethodDecl(),
10156 E->setAtIndexMethodDecl());
10159 template<typename Derived>
10161 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
10162 // Transform the base expression.
10163 ExprResult Base = getDerived().TransformExpr(E->getBase());
10164 if (Base.isInvalid())
10165 return ExprError();
10167 // If nothing changed, just retain the existing expression.
10168 if (!getDerived().AlwaysRebuild() &&
10169 Base.get() == E->getBase())
10172 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
10177 template<typename Derived>
10179 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
10180 bool ArgumentChanged = false;
10181 SmallVector<Expr*, 8> SubExprs;
10182 SubExprs.reserve(E->getNumSubExprs());
10183 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10184 SubExprs, &ArgumentChanged))
10185 return ExprError();
10187 if (!getDerived().AlwaysRebuild() &&
10191 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
10193 E->getRParenLoc());
10196 template<typename Derived>
10198 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
10199 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
10200 if (SrcExpr.isInvalid())
10201 return ExprError();
10203 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10205 return ExprError();
10207 if (!getDerived().AlwaysRebuild() &&
10208 Type == E->getTypeSourceInfo() &&
10209 SrcExpr.get() == E->getSrcExpr())
10212 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
10213 SrcExpr.get(), Type,
10214 E->getRParenLoc());
10217 template<typename Derived>
10219 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
10220 BlockDecl *oldBlock = E->getBlockDecl();
10222 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
10223 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
10225 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
10226 blockScope->TheDecl->setBlockMissingReturnType(
10227 oldBlock->blockMissingReturnType());
10229 SmallVector<ParmVarDecl*, 4> params;
10230 SmallVector<QualType, 4> paramTypes;
10232 // Parameter substitution.
10233 if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
10234 oldBlock->param_begin(),
10235 oldBlock->param_size(),
10236 nullptr, paramTypes, ¶ms)) {
10237 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10238 return ExprError();
10241 const FunctionProtoType *exprFunctionType = E->getFunctionType();
10242 QualType exprResultType =
10243 getDerived().TransformType(exprFunctionType->getReturnType());
10245 QualType functionType =
10246 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes,
10247 exprFunctionType->getExtProtoInfo());
10248 blockScope->FunctionType = functionType;
10250 // Set the parameters on the block decl.
10251 if (!params.empty())
10252 blockScope->TheDecl->setParams(params);
10254 if (!oldBlock->blockMissingReturnType()) {
10255 blockScope->HasImplicitReturnType = false;
10256 blockScope->ReturnType = exprResultType;
10259 // Transform the body
10260 StmtResult body = getDerived().TransformStmt(E->getBody());
10261 if (body.isInvalid()) {
10262 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10263 return ExprError();
10267 // In builds with assertions, make sure that we captured everything we
10268 // captured before.
10269 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
10270 for (const auto &I : oldBlock->captures()) {
10271 VarDecl *oldCapture = I.getVariable();
10273 // Ignore parameter packs.
10274 if (isa<ParmVarDecl>(oldCapture) &&
10275 cast<ParmVarDecl>(oldCapture)->isParameterPack())
10278 VarDecl *newCapture =
10279 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
10281 assert(blockScope->CaptureMap.count(newCapture));
10283 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
10287 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
10288 /*Scope=*/nullptr);
10291 template<typename Derived>
10293 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
10294 llvm_unreachable("Cannot transform asType expressions yet");
10297 template<typename Derived>
10299 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
10300 QualType RetTy = getDerived().TransformType(E->getType());
10301 bool ArgumentChanged = false;
10302 SmallVector<Expr*, 8> SubExprs;
10303 SubExprs.reserve(E->getNumSubExprs());
10304 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10305 SubExprs, &ArgumentChanged))
10306 return ExprError();
10308 if (!getDerived().AlwaysRebuild() &&
10312 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
10313 RetTy, E->getOp(), E->getRParenLoc());
10316 //===----------------------------------------------------------------------===//
10317 // Type reconstruction
10318 //===----------------------------------------------------------------------===//
10320 template<typename Derived>
10321 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
10322 SourceLocation Star) {
10323 return SemaRef.BuildPointerType(PointeeType, Star,
10324 getDerived().getBaseEntity());
10327 template<typename Derived>
10328 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
10329 SourceLocation Star) {
10330 return SemaRef.BuildBlockPointerType(PointeeType, Star,
10331 getDerived().getBaseEntity());
10334 template<typename Derived>
10336 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
10337 bool WrittenAsLValue,
10338 SourceLocation Sigil) {
10339 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
10340 Sigil, getDerived().getBaseEntity());
10343 template<typename Derived>
10345 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
10346 QualType ClassType,
10347 SourceLocation Sigil) {
10348 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
10349 getDerived().getBaseEntity());
10352 template<typename Derived>
10354 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
10355 ArrayType::ArraySizeModifier SizeMod,
10356 const llvm::APInt *Size,
10358 unsigned IndexTypeQuals,
10359 SourceRange BracketsRange) {
10360 if (SizeExpr || !Size)
10361 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
10362 IndexTypeQuals, BracketsRange,
10363 getDerived().getBaseEntity());
10365 QualType Types[] = {
10366 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
10367 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
10368 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
10370 const unsigned NumTypes = llvm::array_lengthof(Types);
10372 for (unsigned I = 0; I != NumTypes; ++I)
10373 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
10374 SizeType = Types[I];
10378 // Note that we can return a VariableArrayType here in the case where
10379 // the element type was a dependent VariableArrayType.
10380 IntegerLiteral *ArraySize
10381 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
10382 /*FIXME*/BracketsRange.getBegin());
10383 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
10384 IndexTypeQuals, BracketsRange,
10385 getDerived().getBaseEntity());
10388 template<typename Derived>
10390 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
10391 ArrayType::ArraySizeModifier SizeMod,
10392 const llvm::APInt &Size,
10393 unsigned IndexTypeQuals,
10394 SourceRange BracketsRange) {
10395 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
10396 IndexTypeQuals, BracketsRange);
10399 template<typename Derived>
10401 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
10402 ArrayType::ArraySizeModifier SizeMod,
10403 unsigned IndexTypeQuals,
10404 SourceRange BracketsRange) {
10405 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
10406 IndexTypeQuals, BracketsRange);
10409 template<typename Derived>
10411 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
10412 ArrayType::ArraySizeModifier SizeMod,
10414 unsigned IndexTypeQuals,
10415 SourceRange BracketsRange) {
10416 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10418 IndexTypeQuals, BracketsRange);
10421 template<typename Derived>
10423 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
10424 ArrayType::ArraySizeModifier SizeMod,
10426 unsigned IndexTypeQuals,
10427 SourceRange BracketsRange) {
10428 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10430 IndexTypeQuals, BracketsRange);
10433 template<typename Derived>
10434 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
10435 unsigned NumElements,
10436 VectorType::VectorKind VecKind) {
10437 // FIXME: semantic checking!
10438 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
10441 template<typename Derived>
10442 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
10443 unsigned NumElements,
10444 SourceLocation AttributeLoc) {
10445 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
10446 NumElements, true);
10447 IntegerLiteral *VectorSize
10448 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
10450 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
10453 template<typename Derived>
10455 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
10457 SourceLocation AttributeLoc) {
10458 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
10461 template<typename Derived>
10462 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
10464 MutableArrayRef<QualType> ParamTypes,
10465 const FunctionProtoType::ExtProtoInfo &EPI) {
10466 return SemaRef.BuildFunctionType(T, ParamTypes,
10467 getDerived().getBaseLocation(),
10468 getDerived().getBaseEntity(),
10472 template<typename Derived>
10473 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
10474 return SemaRef.Context.getFunctionNoProtoType(T);
10477 template<typename Derived>
10478 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
10479 assert(D && "no decl found");
10480 if (D->isInvalidDecl()) return QualType();
10482 // FIXME: Doesn't account for ObjCInterfaceDecl!
10484 if (isa<UsingDecl>(D)) {
10485 UsingDecl *Using = cast<UsingDecl>(D);
10486 assert(Using->hasTypename() &&
10487 "UnresolvedUsingTypenameDecl transformed to non-typename using");
10489 // A valid resolved using typename decl points to exactly one type decl.
10490 assert(++Using->shadow_begin() == Using->shadow_end());
10491 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
10494 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
10495 "UnresolvedUsingTypenameDecl transformed to non-using decl");
10496 Ty = cast<UnresolvedUsingTypenameDecl>(D);
10499 return SemaRef.Context.getTypeDeclType(Ty);
10502 template<typename Derived>
10503 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
10504 SourceLocation Loc) {
10505 return SemaRef.BuildTypeofExprType(E, Loc);
10508 template<typename Derived>
10509 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
10510 return SemaRef.Context.getTypeOfType(Underlying);
10513 template<typename Derived>
10514 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
10515 SourceLocation Loc) {
10516 return SemaRef.BuildDecltypeType(E, Loc);
10519 template<typename Derived>
10520 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
10521 UnaryTransformType::UTTKind UKind,
10522 SourceLocation Loc) {
10523 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
10526 template<typename Derived>
10527 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
10528 TemplateName Template,
10529 SourceLocation TemplateNameLoc,
10530 TemplateArgumentListInfo &TemplateArgs) {
10531 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
10534 template<typename Derived>
10535 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
10536 SourceLocation KWLoc) {
10537 return SemaRef.BuildAtomicType(ValueType, KWLoc);
10540 template<typename Derived>
10542 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10544 TemplateDecl *Template) {
10545 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
10549 template<typename Derived>
10551 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10552 const IdentifierInfo &Name,
10553 SourceLocation NameLoc,
10554 QualType ObjectType,
10555 NamedDecl *FirstQualifierInScope) {
10556 UnqualifiedId TemplateName;
10557 TemplateName.setIdentifier(&Name, NameLoc);
10558 Sema::TemplateTy Template;
10559 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10560 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10561 SS, TemplateKWLoc, TemplateName,
10562 ParsedType::make(ObjectType),
10563 /*EnteringContext=*/false,
10565 return Template.get();
10568 template<typename Derived>
10570 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10571 OverloadedOperatorKind Operator,
10572 SourceLocation NameLoc,
10573 QualType ObjectType) {
10574 UnqualifiedId Name;
10575 // FIXME: Bogus location information.
10576 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
10577 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
10578 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10579 Sema::TemplateTy Template;
10580 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10581 SS, TemplateKWLoc, Name,
10582 ParsedType::make(ObjectType),
10583 /*EnteringContext=*/false,
10585 return Template.get();
10588 template<typename Derived>
10590 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
10591 SourceLocation OpLoc,
10595 Expr *Callee = OrigCallee->IgnoreParenCasts();
10596 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
10598 if (First->getObjectKind() == OK_ObjCProperty) {
10599 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10600 if (BinaryOperator::isAssignmentOp(Opc))
10601 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
10603 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
10604 if (Result.isInvalid())
10605 return ExprError();
10606 First = Result.get();
10609 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
10610 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
10611 if (Result.isInvalid())
10612 return ExprError();
10613 Second = Result.get();
10616 // Determine whether this should be a builtin operation.
10617 if (Op == OO_Subscript) {
10618 if (!First->getType()->isOverloadableType() &&
10619 !Second->getType()->isOverloadableType())
10620 return getSema().CreateBuiltinArraySubscriptExpr(First,
10621 Callee->getLocStart(),
10623 } else if (Op == OO_Arrow) {
10624 // -> is never a builtin operation.
10625 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
10626 } else if (Second == nullptr || isPostIncDec) {
10627 if (!First->getType()->isOverloadableType()) {
10628 // The argument is not of overloadable type, so try to create a
10629 // built-in unary operation.
10630 UnaryOperatorKind Opc
10631 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10633 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
10636 if (!First->getType()->isOverloadableType() &&
10637 !Second->getType()->isOverloadableType()) {
10638 // Neither of the arguments is an overloadable type, so try to
10639 // create a built-in binary operation.
10640 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10642 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
10643 if (Result.isInvalid())
10644 return ExprError();
10650 // Compute the transformed set of functions (and function templates) to be
10651 // used during overload resolution.
10652 UnresolvedSet<16> Functions;
10654 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
10655 assert(ULE->requiresADL());
10656 Functions.append(ULE->decls_begin(), ULE->decls_end());
10658 // If we've resolved this to a particular non-member function, just call
10659 // that function. If we resolved it to a member function,
10660 // CreateOverloaded* will find that function for us.
10661 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
10662 if (!isa<CXXMethodDecl>(ND))
10663 Functions.addDecl(ND);
10666 // Add any functions found via argument-dependent lookup.
10667 Expr *Args[2] = { First, Second };
10668 unsigned NumArgs = 1 + (Second != nullptr);
10670 // Create the overloaded operator invocation for unary operators.
10671 if (NumArgs == 1 || isPostIncDec) {
10672 UnaryOperatorKind Opc
10673 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10674 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
10677 if (Op == OO_Subscript) {
10678 SourceLocation LBrace;
10679 SourceLocation RBrace;
10681 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
10682 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
10683 LBrace = SourceLocation::getFromRawEncoding(
10684 NameLoc.CXXOperatorName.BeginOpNameLoc);
10685 RBrace = SourceLocation::getFromRawEncoding(
10686 NameLoc.CXXOperatorName.EndOpNameLoc);
10688 LBrace = Callee->getLocStart();
10692 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
10696 // Create the overloaded operator invocation for binary operators.
10697 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10699 = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
10700 if (Result.isInvalid())
10701 return ExprError();
10706 template<typename Derived>
10708 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
10709 SourceLocation OperatorLoc,
10712 TypeSourceInfo *ScopeType,
10713 SourceLocation CCLoc,
10714 SourceLocation TildeLoc,
10715 PseudoDestructorTypeStorage Destroyed) {
10716 QualType BaseType = Base->getType();
10717 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
10718 (!isArrow && !BaseType->getAs<RecordType>()) ||
10719 (isArrow && BaseType->getAs<PointerType>() &&
10720 !BaseType->getAs<PointerType>()->getPointeeType()
10721 ->template getAs<RecordType>())){
10722 // This pseudo-destructor expression is still a pseudo-destructor.
10723 return SemaRef.BuildPseudoDestructorExpr(Base, OperatorLoc,
10724 isArrow? tok::arrow : tok::period,
10725 SS, ScopeType, CCLoc, TildeLoc,
10730 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
10731 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
10732 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
10733 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
10734 NameInfo.setNamedTypeInfo(DestroyedType);
10736 // The scope type is now known to be a valid nested name specifier
10737 // component. Tack it on to the end of the nested name specifier.
10739 if (!ScopeType->getType()->getAs<TagType>()) {
10740 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
10741 diag::err_expected_class_or_namespace)
10742 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
10743 return ExprError();
10745 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
10749 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10750 return getSema().BuildMemberReferenceExpr(Base, BaseType,
10751 OperatorLoc, isArrow,
10753 /*FIXME: FirstQualifier*/ nullptr,
10755 /*TemplateArgs*/ nullptr);
10758 template<typename Derived>
10760 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
10761 SourceLocation Loc = S->getLocStart();
10762 CapturedDecl *CD = S->getCapturedDecl();
10763 unsigned NumParams = CD->getNumParams();
10764 unsigned ContextParamPos = CD->getContextParamPosition();
10765 SmallVector<Sema::CapturedParamNameType, 4> Params;
10766 for (unsigned I = 0; I < NumParams; ++I) {
10767 if (I != ContextParamPos) {
10770 CD->getParam(I)->getName(),
10771 getDerived().TransformType(CD->getParam(I)->getType())));
10773 Params.push_back(std::make_pair(StringRef(), QualType()));
10776 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
10777 S->getCapturedRegionKind(), Params);
10780 Sema::CompoundScopeRAII CompoundScope(getSema());
10781 Body = getDerived().TransformStmt(S->getCapturedStmt());
10784 if (Body.isInvalid()) {
10785 getSema().ActOnCapturedRegionError();
10786 return StmtError();
10789 return getSema().ActOnCapturedRegionEnd(Body.get());
10792 } // end namespace clang