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 TemplateParameterList *TransformTemplateParameterList(
624 TemplateParameterList *TPL) {
628 ExprResult TransformAddressOfOperand(Expr *E);
630 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
631 bool IsAddressOfOperand,
632 TypeSourceInfo **RecoveryTSI);
634 ExprResult TransformParenDependentScopeDeclRefExpr(
635 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
636 TypeSourceInfo **RecoveryTSI);
638 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
640 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
641 // amount of stack usage with clang.
642 #define STMT(Node, Parent) \
643 LLVM_ATTRIBUTE_NOINLINE \
644 StmtResult Transform##Node(Node *S);
645 #define EXPR(Node, Parent) \
646 LLVM_ATTRIBUTE_NOINLINE \
647 ExprResult Transform##Node(Node *E);
648 #define ABSTRACT_STMT(Stmt)
649 #include "clang/AST/StmtNodes.inc"
651 #define OPENMP_CLAUSE(Name, Class) \
652 LLVM_ATTRIBUTE_NOINLINE \
653 OMPClause *Transform ## Class(Class *S);
654 #include "clang/Basic/OpenMPKinds.def"
656 /// \brief Build a new pointer type given its pointee type.
658 /// By default, performs semantic analysis when building the pointer type.
659 /// Subclasses may override this routine to provide different behavior.
660 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
662 /// \brief Build a new block pointer type given its pointee type.
664 /// By default, performs semantic analysis when building the block pointer
665 /// type. Subclasses may override this routine to provide different behavior.
666 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
668 /// \brief Build a new reference type given the type it references.
670 /// By default, performs semantic analysis when building the
671 /// reference type. Subclasses may override this routine to provide
672 /// different behavior.
674 /// \param LValue whether the type was written with an lvalue sigil
675 /// or an rvalue sigil.
676 QualType RebuildReferenceType(QualType ReferentType,
678 SourceLocation Sigil);
680 /// \brief Build a new member pointer type given the pointee type and the
681 /// class type it refers into.
683 /// By default, performs semantic analysis when building the member pointer
684 /// type. Subclasses may override this routine to provide different behavior.
685 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
686 SourceLocation Sigil);
688 /// \brief Build an Objective-C object type.
690 /// By default, performs semantic analysis when building the object type.
691 /// Subclasses may override this routine to provide different behavior.
692 QualType RebuildObjCObjectType(QualType BaseType,
694 SourceLocation TypeArgsLAngleLoc,
695 ArrayRef<TypeSourceInfo *> TypeArgs,
696 SourceLocation TypeArgsRAngleLoc,
697 SourceLocation ProtocolLAngleLoc,
698 ArrayRef<ObjCProtocolDecl *> Protocols,
699 ArrayRef<SourceLocation> ProtocolLocs,
700 SourceLocation ProtocolRAngleLoc);
702 /// \brief Build a new Objective-C object pointer type given the pointee type.
704 /// By default, directly builds the pointer type, with no additional semantic
706 QualType RebuildObjCObjectPointerType(QualType PointeeType,
707 SourceLocation Star);
709 /// \brief Build a new array type given the element type, size
710 /// modifier, size of the array (if known), size expression, and index type
713 /// By default, performs semantic analysis when building the array type.
714 /// Subclasses may override this routine to provide different behavior.
715 /// Also by default, all of the other Rebuild*Array
716 QualType RebuildArrayType(QualType ElementType,
717 ArrayType::ArraySizeModifier SizeMod,
718 const llvm::APInt *Size,
720 unsigned IndexTypeQuals,
721 SourceRange BracketsRange);
723 /// \brief Build a new constant array type given the element type, size
724 /// modifier, (known) size of the array, and index type qualifiers.
726 /// By default, performs semantic analysis when building the array type.
727 /// Subclasses may override this routine to provide different behavior.
728 QualType RebuildConstantArrayType(QualType ElementType,
729 ArrayType::ArraySizeModifier SizeMod,
730 const llvm::APInt &Size,
731 unsigned IndexTypeQuals,
732 SourceRange BracketsRange);
734 /// \brief Build a new incomplete array type given the element type, size
735 /// modifier, and index type qualifiers.
737 /// By default, performs semantic analysis when building the array type.
738 /// Subclasses may override this routine to provide different behavior.
739 QualType RebuildIncompleteArrayType(QualType ElementType,
740 ArrayType::ArraySizeModifier SizeMod,
741 unsigned IndexTypeQuals,
742 SourceRange BracketsRange);
744 /// \brief Build a new variable-length array type given the element type,
745 /// size modifier, size expression, and index type qualifiers.
747 /// By default, performs semantic analysis when building the array type.
748 /// Subclasses may override this routine to provide different behavior.
749 QualType RebuildVariableArrayType(QualType ElementType,
750 ArrayType::ArraySizeModifier SizeMod,
752 unsigned IndexTypeQuals,
753 SourceRange BracketsRange);
755 /// \brief Build a new dependent-sized array type given the element type,
756 /// size modifier, size expression, and index type qualifiers.
758 /// By default, performs semantic analysis when building the array type.
759 /// Subclasses may override this routine to provide different behavior.
760 QualType RebuildDependentSizedArrayType(QualType ElementType,
761 ArrayType::ArraySizeModifier SizeMod,
763 unsigned IndexTypeQuals,
764 SourceRange BracketsRange);
766 /// \brief Build a new vector type given the element type and
767 /// 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 RebuildVectorType(QualType ElementType, unsigned NumElements,
772 VectorType::VectorKind VecKind);
774 /// \brief Build a new extended vector type given the element type and
775 /// number of elements.
777 /// By default, performs semantic analysis when building the vector type.
778 /// Subclasses may override this routine to provide different behavior.
779 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
780 SourceLocation AttributeLoc);
782 /// \brief Build a new potentially dependently-sized extended vector type
783 /// given the element type and number of elements.
785 /// By default, performs semantic analysis when building the vector type.
786 /// Subclasses may override this routine to provide different behavior.
787 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
789 SourceLocation AttributeLoc);
791 /// \brief Build a new function type.
793 /// By default, performs semantic analysis when building the function type.
794 /// Subclasses may override this routine to provide different behavior.
795 QualType RebuildFunctionProtoType(QualType T,
796 MutableArrayRef<QualType> ParamTypes,
797 const FunctionProtoType::ExtProtoInfo &EPI);
799 /// \brief Build a new unprototyped function type.
800 QualType RebuildFunctionNoProtoType(QualType ResultType);
802 /// \brief Rebuild an unresolved typename type, given the decl that
803 /// the UnresolvedUsingTypenameDecl was transformed to.
804 QualType RebuildUnresolvedUsingType(Decl *D);
806 /// \brief Build a new typedef type.
807 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
808 return SemaRef.Context.getTypeDeclType(Typedef);
811 /// \brief Build a new class/struct/union type.
812 QualType RebuildRecordType(RecordDecl *Record) {
813 return SemaRef.Context.getTypeDeclType(Record);
816 /// \brief Build a new Enum type.
817 QualType RebuildEnumType(EnumDecl *Enum) {
818 return SemaRef.Context.getTypeDeclType(Enum);
821 /// \brief Build a new typeof(expr) type.
823 /// By default, performs semantic analysis when building the typeof type.
824 /// Subclasses may override this routine to provide different behavior.
825 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
827 /// \brief Build a new typeof(type) type.
829 /// By default, builds a new TypeOfType with the given underlying type.
830 QualType RebuildTypeOfType(QualType Underlying);
832 /// \brief Build a new unary transform type.
833 QualType RebuildUnaryTransformType(QualType BaseType,
834 UnaryTransformType::UTTKind UKind,
837 /// \brief Build a new C++11 decltype type.
839 /// By default, performs semantic analysis when building the decltype type.
840 /// Subclasses may override this routine to provide different behavior.
841 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
843 /// \brief Build a new C++11 auto type.
845 /// By default, builds a new AutoType with the given deduced type.
846 QualType RebuildAutoType(QualType Deduced, bool IsDecltypeAuto) {
847 // Note, IsDependent is always false here: we implicitly convert an 'auto'
848 // which has been deduced to a dependent type into an undeduced 'auto', so
849 // that we'll retry deduction after the transformation.
850 return SemaRef.Context.getAutoType(Deduced, IsDecltypeAuto,
851 /*IsDependent*/ false);
854 /// \brief Build a new template specialization type.
856 /// By default, performs semantic analysis when building the template
857 /// specialization type. Subclasses may override this routine to provide
858 /// different behavior.
859 QualType RebuildTemplateSpecializationType(TemplateName Template,
860 SourceLocation TemplateLoc,
861 TemplateArgumentListInfo &Args);
863 /// \brief Build a new parenthesized type.
865 /// By default, builds a new ParenType type from the inner type.
866 /// Subclasses may override this routine to provide different behavior.
867 QualType RebuildParenType(QualType InnerType) {
868 return SemaRef.Context.getParenType(InnerType);
871 /// \brief Build a new qualified name type.
873 /// By default, builds a new ElaboratedType type from the keyword,
874 /// the nested-name-specifier and the named type.
875 /// Subclasses may override this routine to provide different behavior.
876 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
877 ElaboratedTypeKeyword Keyword,
878 NestedNameSpecifierLoc QualifierLoc,
880 return SemaRef.Context.getElaboratedType(Keyword,
881 QualifierLoc.getNestedNameSpecifier(),
885 /// \brief Build a new typename type that refers to a template-id.
887 /// By default, builds a new DependentNameType type from the
888 /// nested-name-specifier and the given type. Subclasses may override
889 /// this routine to provide different behavior.
890 QualType RebuildDependentTemplateSpecializationType(
891 ElaboratedTypeKeyword Keyword,
892 NestedNameSpecifierLoc QualifierLoc,
893 const IdentifierInfo *Name,
894 SourceLocation NameLoc,
895 TemplateArgumentListInfo &Args) {
896 // Rebuild the template name.
897 // TODO: avoid TemplateName abstraction
899 SS.Adopt(QualifierLoc);
900 TemplateName InstName
901 = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(),
904 if (InstName.isNull())
907 // If it's still dependent, make a dependent specialization.
908 if (InstName.getAsDependentTemplateName())
909 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
910 QualifierLoc.getNestedNameSpecifier(),
914 // Otherwise, make an elaborated type wrapping a non-dependent
917 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
918 if (T.isNull()) return QualType();
920 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
923 return SemaRef.Context.getElaboratedType(Keyword,
924 QualifierLoc.getNestedNameSpecifier(),
928 /// \brief Build a new typename type that refers to an identifier.
930 /// By default, performs semantic analysis when building the typename type
931 /// (or elaborated type). Subclasses may override this routine to provide
932 /// different behavior.
933 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
934 SourceLocation KeywordLoc,
935 NestedNameSpecifierLoc QualifierLoc,
936 const IdentifierInfo *Id,
937 SourceLocation IdLoc) {
939 SS.Adopt(QualifierLoc);
941 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
942 // If the name is still dependent, just build a new dependent name type.
943 if (!SemaRef.computeDeclContext(SS))
944 return SemaRef.Context.getDependentNameType(Keyword,
945 QualifierLoc.getNestedNameSpecifier(),
949 if (Keyword == ETK_None || Keyword == ETK_Typename)
950 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
953 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
955 // We had a dependent elaborated-type-specifier that has been transformed
956 // into a non-dependent elaborated-type-specifier. Find the tag we're
958 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
959 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
963 if (SemaRef.RequireCompleteDeclContext(SS, DC))
966 TagDecl *Tag = nullptr;
967 SemaRef.LookupQualifiedName(Result, DC);
968 switch (Result.getResultKind()) {
969 case LookupResult::NotFound:
970 case LookupResult::NotFoundInCurrentInstantiation:
973 case LookupResult::Found:
974 Tag = Result.getAsSingle<TagDecl>();
977 case LookupResult::FoundOverloaded:
978 case LookupResult::FoundUnresolvedValue:
979 llvm_unreachable("Tag lookup cannot find non-tags");
981 case LookupResult::Ambiguous:
982 // Let the LookupResult structure handle ambiguities.
987 // Check where the name exists but isn't a tag type and use that to emit
988 // better diagnostics.
989 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
990 SemaRef.LookupQualifiedName(Result, DC);
991 switch (Result.getResultKind()) {
992 case LookupResult::Found:
993 case LookupResult::FoundOverloaded:
994 case LookupResult::FoundUnresolvedValue: {
995 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
997 if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
998 else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
999 else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
1000 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
1001 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1005 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1006 << Kind << Id << DC << QualifierLoc.getSourceRange();
1012 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1014 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1015 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1019 // Build the elaborated-type-specifier type.
1020 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1021 return SemaRef.Context.getElaboratedType(Keyword,
1022 QualifierLoc.getNestedNameSpecifier(),
1026 /// \brief Build a new pack expansion type.
1028 /// By default, builds a new PackExpansionType type from the given pattern.
1029 /// Subclasses may override this routine to provide different behavior.
1030 QualType RebuildPackExpansionType(QualType Pattern,
1031 SourceRange PatternRange,
1032 SourceLocation EllipsisLoc,
1033 Optional<unsigned> NumExpansions) {
1034 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1038 /// \brief Build a new atomic type given its value type.
1040 /// By default, performs semantic analysis when building the atomic type.
1041 /// Subclasses may override this routine to provide different behavior.
1042 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1044 /// \brief Build a new template name given a nested name specifier, a flag
1045 /// indicating whether the "template" keyword was provided, and the template
1046 /// that the template name refers to.
1048 /// By default, builds the new template name directly. Subclasses may override
1049 /// this routine to provide different behavior.
1050 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1052 TemplateDecl *Template);
1054 /// \brief Build a new template name given a nested name specifier and the
1055 /// name that is referred to as a template.
1057 /// By default, performs semantic analysis to determine whether the name can
1058 /// be resolved to a specific template, then builds the appropriate kind of
1059 /// template name. Subclasses may override this routine to provide different
1061 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1062 const IdentifierInfo &Name,
1063 SourceLocation NameLoc,
1064 QualType ObjectType,
1065 NamedDecl *FirstQualifierInScope);
1067 /// \brief Build a new template name given a nested name specifier and the
1068 /// overloaded operator name that is referred to as a template.
1070 /// By default, performs semantic analysis to determine whether the name can
1071 /// be resolved to a specific template, then builds the appropriate kind of
1072 /// template name. Subclasses may override this routine to provide different
1074 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1075 OverloadedOperatorKind Operator,
1076 SourceLocation NameLoc,
1077 QualType ObjectType);
1079 /// \brief Build a new template name given a template template parameter pack
1082 /// By default, performs semantic analysis to determine whether the name can
1083 /// be resolved to a specific template, then builds the appropriate kind of
1084 /// template name. Subclasses may override this routine to provide different
1086 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1087 const TemplateArgument &ArgPack) {
1088 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1091 /// \brief Build a new compound statement.
1093 /// By default, performs semantic analysis to build the new statement.
1094 /// Subclasses may override this routine to provide different behavior.
1095 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1096 MultiStmtArg Statements,
1097 SourceLocation RBraceLoc,
1099 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1103 /// \brief Build a new case statement.
1105 /// By default, performs semantic analysis to build the new statement.
1106 /// Subclasses may override this routine to provide different behavior.
1107 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1109 SourceLocation EllipsisLoc,
1111 SourceLocation ColonLoc) {
1112 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1116 /// \brief Attach the body to a new case statement.
1118 /// By default, performs semantic analysis to build the new statement.
1119 /// Subclasses may override this routine to provide different behavior.
1120 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1121 getSema().ActOnCaseStmtBody(S, Body);
1125 /// \brief Build a new default statement.
1127 /// By default, performs semantic analysis to build the new statement.
1128 /// Subclasses may override this routine to provide different behavior.
1129 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1130 SourceLocation ColonLoc,
1132 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1133 /*CurScope=*/nullptr);
1136 /// \brief Build a new label statement.
1138 /// By default, performs semantic analysis to build the new statement.
1139 /// Subclasses may override this routine to provide different behavior.
1140 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1141 SourceLocation ColonLoc, Stmt *SubStmt) {
1142 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1145 /// \brief Build a new label statement.
1147 /// By default, performs semantic analysis to build the new statement.
1148 /// Subclasses may override this routine to provide different behavior.
1149 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1150 ArrayRef<const Attr*> Attrs,
1152 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1155 /// \brief Build a new "if" statement.
1157 /// By default, performs semantic analysis to build the new statement.
1158 /// Subclasses may override this routine to provide different behavior.
1159 StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
1160 VarDecl *CondVar, Stmt *Then,
1161 SourceLocation ElseLoc, Stmt *Else) {
1162 return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
1165 /// \brief Start building a new switch statement.
1167 /// By default, performs semantic analysis to build the new statement.
1168 /// Subclasses may override this routine to provide different behavior.
1169 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1170 Expr *Cond, VarDecl *CondVar) {
1171 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
1175 /// \brief Attach the body to the switch statement.
1177 /// By default, performs semantic analysis to build the new statement.
1178 /// Subclasses may override this routine to provide different behavior.
1179 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1180 Stmt *Switch, Stmt *Body) {
1181 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1184 /// \brief Build a new while statement.
1186 /// By default, performs semantic analysis to build the new statement.
1187 /// Subclasses may override this routine to provide different behavior.
1188 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
1189 VarDecl *CondVar, Stmt *Body) {
1190 return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
1193 /// \brief Build a new do-while statement.
1195 /// By default, performs semantic analysis to build the new statement.
1196 /// Subclasses may override this routine to provide different behavior.
1197 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1198 SourceLocation WhileLoc, SourceLocation LParenLoc,
1199 Expr *Cond, SourceLocation RParenLoc) {
1200 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1204 /// \brief Build a new for statement.
1206 /// By default, performs semantic analysis to build the new statement.
1207 /// Subclasses may override this routine to provide different behavior.
1208 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1209 Stmt *Init, Sema::FullExprArg Cond,
1210 VarDecl *CondVar, Sema::FullExprArg Inc,
1211 SourceLocation RParenLoc, Stmt *Body) {
1212 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1213 CondVar, Inc, RParenLoc, Body);
1216 /// \brief Build a new goto statement.
1218 /// By default, performs semantic analysis to build the new statement.
1219 /// Subclasses may override this routine to provide different behavior.
1220 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1222 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1225 /// \brief Build a new indirect goto statement.
1227 /// By default, performs semantic analysis to build the new statement.
1228 /// Subclasses may override this routine to provide different behavior.
1229 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1230 SourceLocation StarLoc,
1232 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1235 /// \brief Build a new return statement.
1237 /// By default, performs semantic analysis to build the new statement.
1238 /// Subclasses may override this routine to provide different behavior.
1239 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1240 return getSema().BuildReturnStmt(ReturnLoc, Result);
1243 /// \brief Build a new declaration statement.
1245 /// By default, performs semantic analysis to build the new statement.
1246 /// Subclasses may override this routine to provide different behavior.
1247 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1248 SourceLocation StartLoc, SourceLocation EndLoc) {
1249 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1250 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1253 /// \brief Build a new inline asm statement.
1255 /// By default, performs semantic analysis to build the new statement.
1256 /// Subclasses may override this routine to provide different behavior.
1257 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1258 bool IsVolatile, unsigned NumOutputs,
1259 unsigned NumInputs, IdentifierInfo **Names,
1260 MultiExprArg Constraints, MultiExprArg Exprs,
1261 Expr *AsmString, MultiExprArg Clobbers,
1262 SourceLocation RParenLoc) {
1263 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1264 NumInputs, Names, Constraints, Exprs,
1265 AsmString, Clobbers, RParenLoc);
1268 /// \brief Build a new MS style inline asm statement.
1270 /// By default, performs semantic analysis to build the new statement.
1271 /// Subclasses may override this routine to provide different behavior.
1272 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1273 ArrayRef<Token> AsmToks,
1274 StringRef AsmString,
1275 unsigned NumOutputs, unsigned NumInputs,
1276 ArrayRef<StringRef> Constraints,
1277 ArrayRef<StringRef> Clobbers,
1278 ArrayRef<Expr*> Exprs,
1279 SourceLocation EndLoc) {
1280 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1281 NumOutputs, NumInputs,
1282 Constraints, Clobbers, Exprs, EndLoc);
1285 /// \brief Build a new Objective-C \@try statement.
1287 /// By default, performs semantic analysis to build the new statement.
1288 /// Subclasses may override this routine to provide different behavior.
1289 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1291 MultiStmtArg CatchStmts,
1293 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1297 /// \brief Rebuild an Objective-C exception declaration.
1299 /// By default, performs semantic analysis to build the new declaration.
1300 /// Subclasses may override this routine to provide different behavior.
1301 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1302 TypeSourceInfo *TInfo, QualType T) {
1303 return getSema().BuildObjCExceptionDecl(TInfo, T,
1304 ExceptionDecl->getInnerLocStart(),
1305 ExceptionDecl->getLocation(),
1306 ExceptionDecl->getIdentifier());
1309 /// \brief Build a new Objective-C \@catch statement.
1311 /// By default, performs semantic analysis to build the new statement.
1312 /// Subclasses may override this routine to provide different behavior.
1313 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1314 SourceLocation RParenLoc,
1317 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1321 /// \brief Build a new Objective-C \@finally statement.
1323 /// By default, performs semantic analysis to build the new statement.
1324 /// Subclasses may override this routine to provide different behavior.
1325 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1327 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1330 /// \brief Build a new Objective-C \@throw statement.
1332 /// By default, performs semantic analysis to build the new statement.
1333 /// Subclasses may override this routine to provide different behavior.
1334 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1336 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1339 /// \brief Build a new OpenMP executable directive.
1341 /// By default, performs semantic analysis to build the new statement.
1342 /// Subclasses may override this routine to provide different behavior.
1343 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1344 DeclarationNameInfo DirName,
1345 OpenMPDirectiveKind CancelRegion,
1346 ArrayRef<OMPClause *> Clauses,
1347 Stmt *AStmt, SourceLocation StartLoc,
1348 SourceLocation EndLoc) {
1349 return getSema().ActOnOpenMPExecutableDirective(
1350 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1353 /// \brief Build a new OpenMP 'if' clause.
1355 /// By default, performs semantic analysis to build the new OpenMP clause.
1356 /// Subclasses may override this routine to provide different behavior.
1357 OMPClause *RebuildOMPIfClause(Expr *Condition,
1358 SourceLocation StartLoc,
1359 SourceLocation LParenLoc,
1360 SourceLocation EndLoc) {
1361 return getSema().ActOnOpenMPIfClause(Condition, StartLoc,
1365 /// \brief Build a new OpenMP 'final' clause.
1367 /// By default, performs semantic analysis to build the new OpenMP clause.
1368 /// Subclasses may override this routine to provide different behavior.
1369 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1370 SourceLocation LParenLoc,
1371 SourceLocation EndLoc) {
1372 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1376 /// \brief Build a new OpenMP 'num_threads' clause.
1378 /// By default, performs semantic analysis to build the new OpenMP clause.
1379 /// Subclasses may override this routine to provide different behavior.
1380 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1381 SourceLocation StartLoc,
1382 SourceLocation LParenLoc,
1383 SourceLocation EndLoc) {
1384 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1388 /// \brief Build a new OpenMP 'safelen' clause.
1390 /// By default, performs semantic analysis to build the new OpenMP clause.
1391 /// Subclasses may override this routine to provide different behavior.
1392 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1393 SourceLocation LParenLoc,
1394 SourceLocation EndLoc) {
1395 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1398 /// \brief Build a new OpenMP 'collapse' clause.
1400 /// By default, performs semantic analysis to build the new OpenMP clause.
1401 /// Subclasses may override this routine to provide different behavior.
1402 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1403 SourceLocation LParenLoc,
1404 SourceLocation EndLoc) {
1405 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1409 /// \brief Build a new OpenMP 'default' clause.
1411 /// By default, performs semantic analysis to build the new OpenMP clause.
1412 /// Subclasses may override this routine to provide different behavior.
1413 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1414 SourceLocation KindKwLoc,
1415 SourceLocation StartLoc,
1416 SourceLocation LParenLoc,
1417 SourceLocation EndLoc) {
1418 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1419 StartLoc, LParenLoc, EndLoc);
1422 /// \brief Build a new OpenMP 'proc_bind' clause.
1424 /// By default, performs semantic analysis to build the new OpenMP clause.
1425 /// Subclasses may override this routine to provide different behavior.
1426 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1427 SourceLocation KindKwLoc,
1428 SourceLocation StartLoc,
1429 SourceLocation LParenLoc,
1430 SourceLocation EndLoc) {
1431 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1432 StartLoc, LParenLoc, EndLoc);
1435 /// \brief Build a new OpenMP 'schedule' clause.
1437 /// By default, performs semantic analysis to build the new OpenMP clause.
1438 /// Subclasses may override this routine to provide different behavior.
1439 OMPClause *RebuildOMPScheduleClause(OpenMPScheduleClauseKind Kind,
1441 SourceLocation StartLoc,
1442 SourceLocation LParenLoc,
1443 SourceLocation KindLoc,
1444 SourceLocation CommaLoc,
1445 SourceLocation EndLoc) {
1446 return getSema().ActOnOpenMPScheduleClause(
1447 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1450 /// \brief Build a new OpenMP 'private' clause.
1452 /// By default, performs semantic analysis to build the new OpenMP clause.
1453 /// Subclasses may override this routine to provide different behavior.
1454 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1455 SourceLocation StartLoc,
1456 SourceLocation LParenLoc,
1457 SourceLocation EndLoc) {
1458 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1462 /// \brief Build a new OpenMP 'firstprivate' clause.
1464 /// By default, performs semantic analysis to build the new OpenMP clause.
1465 /// Subclasses may override this routine to provide different behavior.
1466 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1467 SourceLocation StartLoc,
1468 SourceLocation LParenLoc,
1469 SourceLocation EndLoc) {
1470 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1474 /// \brief Build a new OpenMP 'lastprivate' clause.
1476 /// By default, performs semantic analysis to build the new OpenMP clause.
1477 /// Subclasses may override this routine to provide different behavior.
1478 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1479 SourceLocation StartLoc,
1480 SourceLocation LParenLoc,
1481 SourceLocation EndLoc) {
1482 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1486 /// \brief Build a new OpenMP 'shared' clause.
1488 /// By default, performs semantic analysis to build the new OpenMP clause.
1489 /// Subclasses may override this routine to provide different behavior.
1490 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1491 SourceLocation StartLoc,
1492 SourceLocation LParenLoc,
1493 SourceLocation EndLoc) {
1494 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1498 /// \brief Build a new OpenMP 'reduction' clause.
1500 /// By default, performs semantic analysis to build the new statement.
1501 /// Subclasses may override this routine to provide different behavior.
1502 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1503 SourceLocation StartLoc,
1504 SourceLocation LParenLoc,
1505 SourceLocation ColonLoc,
1506 SourceLocation EndLoc,
1507 CXXScopeSpec &ReductionIdScopeSpec,
1508 const DeclarationNameInfo &ReductionId) {
1509 return getSema().ActOnOpenMPReductionClause(
1510 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1514 /// \brief Build a new OpenMP 'linear' clause.
1516 /// By default, performs semantic analysis to build the new OpenMP clause.
1517 /// Subclasses may override this routine to provide different behavior.
1518 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1519 SourceLocation StartLoc,
1520 SourceLocation LParenLoc,
1521 SourceLocation ColonLoc,
1522 SourceLocation EndLoc) {
1523 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1527 /// \brief Build a new OpenMP 'aligned' clause.
1529 /// By default, performs semantic analysis to build the new OpenMP clause.
1530 /// Subclasses may override this routine to provide different behavior.
1531 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1532 SourceLocation StartLoc,
1533 SourceLocation LParenLoc,
1534 SourceLocation ColonLoc,
1535 SourceLocation EndLoc) {
1536 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1537 LParenLoc, ColonLoc, EndLoc);
1540 /// \brief Build a new OpenMP 'copyin' clause.
1542 /// By default, performs semantic analysis to build the new OpenMP clause.
1543 /// Subclasses may override this routine to provide different behavior.
1544 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1545 SourceLocation StartLoc,
1546 SourceLocation LParenLoc,
1547 SourceLocation EndLoc) {
1548 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1552 /// \brief Build a new OpenMP 'copyprivate' clause.
1554 /// By default, performs semantic analysis to build the new OpenMP clause.
1555 /// Subclasses may override this routine to provide different behavior.
1556 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1557 SourceLocation StartLoc,
1558 SourceLocation LParenLoc,
1559 SourceLocation EndLoc) {
1560 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1564 /// \brief Build a new OpenMP 'flush' pseudo clause.
1566 /// By default, performs semantic analysis to build the new OpenMP clause.
1567 /// Subclasses may override this routine to provide different behavior.
1568 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1569 SourceLocation StartLoc,
1570 SourceLocation LParenLoc,
1571 SourceLocation EndLoc) {
1572 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1576 /// \brief Build a new OpenMP 'depend' pseudo clause.
1578 /// By default, performs semantic analysis to build the new OpenMP clause.
1579 /// Subclasses may override this routine to provide different behavior.
1581 RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1582 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1583 SourceLocation StartLoc, SourceLocation LParenLoc,
1584 SourceLocation EndLoc) {
1585 return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1586 StartLoc, LParenLoc, EndLoc);
1589 /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
1591 /// By default, performs semantic analysis to build the new statement.
1592 /// Subclasses may override this routine to provide different behavior.
1593 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1595 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1598 /// \brief Build a new Objective-C \@synchronized statement.
1600 /// By default, performs semantic analysis to build the new statement.
1601 /// Subclasses may override this routine to provide different behavior.
1602 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1603 Expr *Object, Stmt *Body) {
1604 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1607 /// \brief Build a new Objective-C \@autoreleasepool statement.
1609 /// By default, performs semantic analysis to build the new statement.
1610 /// Subclasses may override this routine to provide different behavior.
1611 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1613 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1616 /// \brief Build a new Objective-C fast enumeration statement.
1618 /// By default, performs semantic analysis to build the new statement.
1619 /// Subclasses may override this routine to provide different behavior.
1620 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1623 SourceLocation RParenLoc,
1625 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1629 if (ForEachStmt.isInvalid())
1632 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
1635 /// \brief Build a new C++ exception declaration.
1637 /// By default, performs semantic analysis to build the new decaration.
1638 /// Subclasses may override this routine to provide different behavior.
1639 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1640 TypeSourceInfo *Declarator,
1641 SourceLocation StartLoc,
1642 SourceLocation IdLoc,
1643 IdentifierInfo *Id) {
1644 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
1645 StartLoc, IdLoc, Id);
1647 getSema().CurContext->addDecl(Var);
1651 /// \brief Build a new C++ catch statement.
1653 /// By default, performs semantic analysis to build the new statement.
1654 /// Subclasses may override this routine to provide different behavior.
1655 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
1656 VarDecl *ExceptionDecl,
1658 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
1662 /// \brief Build a new C++ try statement.
1664 /// By default, performs semantic analysis to build the new statement.
1665 /// Subclasses may override this routine to provide different behavior.
1666 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
1667 ArrayRef<Stmt *> Handlers) {
1668 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
1671 /// \brief Build a new C++0x range-based for statement.
1673 /// By default, performs semantic analysis to build the new statement.
1674 /// Subclasses may override this routine to provide different behavior.
1675 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
1676 SourceLocation ColonLoc,
1677 Stmt *Range, Stmt *BeginEnd,
1678 Expr *Cond, Expr *Inc,
1680 SourceLocation RParenLoc) {
1681 // If we've just learned that the range is actually an Objective-C
1682 // collection, treat this as an Objective-C fast enumeration loop.
1683 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
1684 if (RangeStmt->isSingleDecl()) {
1685 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
1686 if (RangeVar->isInvalidDecl())
1689 Expr *RangeExpr = RangeVar->getInit();
1690 if (!RangeExpr->isTypeDependent() &&
1691 RangeExpr->getType()->isObjCObjectPointerType())
1692 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
1698 return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEnd,
1699 Cond, Inc, LoopVar, RParenLoc,
1700 Sema::BFRK_Rebuild);
1703 /// \brief Build a new C++0x range-based for statement.
1705 /// By default, performs semantic analysis to build the new statement.
1706 /// Subclasses may override this routine to provide different behavior.
1707 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
1709 NestedNameSpecifierLoc QualifierLoc,
1710 DeclarationNameInfo NameInfo,
1712 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
1713 QualifierLoc, NameInfo, Nested);
1716 /// \brief Attach body to a C++0x range-based for statement.
1718 /// By default, performs semantic analysis to finish the new statement.
1719 /// Subclasses may override this routine to provide different behavior.
1720 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
1721 return getSema().FinishCXXForRangeStmt(ForRange, Body);
1724 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
1725 Stmt *TryBlock, Stmt *Handler) {
1726 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
1729 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
1731 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
1734 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
1735 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
1738 /// \brief Build a new predefined expression.
1740 /// By default, performs semantic analysis to build the new expression.
1741 /// Subclasses may override this routine to provide different behavior.
1742 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
1743 PredefinedExpr::IdentType IT) {
1744 return getSema().BuildPredefinedExpr(Loc, IT);
1747 /// \brief Build a new expression that references a declaration.
1749 /// By default, performs semantic analysis to build the new expression.
1750 /// Subclasses may override this routine to provide different behavior.
1751 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
1754 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
1758 /// \brief Build a new expression that references a declaration.
1760 /// By default, performs semantic analysis to build the new expression.
1761 /// Subclasses may override this routine to provide different behavior.
1762 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
1764 const DeclarationNameInfo &NameInfo,
1765 TemplateArgumentListInfo *TemplateArgs) {
1767 SS.Adopt(QualifierLoc);
1769 // FIXME: loses template args.
1771 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
1774 /// \brief Build a new expression in parentheses.
1776 /// By default, performs semantic analysis to build the new expression.
1777 /// Subclasses may override this routine to provide different behavior.
1778 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
1779 SourceLocation RParen) {
1780 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
1783 /// \brief Build a new pseudo-destructor expression.
1785 /// By default, performs semantic analysis to build the new expression.
1786 /// Subclasses may override this routine to provide different behavior.
1787 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
1788 SourceLocation OperatorLoc,
1791 TypeSourceInfo *ScopeType,
1792 SourceLocation CCLoc,
1793 SourceLocation TildeLoc,
1794 PseudoDestructorTypeStorage Destroyed);
1796 /// \brief Build a new unary operator expression.
1798 /// By default, performs semantic analysis to build the new expression.
1799 /// Subclasses may override this routine to provide different behavior.
1800 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
1801 UnaryOperatorKind Opc,
1803 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
1806 /// \brief Build a new builtin offsetof expression.
1808 /// By default, performs semantic analysis to build the new expression.
1809 /// Subclasses may override this routine to provide different behavior.
1810 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
1811 TypeSourceInfo *Type,
1812 Sema::OffsetOfComponent *Components,
1813 unsigned NumComponents,
1814 SourceLocation RParenLoc) {
1815 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
1816 NumComponents, RParenLoc);
1819 /// \brief Build a new sizeof, alignof or vec_step expression with a
1822 /// By default, performs semantic analysis to build the new expression.
1823 /// Subclasses may override this routine to provide different behavior.
1824 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
1825 SourceLocation OpLoc,
1826 UnaryExprOrTypeTrait ExprKind,
1828 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
1831 /// \brief Build a new sizeof, alignof or vec step expression with an
1832 /// expression argument.
1834 /// By default, performs semantic analysis to build the new expression.
1835 /// Subclasses may override this routine to provide different behavior.
1836 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
1837 UnaryExprOrTypeTrait ExprKind,
1840 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
1841 if (Result.isInvalid())
1847 /// \brief Build a new array subscript expression.
1849 /// By default, performs semantic analysis to build the new expression.
1850 /// Subclasses may override this routine to provide different behavior.
1851 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
1852 SourceLocation LBracketLoc,
1854 SourceLocation RBracketLoc) {
1855 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
1860 /// \brief Build a new call expression.
1862 /// By default, performs semantic analysis to build the new expression.
1863 /// Subclasses may override this routine to provide different behavior.
1864 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
1866 SourceLocation RParenLoc,
1867 Expr *ExecConfig = nullptr) {
1868 return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
1869 Args, RParenLoc, ExecConfig);
1872 /// \brief Build a new member access expression.
1874 /// By default, performs semantic analysis to build the new expression.
1875 /// Subclasses may override this routine to provide different behavior.
1876 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
1878 NestedNameSpecifierLoc QualifierLoc,
1879 SourceLocation TemplateKWLoc,
1880 const DeclarationNameInfo &MemberNameInfo,
1882 NamedDecl *FoundDecl,
1883 const TemplateArgumentListInfo *ExplicitTemplateArgs,
1884 NamedDecl *FirstQualifierInScope) {
1885 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
1887 if (!Member->getDeclName()) {
1888 // We have a reference to an unnamed field. This is always the
1889 // base of an anonymous struct/union member access, i.e. the
1890 // field is always of record type.
1891 assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
1892 assert(Member->getType()->isRecordType() &&
1893 "unnamed member not of record type?");
1896 getSema().PerformObjectMemberConversion(BaseResult.get(),
1897 QualifierLoc.getNestedNameSpecifier(),
1899 if (BaseResult.isInvalid())
1901 Base = BaseResult.get();
1902 ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
1903 MemberExpr *ME = new (getSema().Context)
1904 MemberExpr(Base, isArrow, OpLoc, Member, MemberNameInfo,
1905 cast<FieldDecl>(Member)->getType(), VK, OK_Ordinary);
1910 SS.Adopt(QualifierLoc);
1912 Base = BaseResult.get();
1913 QualType BaseType = Base->getType();
1915 // FIXME: this involves duplicating earlier analysis in a lot of
1916 // cases; we should avoid this when possible.
1917 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
1918 R.addDecl(FoundDecl);
1921 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
1923 FirstQualifierInScope,
1924 R, ExplicitTemplateArgs);
1927 /// \brief Build a new binary operator expression.
1929 /// By default, performs semantic analysis to build the new expression.
1930 /// Subclasses may override this routine to provide different behavior.
1931 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
1932 BinaryOperatorKind Opc,
1933 Expr *LHS, Expr *RHS) {
1934 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
1937 /// \brief Build a new conditional operator expression.
1939 /// By default, performs semantic analysis to build the new expression.
1940 /// Subclasses may override this routine to provide different behavior.
1941 ExprResult RebuildConditionalOperator(Expr *Cond,
1942 SourceLocation QuestionLoc,
1944 SourceLocation ColonLoc,
1946 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
1950 /// \brief Build a new C-style cast expression.
1952 /// By default, performs semantic analysis to build the new expression.
1953 /// Subclasses may override this routine to provide different behavior.
1954 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
1955 TypeSourceInfo *TInfo,
1956 SourceLocation RParenLoc,
1958 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
1962 /// \brief Build a new compound literal expression.
1964 /// By default, performs semantic analysis to build the new expression.
1965 /// Subclasses may override this routine to provide different behavior.
1966 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
1967 TypeSourceInfo *TInfo,
1968 SourceLocation RParenLoc,
1970 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
1974 /// \brief Build a new extended vector element access expression.
1976 /// By default, performs semantic analysis to build the new expression.
1977 /// Subclasses may override this routine to provide different behavior.
1978 ExprResult RebuildExtVectorElementExpr(Expr *Base,
1979 SourceLocation OpLoc,
1980 SourceLocation AccessorLoc,
1981 IdentifierInfo &Accessor) {
1984 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
1985 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
1986 OpLoc, /*IsArrow*/ false,
1987 SS, SourceLocation(),
1988 /*FirstQualifierInScope*/ nullptr,
1990 /* TemplateArgs */ nullptr);
1993 /// \brief Build a new initializer list expression.
1995 /// By default, performs semantic analysis to build the new expression.
1996 /// Subclasses may override this routine to provide different behavior.
1997 ExprResult RebuildInitList(SourceLocation LBraceLoc,
1999 SourceLocation RBraceLoc,
2000 QualType ResultTy) {
2002 = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
2003 if (Result.isInvalid() || ResultTy->isDependentType())
2006 // Patch in the result type we were given, which may have been computed
2007 // when the initial InitListExpr was built.
2008 InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
2009 ILE->setType(ResultTy);
2013 /// \brief Build a new designated initializer expression.
2015 /// By default, performs semantic analysis to build the new expression.
2016 /// Subclasses may override this routine to provide different behavior.
2017 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2018 MultiExprArg ArrayExprs,
2019 SourceLocation EqualOrColonLoc,
2023 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2025 if (Result.isInvalid())
2031 /// \brief Build a new value-initialized expression.
2033 /// By default, builds the implicit value initialization without performing
2034 /// any semantic analysis. Subclasses may override this routine to provide
2035 /// different behavior.
2036 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2037 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2040 /// \brief Build a new \c va_arg expression.
2042 /// By default, performs semantic analysis to build the new expression.
2043 /// Subclasses may override this routine to provide different behavior.
2044 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2045 Expr *SubExpr, TypeSourceInfo *TInfo,
2046 SourceLocation RParenLoc) {
2047 return getSema().BuildVAArgExpr(BuiltinLoc,
2052 /// \brief Build a new expression list in parentheses.
2054 /// By default, performs semantic analysis to build the new expression.
2055 /// Subclasses may override this routine to provide different behavior.
2056 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2057 MultiExprArg SubExprs,
2058 SourceLocation RParenLoc) {
2059 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2062 /// \brief Build a new address-of-label expression.
2064 /// By default, performs semantic analysis, using the name of the label
2065 /// rather than attempting to map the label statement itself.
2066 /// Subclasses may override this routine to provide different behavior.
2067 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2068 SourceLocation LabelLoc, LabelDecl *Label) {
2069 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2072 /// \brief Build a new GNU statement expression.
2074 /// By default, performs semantic analysis to build the new expression.
2075 /// Subclasses may override this routine to provide different behavior.
2076 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2078 SourceLocation RParenLoc) {
2079 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2082 /// \brief Build a new __builtin_choose_expr expression.
2084 /// By default, performs semantic analysis to build the new expression.
2085 /// Subclasses may override this routine to provide different behavior.
2086 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2087 Expr *Cond, Expr *LHS, Expr *RHS,
2088 SourceLocation RParenLoc) {
2089 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2094 /// \brief Build a new generic selection expression.
2096 /// By default, performs semantic analysis to build the new expression.
2097 /// Subclasses may override this routine to provide different behavior.
2098 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2099 SourceLocation DefaultLoc,
2100 SourceLocation RParenLoc,
2101 Expr *ControllingExpr,
2102 ArrayRef<TypeSourceInfo *> Types,
2103 ArrayRef<Expr *> Exprs) {
2104 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2105 ControllingExpr, Types, Exprs);
2108 /// \brief Build a new overloaded operator call expression.
2110 /// By default, performs semantic analysis to build the new expression.
2111 /// The semantic analysis provides the behavior of template instantiation,
2112 /// copying with transformations that turn what looks like an overloaded
2113 /// operator call into a use of a builtin operator, performing
2114 /// argument-dependent lookup, etc. Subclasses may override this routine to
2115 /// provide different behavior.
2116 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2117 SourceLocation OpLoc,
2122 /// \brief Build a new C++ "named" cast expression, such as static_cast or
2123 /// reinterpret_cast.
2125 /// By default, this routine dispatches to one of the more-specific routines
2126 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2127 /// Subclasses may override this routine to provide different behavior.
2128 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2129 Stmt::StmtClass Class,
2130 SourceLocation LAngleLoc,
2131 TypeSourceInfo *TInfo,
2132 SourceLocation RAngleLoc,
2133 SourceLocation LParenLoc,
2135 SourceLocation RParenLoc) {
2137 case Stmt::CXXStaticCastExprClass:
2138 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2139 RAngleLoc, LParenLoc,
2140 SubExpr, RParenLoc);
2142 case Stmt::CXXDynamicCastExprClass:
2143 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2144 RAngleLoc, LParenLoc,
2145 SubExpr, RParenLoc);
2147 case Stmt::CXXReinterpretCastExprClass:
2148 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2149 RAngleLoc, LParenLoc,
2153 case Stmt::CXXConstCastExprClass:
2154 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2155 RAngleLoc, LParenLoc,
2156 SubExpr, RParenLoc);
2159 llvm_unreachable("Invalid C++ named cast");
2163 /// \brief Build a new C++ static_cast expression.
2165 /// By default, performs semantic analysis to build the new expression.
2166 /// Subclasses may override this routine to provide different behavior.
2167 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2168 SourceLocation LAngleLoc,
2169 TypeSourceInfo *TInfo,
2170 SourceLocation RAngleLoc,
2171 SourceLocation LParenLoc,
2173 SourceLocation RParenLoc) {
2174 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2176 SourceRange(LAngleLoc, RAngleLoc),
2177 SourceRange(LParenLoc, RParenLoc));
2180 /// \brief Build a new C++ dynamic_cast expression.
2182 /// By default, performs semantic analysis to build the new expression.
2183 /// Subclasses may override this routine to provide different behavior.
2184 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2185 SourceLocation LAngleLoc,
2186 TypeSourceInfo *TInfo,
2187 SourceLocation RAngleLoc,
2188 SourceLocation LParenLoc,
2190 SourceLocation RParenLoc) {
2191 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2193 SourceRange(LAngleLoc, RAngleLoc),
2194 SourceRange(LParenLoc, RParenLoc));
2197 /// \brief Build a new C++ reinterpret_cast expression.
2199 /// By default, performs semantic analysis to build the new expression.
2200 /// Subclasses may override this routine to provide different behavior.
2201 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2202 SourceLocation LAngleLoc,
2203 TypeSourceInfo *TInfo,
2204 SourceLocation RAngleLoc,
2205 SourceLocation LParenLoc,
2207 SourceLocation RParenLoc) {
2208 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2210 SourceRange(LAngleLoc, RAngleLoc),
2211 SourceRange(LParenLoc, RParenLoc));
2214 /// \brief Build a new C++ const_cast expression.
2216 /// By default, performs semantic analysis to build the new expression.
2217 /// Subclasses may override this routine to provide different behavior.
2218 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2219 SourceLocation LAngleLoc,
2220 TypeSourceInfo *TInfo,
2221 SourceLocation RAngleLoc,
2222 SourceLocation LParenLoc,
2224 SourceLocation RParenLoc) {
2225 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2227 SourceRange(LAngleLoc, RAngleLoc),
2228 SourceRange(LParenLoc, RParenLoc));
2231 /// \brief Build a new C++ functional-style cast expression.
2233 /// By default, performs semantic analysis to build the new expression.
2234 /// Subclasses may override this routine to provide different behavior.
2235 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2236 SourceLocation LParenLoc,
2238 SourceLocation RParenLoc) {
2239 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2240 MultiExprArg(&Sub, 1),
2244 /// \brief Build a new C++ typeid(type) expression.
2246 /// By default, performs semantic analysis to build the new expression.
2247 /// Subclasses may override this routine to provide different behavior.
2248 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2249 SourceLocation TypeidLoc,
2250 TypeSourceInfo *Operand,
2251 SourceLocation RParenLoc) {
2252 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2257 /// \brief Build a new C++ typeid(expr) expression.
2259 /// By default, performs semantic analysis to build the new expression.
2260 /// Subclasses may override this routine to provide different behavior.
2261 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2262 SourceLocation TypeidLoc,
2264 SourceLocation RParenLoc) {
2265 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2269 /// \brief Build a new C++ __uuidof(type) expression.
2271 /// By default, performs semantic analysis to build the new expression.
2272 /// Subclasses may override this routine to provide different behavior.
2273 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2274 SourceLocation TypeidLoc,
2275 TypeSourceInfo *Operand,
2276 SourceLocation RParenLoc) {
2277 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2281 /// \brief Build a new C++ __uuidof(expr) expression.
2283 /// By default, performs semantic analysis to build the new expression.
2284 /// Subclasses may override this routine to provide different behavior.
2285 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2286 SourceLocation TypeidLoc,
2288 SourceLocation RParenLoc) {
2289 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2293 /// \brief Build a new C++ "this" expression.
2295 /// By default, builds a new "this" expression without performing any
2296 /// semantic analysis. Subclasses may override this routine to provide
2297 /// different behavior.
2298 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2301 getSema().CheckCXXThisCapture(ThisLoc);
2302 return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
2305 /// \brief Build a new C++ throw expression.
2307 /// By default, performs semantic analysis to build the new expression.
2308 /// Subclasses may override this routine to provide different behavior.
2309 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2310 bool IsThrownVariableInScope) {
2311 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2314 /// \brief Build a new C++ default-argument expression.
2316 /// By default, builds a new default-argument expression, which does not
2317 /// require any semantic analysis. Subclasses may override this routine to
2318 /// provide different behavior.
2319 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
2320 ParmVarDecl *Param) {
2321 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
2324 /// \brief Build a new C++11 default-initialization expression.
2326 /// By default, builds a new default field initialization expression, which
2327 /// does not require any semantic analysis. Subclasses may override this
2328 /// routine to provide different behavior.
2329 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2331 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
2334 /// \brief Build a new C++ zero-initialization expression.
2336 /// By default, performs semantic analysis to build the new expression.
2337 /// Subclasses may override this routine to provide different behavior.
2338 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2339 SourceLocation LParenLoc,
2340 SourceLocation RParenLoc) {
2341 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
2345 /// \brief Build a new C++ "new" expression.
2347 /// By default, performs semantic analysis to build the new expression.
2348 /// Subclasses may override this routine to provide different behavior.
2349 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2351 SourceLocation PlacementLParen,
2352 MultiExprArg PlacementArgs,
2353 SourceLocation PlacementRParen,
2354 SourceRange TypeIdParens,
2355 QualType AllocatedType,
2356 TypeSourceInfo *AllocatedTypeInfo,
2358 SourceRange DirectInitRange,
2359 Expr *Initializer) {
2360 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2372 /// \brief Build a new C++ "delete" expression.
2374 /// By default, performs semantic analysis to build the new expression.
2375 /// Subclasses may override this routine to provide different behavior.
2376 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2377 bool IsGlobalDelete,
2380 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2384 /// \brief Build a new type trait expression.
2386 /// By default, performs semantic analysis to build the new expression.
2387 /// Subclasses may override this routine to provide different behavior.
2388 ExprResult RebuildTypeTrait(TypeTrait Trait,
2389 SourceLocation StartLoc,
2390 ArrayRef<TypeSourceInfo *> Args,
2391 SourceLocation RParenLoc) {
2392 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2395 /// \brief Build a new array type trait expression.
2397 /// By default, performs semantic analysis to build the new expression.
2398 /// Subclasses may override this routine to provide different behavior.
2399 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2400 SourceLocation StartLoc,
2401 TypeSourceInfo *TSInfo,
2403 SourceLocation RParenLoc) {
2404 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2407 /// \brief Build a new expression trait expression.
2409 /// By default, performs semantic analysis to build the new expression.
2410 /// Subclasses may override this routine to provide different behavior.
2411 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2412 SourceLocation StartLoc,
2414 SourceLocation RParenLoc) {
2415 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2418 /// \brief Build a new (previously unresolved) declaration reference
2421 /// By default, performs semantic analysis to build the new expression.
2422 /// Subclasses may override this routine to provide different behavior.
2423 ExprResult RebuildDependentScopeDeclRefExpr(
2424 NestedNameSpecifierLoc QualifierLoc,
2425 SourceLocation TemplateKWLoc,
2426 const DeclarationNameInfo &NameInfo,
2427 const TemplateArgumentListInfo *TemplateArgs,
2428 bool IsAddressOfOperand,
2429 TypeSourceInfo **RecoveryTSI) {
2431 SS.Adopt(QualifierLoc);
2433 if (TemplateArgs || TemplateKWLoc.isValid())
2434 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2437 return getSema().BuildQualifiedDeclarationNameExpr(
2438 SS, NameInfo, IsAddressOfOperand, RecoveryTSI);
2441 /// \brief Build a new template-id expression.
2443 /// By default, performs semantic analysis to build the new expression.
2444 /// Subclasses may override this routine to provide different behavior.
2445 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2446 SourceLocation TemplateKWLoc,
2449 const TemplateArgumentListInfo *TemplateArgs) {
2450 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2454 /// \brief Build a new object-construction expression.
2456 /// By default, performs semantic analysis to build the new expression.
2457 /// Subclasses may override this routine to provide different behavior.
2458 ExprResult RebuildCXXConstructExpr(QualType T,
2460 CXXConstructorDecl *Constructor,
2463 bool HadMultipleCandidates,
2464 bool ListInitialization,
2465 bool StdInitListInitialization,
2466 bool RequiresZeroInit,
2467 CXXConstructExpr::ConstructionKind ConstructKind,
2468 SourceRange ParenRange) {
2469 SmallVector<Expr*, 8> ConvertedArgs;
2470 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2474 return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
2476 HadMultipleCandidates,
2478 StdInitListInitialization,
2479 RequiresZeroInit, ConstructKind,
2483 /// \brief Build a new object-construction expression.
2485 /// By default, performs semantic analysis to build the new expression.
2486 /// Subclasses may override this routine to provide different behavior.
2487 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2488 SourceLocation LParenLoc,
2490 SourceLocation RParenLoc) {
2491 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2497 /// \brief Build a new object-construction expression.
2499 /// By default, performs semantic analysis to build the new expression.
2500 /// Subclasses may override this routine to provide different behavior.
2501 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2502 SourceLocation LParenLoc,
2504 SourceLocation RParenLoc) {
2505 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2511 /// \brief Build a new member reference expression.
2513 /// By default, performs semantic analysis to build the new expression.
2514 /// Subclasses may override this routine to provide different behavior.
2515 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2518 SourceLocation OperatorLoc,
2519 NestedNameSpecifierLoc QualifierLoc,
2520 SourceLocation TemplateKWLoc,
2521 NamedDecl *FirstQualifierInScope,
2522 const DeclarationNameInfo &MemberNameInfo,
2523 const TemplateArgumentListInfo *TemplateArgs) {
2525 SS.Adopt(QualifierLoc);
2527 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2528 OperatorLoc, IsArrow,
2530 FirstQualifierInScope,
2535 /// \brief Build a new member reference expression.
2537 /// By default, performs semantic analysis to build the new expression.
2538 /// Subclasses may override this routine to provide different behavior.
2539 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2540 SourceLocation OperatorLoc,
2542 NestedNameSpecifierLoc QualifierLoc,
2543 SourceLocation TemplateKWLoc,
2544 NamedDecl *FirstQualifierInScope,
2546 const TemplateArgumentListInfo *TemplateArgs) {
2548 SS.Adopt(QualifierLoc);
2550 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2551 OperatorLoc, IsArrow,
2553 FirstQualifierInScope,
2557 /// \brief Build a new noexcept expression.
2559 /// By default, performs semantic analysis to build the new expression.
2560 /// Subclasses may override this routine to provide different behavior.
2561 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2562 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2565 /// \brief Build a new expression to compute the length of a parameter pack.
2566 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
2567 SourceLocation PackLoc,
2568 SourceLocation RParenLoc,
2569 Optional<unsigned> Length) {
2571 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2572 OperatorLoc, Pack, PackLoc,
2573 RParenLoc, *Length);
2575 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2576 OperatorLoc, Pack, PackLoc,
2580 /// \brief Build a new Objective-C boxed expression.
2582 /// By default, performs semantic analysis to build the new expression.
2583 /// Subclasses may override this routine to provide different behavior.
2584 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
2585 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
2588 /// \brief Build a new Objective-C array literal.
2590 /// By default, performs semantic analysis to build the new expression.
2591 /// Subclasses may override this routine to provide different behavior.
2592 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
2593 Expr **Elements, unsigned NumElements) {
2594 return getSema().BuildObjCArrayLiteral(Range,
2595 MultiExprArg(Elements, NumElements));
2598 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
2599 Expr *Base, Expr *Key,
2600 ObjCMethodDecl *getterMethod,
2601 ObjCMethodDecl *setterMethod) {
2602 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
2603 getterMethod, setterMethod);
2606 /// \brief Build a new Objective-C dictionary literal.
2608 /// By default, performs semantic analysis to build the new expression.
2609 /// Subclasses may override this routine to provide different behavior.
2610 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
2611 ObjCDictionaryElement *Elements,
2612 unsigned NumElements) {
2613 return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElements);
2616 /// \brief Build a new Objective-C \@encode expression.
2618 /// By default, performs semantic analysis to build the new expression.
2619 /// Subclasses may override this routine to provide different behavior.
2620 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2621 TypeSourceInfo *EncodeTypeInfo,
2622 SourceLocation RParenLoc) {
2623 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
2626 /// \brief Build a new Objective-C class message.
2627 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2629 ArrayRef<SourceLocation> SelectorLocs,
2630 ObjCMethodDecl *Method,
2631 SourceLocation LBracLoc,
2633 SourceLocation RBracLoc) {
2634 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
2635 ReceiverTypeInfo->getType(),
2636 /*SuperLoc=*/SourceLocation(),
2637 Sel, Method, LBracLoc, SelectorLocs,
2641 /// \brief Build a new Objective-C instance message.
2642 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
2644 ArrayRef<SourceLocation> SelectorLocs,
2645 ObjCMethodDecl *Method,
2646 SourceLocation LBracLoc,
2648 SourceLocation RBracLoc) {
2649 return SemaRef.BuildInstanceMessage(Receiver,
2650 Receiver->getType(),
2651 /*SuperLoc=*/SourceLocation(),
2652 Sel, Method, LBracLoc, SelectorLocs,
2656 /// \brief Build a new Objective-C instance/class message to 'super'.
2657 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
2659 ArrayRef<SourceLocation> SelectorLocs,
2660 ObjCMethodDecl *Method,
2661 SourceLocation LBracLoc,
2663 SourceLocation RBracLoc) {
2664 ObjCInterfaceDecl *Class = Method->getClassInterface();
2665 QualType ReceiverTy = SemaRef.Context.getObjCInterfaceType(Class);
2667 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
2670 Sel, Method, LBracLoc, SelectorLocs,
2672 : SemaRef.BuildClassMessage(nullptr,
2675 Sel, Method, LBracLoc, SelectorLocs,
2681 /// \brief Build a new Objective-C ivar reference expression.
2683 /// By default, performs semantic analysis to build the new expression.
2684 /// Subclasses may override this routine to provide different behavior.
2685 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
2686 SourceLocation IvarLoc,
2687 bool IsArrow, bool IsFreeIvar) {
2688 // FIXME: We lose track of the IsFreeIvar bit.
2690 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
2691 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2692 /*FIXME:*/IvarLoc, IsArrow,
2693 SS, SourceLocation(),
2694 /*FirstQualifierInScope=*/nullptr,
2696 /*TemplateArgs=*/nullptr);
2699 /// \brief Build a new Objective-C property reference expression.
2701 /// By default, performs semantic analysis to build the new expression.
2702 /// Subclasses may override this routine to provide different behavior.
2703 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
2704 ObjCPropertyDecl *Property,
2705 SourceLocation PropertyLoc) {
2707 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
2708 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2709 /*FIXME:*/PropertyLoc,
2711 SS, SourceLocation(),
2712 /*FirstQualifierInScope=*/nullptr,
2714 /*TemplateArgs=*/nullptr);
2717 /// \brief Build a new Objective-C property reference expression.
2719 /// By default, performs semantic analysis to build the new expression.
2720 /// Subclasses may override this routine to provide different behavior.
2721 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
2722 ObjCMethodDecl *Getter,
2723 ObjCMethodDecl *Setter,
2724 SourceLocation PropertyLoc) {
2725 // Since these expressions can only be value-dependent, we do not
2726 // need to perform semantic analysis again.
2728 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
2729 VK_LValue, OK_ObjCProperty,
2730 PropertyLoc, Base));
2733 /// \brief Build a new Objective-C "isa" expression.
2735 /// By default, performs semantic analysis to build the new expression.
2736 /// Subclasses may override this routine to provide different behavior.
2737 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
2738 SourceLocation OpLoc, bool IsArrow) {
2740 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
2741 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2743 SS, SourceLocation(),
2744 /*FirstQualifierInScope=*/nullptr,
2746 /*TemplateArgs=*/nullptr);
2749 /// \brief Build a new shuffle vector expression.
2751 /// By default, performs semantic analysis to build the new expression.
2752 /// Subclasses may override this routine to provide different behavior.
2753 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
2754 MultiExprArg SubExprs,
2755 SourceLocation RParenLoc) {
2756 // Find the declaration for __builtin_shufflevector
2757 const IdentifierInfo &Name
2758 = SemaRef.Context.Idents.get("__builtin_shufflevector");
2759 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
2760 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
2761 assert(!Lookup.empty() && "No __builtin_shufflevector?");
2763 // Build a reference to the __builtin_shufflevector builtin
2764 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
2765 Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
2766 SemaRef.Context.BuiltinFnTy,
2767 VK_RValue, BuiltinLoc);
2768 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
2769 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
2770 CK_BuiltinFnToFnPtr).get();
2772 // Build the CallExpr
2773 ExprResult TheCall = new (SemaRef.Context) CallExpr(
2774 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
2775 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
2777 // Type-check the __builtin_shufflevector expression.
2778 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
2781 /// \brief Build a new convert vector expression.
2782 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
2783 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
2784 SourceLocation RParenLoc) {
2785 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
2786 BuiltinLoc, RParenLoc);
2789 /// \brief Build a new template argument pack expansion.
2791 /// By default, performs semantic analysis to build a new pack expansion
2792 /// for a template argument. Subclasses may override this routine to provide
2793 /// different behavior.
2794 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
2795 SourceLocation EllipsisLoc,
2796 Optional<unsigned> NumExpansions) {
2797 switch (Pattern.getArgument().getKind()) {
2798 case TemplateArgument::Expression: {
2800 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
2801 EllipsisLoc, NumExpansions);
2802 if (Result.isInvalid())
2803 return TemplateArgumentLoc();
2805 return TemplateArgumentLoc(Result.get(), Result.get());
2808 case TemplateArgument::Template:
2809 return TemplateArgumentLoc(TemplateArgument(
2810 Pattern.getArgument().getAsTemplate(),
2812 Pattern.getTemplateQualifierLoc(),
2813 Pattern.getTemplateNameLoc(),
2816 case TemplateArgument::Null:
2817 case TemplateArgument::Integral:
2818 case TemplateArgument::Declaration:
2819 case TemplateArgument::Pack:
2820 case TemplateArgument::TemplateExpansion:
2821 case TemplateArgument::NullPtr:
2822 llvm_unreachable("Pack expansion pattern has no parameter packs");
2824 case TemplateArgument::Type:
2825 if (TypeSourceInfo *Expansion
2826 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
2829 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
2834 return TemplateArgumentLoc();
2837 /// \brief Build a new expression pack expansion.
2839 /// By default, performs semantic analysis to build a new pack expansion
2840 /// for an expression. Subclasses may override this routine to provide
2841 /// different behavior.
2842 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
2843 Optional<unsigned> NumExpansions) {
2844 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
2847 /// \brief Build a new C++1z fold-expression.
2849 /// By default, performs semantic analysis in order to build a new fold
2851 ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
2852 BinaryOperatorKind Operator,
2853 SourceLocation EllipsisLoc, Expr *RHS,
2854 SourceLocation RParenLoc) {
2855 return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
2859 /// \brief Build an empty C++1z fold-expression with the given operator.
2861 /// By default, produces the fallback value for the fold-expression, or
2862 /// produce an error if there is no fallback value.
2863 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
2864 BinaryOperatorKind Operator) {
2865 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
2868 /// \brief Build a new atomic operation expression.
2870 /// By default, performs semantic analysis to build the new expression.
2871 /// Subclasses may override this routine to provide different behavior.
2872 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
2873 MultiExprArg SubExprs,
2875 AtomicExpr::AtomicOp Op,
2876 SourceLocation RParenLoc) {
2877 // Just create the expression; there is not any interesting semantic
2878 // analysis here because we can't actually build an AtomicExpr until
2879 // we are sure it is semantically sound.
2880 return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
2885 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
2886 QualType ObjectType,
2887 NamedDecl *FirstQualifierInScope,
2890 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
2891 QualType ObjectType,
2892 NamedDecl *FirstQualifierInScope,
2895 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
2896 NamedDecl *FirstQualifierInScope,
2900 template<typename Derived>
2901 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
2905 switch (S->getStmtClass()) {
2906 case Stmt::NoStmtClass: break;
2908 // Transform individual statement nodes
2909 #define STMT(Node, Parent) \
2910 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
2911 #define ABSTRACT_STMT(Node)
2912 #define EXPR(Node, Parent)
2913 #include "clang/AST/StmtNodes.inc"
2915 // Transform expressions by calling TransformExpr.
2916 #define STMT(Node, Parent)
2917 #define ABSTRACT_STMT(Stmt)
2918 #define EXPR(Node, Parent) case Stmt::Node##Class:
2919 #include "clang/AST/StmtNodes.inc"
2921 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
2925 return getSema().ActOnExprStmt(E);
2932 template<typename Derived>
2933 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
2937 switch (S->getClauseKind()) {
2939 // Transform individual clause nodes
2940 #define OPENMP_CLAUSE(Name, Class) \
2941 case OMPC_ ## Name : \
2942 return getDerived().Transform ## Class(cast<Class>(S));
2943 #include "clang/Basic/OpenMPKinds.def"
2950 template<typename Derived>
2951 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
2955 switch (E->getStmtClass()) {
2956 case Stmt::NoStmtClass: break;
2957 #define STMT(Node, Parent) case Stmt::Node##Class: break;
2958 #define ABSTRACT_STMT(Stmt)
2959 #define EXPR(Node, Parent) \
2960 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
2961 #include "clang/AST/StmtNodes.inc"
2967 template<typename Derived>
2968 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
2970 // Initializers are instantiated like expressions, except that various outer
2971 // layers are stripped.
2975 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
2976 Init = ExprTemp->getSubExpr();
2978 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
2979 Init = MTE->GetTemporaryExpr();
2981 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
2982 Init = Binder->getSubExpr();
2984 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
2985 Init = ICE->getSubExprAsWritten();
2987 if (CXXStdInitializerListExpr *ILE =
2988 dyn_cast<CXXStdInitializerListExpr>(Init))
2989 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
2991 // If this is copy-initialization, we only need to reconstruct
2992 // InitListExprs. Other forms of copy-initialization will be a no-op if
2993 // the initializer is already the right type.
2994 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
2995 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
2996 return getDerived().TransformExpr(Init);
2998 // Revert value-initialization back to empty parens.
2999 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3000 SourceRange Parens = VIE->getSourceRange();
3001 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3005 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3006 if (isa<ImplicitValueInitExpr>(Init))
3007 return getDerived().RebuildParenListExpr(SourceLocation(), None,
3010 // Revert initialization by constructor back to a parenthesized or braced list
3011 // of expressions. Any other form of initializer can just be reused directly.
3012 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3013 return getDerived().TransformExpr(Init);
3015 // If the initialization implicitly converted an initializer list to a
3016 // std::initializer_list object, unwrap the std::initializer_list too.
3017 if (Construct && Construct->isStdInitListInitialization())
3018 return TransformInitializer(Construct->getArg(0), NotCopyInit);
3020 SmallVector<Expr*, 8> NewArgs;
3021 bool ArgChanged = false;
3022 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3023 /*IsCall*/true, NewArgs, &ArgChanged))
3026 // If this was list initialization, revert to list form.
3027 if (Construct->isListInitialization())
3028 return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
3029 Construct->getLocEnd(),
3030 Construct->getType());
3032 // Build a ParenListExpr to represent anything else.
3033 SourceRange Parens = Construct->getParenOrBraceRange();
3034 if (Parens.isInvalid()) {
3035 // This was a variable declaration's initialization for which no initializer
3037 assert(NewArgs.empty() &&
3038 "no parens or braces but have direct init with arguments?");
3041 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3045 template<typename Derived>
3046 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
3049 SmallVectorImpl<Expr *> &Outputs,
3051 for (unsigned I = 0; I != NumInputs; ++I) {
3052 // If requested, drop call arguments that need to be dropped.
3053 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3060 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3061 Expr *Pattern = Expansion->getPattern();
3063 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3064 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3065 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3067 // Determine whether the set of unexpanded parameter packs can and should
3070 bool RetainExpansion = false;
3071 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3072 Optional<unsigned> NumExpansions = OrigNumExpansions;
3073 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3074 Pattern->getSourceRange(),
3076 Expand, RetainExpansion,
3081 // The transform has determined that we should perform a simple
3082 // transformation on the pack expansion, producing another pack
3084 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3085 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3086 if (OutPattern.isInvalid())
3089 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3090 Expansion->getEllipsisLoc(),
3092 if (Out.isInvalid())
3097 Outputs.push_back(Out.get());
3101 // Record right away that the argument was changed. This needs
3102 // to happen even if the array expands to nothing.
3103 if (ArgChanged) *ArgChanged = true;
3105 // The transform has determined that we should perform an elementwise
3106 // expansion of the pattern. Do so.
3107 for (unsigned I = 0; I != *NumExpansions; ++I) {
3108 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3109 ExprResult Out = getDerived().TransformExpr(Pattern);
3110 if (Out.isInvalid())
3113 // FIXME: Can this happen? We should not try to expand the pack
3115 if (Out.get()->containsUnexpandedParameterPack()) {
3116 Out = getDerived().RebuildPackExpansion(
3117 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3118 if (Out.isInvalid())
3122 Outputs.push_back(Out.get());
3125 // If we're supposed to retain a pack expansion, do so by temporarily
3126 // forgetting the partially-substituted parameter pack.
3127 if (RetainExpansion) {
3128 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3130 ExprResult Out = getDerived().TransformExpr(Pattern);
3131 if (Out.isInvalid())
3134 Out = getDerived().RebuildPackExpansion(
3135 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3136 if (Out.isInvalid())
3139 Outputs.push_back(Out.get());
3146 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3147 : getDerived().TransformExpr(Inputs[I]);
3148 if (Result.isInvalid())
3151 if (Result.get() != Inputs[I] && ArgChanged)
3154 Outputs.push_back(Result.get());
3160 template<typename Derived>
3161 NestedNameSpecifierLoc
3162 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3163 NestedNameSpecifierLoc NNS,
3164 QualType ObjectType,
3165 NamedDecl *FirstQualifierInScope) {
3166 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3167 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3168 Qualifier = Qualifier.getPrefix())
3169 Qualifiers.push_back(Qualifier);
3172 while (!Qualifiers.empty()) {
3173 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3174 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3176 switch (QNNS->getKind()) {
3177 case NestedNameSpecifier::Identifier:
3178 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr,
3179 *QNNS->getAsIdentifier(),
3180 Q.getLocalBeginLoc(),
3182 ObjectType, false, SS,
3183 FirstQualifierInScope, false))
3184 return NestedNameSpecifierLoc();
3188 case NestedNameSpecifier::Namespace: {
3190 = cast_or_null<NamespaceDecl>(
3191 getDerived().TransformDecl(
3192 Q.getLocalBeginLoc(),
3193 QNNS->getAsNamespace()));
3194 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3198 case NestedNameSpecifier::NamespaceAlias: {
3199 NamespaceAliasDecl *Alias
3200 = cast_or_null<NamespaceAliasDecl>(
3201 getDerived().TransformDecl(Q.getLocalBeginLoc(),
3202 QNNS->getAsNamespaceAlias()));
3203 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3204 Q.getLocalEndLoc());
3208 case NestedNameSpecifier::Global:
3209 // There is no meaningful transformation that one could perform on the
3211 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3214 case NestedNameSpecifier::Super: {
3216 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3217 SourceLocation(), QNNS->getAsRecordDecl()));
3218 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3222 case NestedNameSpecifier::TypeSpecWithTemplate:
3223 case NestedNameSpecifier::TypeSpec: {
3224 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3225 FirstQualifierInScope, SS);
3228 return NestedNameSpecifierLoc();
3230 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3231 (SemaRef.getLangOpts().CPlusPlus11 &&
3232 TL.getType()->isEnumeralType())) {
3233 assert(!TL.getType().hasLocalQualifiers() &&
3234 "Can't get cv-qualifiers here");
3235 if (TL.getType()->isEnumeralType())
3236 SemaRef.Diag(TL.getBeginLoc(),
3237 diag::warn_cxx98_compat_enum_nested_name_spec);
3238 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3239 Q.getLocalEndLoc());
3242 // If the nested-name-specifier is an invalid type def, don't emit an
3243 // error because a previous error should have already been emitted.
3244 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3245 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3246 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3247 << TL.getType() << SS.getRange();
3249 return NestedNameSpecifierLoc();
3253 // The qualifier-in-scope and object type only apply to the leftmost entity.
3254 FirstQualifierInScope = nullptr;
3255 ObjectType = QualType();
3258 // Don't rebuild the nested-name-specifier if we don't have to.
3259 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3260 !getDerived().AlwaysRebuild())
3263 // If we can re-use the source-location data from the original
3264 // nested-name-specifier, do so.
3265 if (SS.location_size() == NNS.getDataLength() &&
3266 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3267 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3269 // Allocate new nested-name-specifier location information.
3270 return SS.getWithLocInContext(SemaRef.Context);
3273 template<typename Derived>
3275 TreeTransform<Derived>
3276 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3277 DeclarationName Name = NameInfo.getName();
3279 return DeclarationNameInfo();
3281 switch (Name.getNameKind()) {
3282 case DeclarationName::Identifier:
3283 case DeclarationName::ObjCZeroArgSelector:
3284 case DeclarationName::ObjCOneArgSelector:
3285 case DeclarationName::ObjCMultiArgSelector:
3286 case DeclarationName::CXXOperatorName:
3287 case DeclarationName::CXXLiteralOperatorName:
3288 case DeclarationName::CXXUsingDirective:
3291 case DeclarationName::CXXConstructorName:
3292 case DeclarationName::CXXDestructorName:
3293 case DeclarationName::CXXConversionFunctionName: {
3294 TypeSourceInfo *NewTInfo;
3295 CanQualType NewCanTy;
3296 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3297 NewTInfo = getDerived().TransformType(OldTInfo);
3299 return DeclarationNameInfo();
3300 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3304 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3305 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3307 return DeclarationNameInfo();
3308 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3311 DeclarationName NewName
3312 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3314 DeclarationNameInfo NewNameInfo(NameInfo);
3315 NewNameInfo.setName(NewName);
3316 NewNameInfo.setNamedTypeInfo(NewTInfo);
3321 llvm_unreachable("Unknown name kind.");
3324 template<typename Derived>
3326 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3328 SourceLocation NameLoc,
3329 QualType ObjectType,
3330 NamedDecl *FirstQualifierInScope) {
3331 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3332 TemplateDecl *Template = QTN->getTemplateDecl();
3333 assert(Template && "qualified template name must refer to a template");
3335 TemplateDecl *TransTemplate
3336 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3339 return TemplateName();
3341 if (!getDerived().AlwaysRebuild() &&
3342 SS.getScopeRep() == QTN->getQualifier() &&
3343 TransTemplate == Template)
3346 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3350 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3351 if (SS.getScopeRep()) {
3352 // These apply to the scope specifier, not the template.
3353 ObjectType = QualType();
3354 FirstQualifierInScope = nullptr;
3357 if (!getDerived().AlwaysRebuild() &&
3358 SS.getScopeRep() == DTN->getQualifier() &&
3359 ObjectType.isNull())
3362 if (DTN->isIdentifier()) {
3363 return getDerived().RebuildTemplateName(SS,
3364 *DTN->getIdentifier(),
3367 FirstQualifierInScope);
3370 return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
3374 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3375 TemplateDecl *TransTemplate
3376 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3379 return TemplateName();
3381 if (!getDerived().AlwaysRebuild() &&
3382 TransTemplate == Template)
3385 return TemplateName(TransTemplate);
3388 if (SubstTemplateTemplateParmPackStorage *SubstPack
3389 = Name.getAsSubstTemplateTemplateParmPack()) {
3390 TemplateTemplateParmDecl *TransParam
3391 = cast_or_null<TemplateTemplateParmDecl>(
3392 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3394 return TemplateName();
3396 if (!getDerived().AlwaysRebuild() &&
3397 TransParam == SubstPack->getParameterPack())
3400 return getDerived().RebuildTemplateName(TransParam,
3401 SubstPack->getArgumentPack());
3404 // These should be getting filtered out before they reach the AST.
3405 llvm_unreachable("overloaded function decl survived to here");
3408 template<typename Derived>
3409 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3410 const TemplateArgument &Arg,
3411 TemplateArgumentLoc &Output) {
3412 SourceLocation Loc = getDerived().getBaseLocation();
3413 switch (Arg.getKind()) {
3414 case TemplateArgument::Null:
3415 llvm_unreachable("null template argument in TreeTransform");
3418 case TemplateArgument::Type:
3419 Output = TemplateArgumentLoc(Arg,
3420 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3424 case TemplateArgument::Template:
3425 case TemplateArgument::TemplateExpansion: {
3426 NestedNameSpecifierLocBuilder Builder;
3427 TemplateName Template = Arg.getAsTemplate();
3428 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3429 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3430 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3431 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3433 if (Arg.getKind() == TemplateArgument::Template)
3434 Output = TemplateArgumentLoc(Arg,
3435 Builder.getWithLocInContext(SemaRef.Context),
3438 Output = TemplateArgumentLoc(Arg,
3439 Builder.getWithLocInContext(SemaRef.Context),
3445 case TemplateArgument::Expression:
3446 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3449 case TemplateArgument::Declaration:
3450 case TemplateArgument::Integral:
3451 case TemplateArgument::Pack:
3452 case TemplateArgument::NullPtr:
3453 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3458 template<typename Derived>
3459 bool TreeTransform<Derived>::TransformTemplateArgument(
3460 const TemplateArgumentLoc &Input,
3461 TemplateArgumentLoc &Output) {
3462 const TemplateArgument &Arg = Input.getArgument();
3463 switch (Arg.getKind()) {
3464 case TemplateArgument::Null:
3465 case TemplateArgument::Integral:
3466 case TemplateArgument::Pack:
3467 case TemplateArgument::Declaration:
3468 case TemplateArgument::NullPtr:
3469 llvm_unreachable("Unexpected TemplateArgument");
3471 case TemplateArgument::Type: {
3472 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3474 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3476 DI = getDerived().TransformType(DI);
3477 if (!DI) return true;
3479 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3483 case TemplateArgument::Template: {
3484 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3486 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3492 SS.Adopt(QualifierLoc);
3493 TemplateName Template
3494 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3495 Input.getTemplateNameLoc());
3496 if (Template.isNull())
3499 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3500 Input.getTemplateNameLoc());
3504 case TemplateArgument::TemplateExpansion:
3505 llvm_unreachable("Caller should expand pack expansions");
3507 case TemplateArgument::Expression: {
3508 // Template argument expressions are constant expressions.
3509 EnterExpressionEvaluationContext Unevaluated(getSema(),
3510 Sema::ConstantEvaluated);
3512 Expr *InputExpr = Input.getSourceExpression();
3513 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
3515 ExprResult E = getDerived().TransformExpr(InputExpr);
3516 E = SemaRef.ActOnConstantExpression(E);
3517 if (E.isInvalid()) return true;
3518 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
3523 // Work around bogus GCC warning
3527 /// \brief Iterator adaptor that invents template argument location information
3528 /// for each of the template arguments in its underlying iterator.
3529 template<typename Derived, typename InputIterator>
3530 class TemplateArgumentLocInventIterator {
3531 TreeTransform<Derived> &Self;
3535 typedef TemplateArgumentLoc value_type;
3536 typedef TemplateArgumentLoc reference;
3537 typedef typename std::iterator_traits<InputIterator>::difference_type
3539 typedef std::input_iterator_tag iterator_category;
3542 TemplateArgumentLoc Arg;
3545 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
3547 const TemplateArgumentLoc *operator->() const { return &Arg; }
3550 TemplateArgumentLocInventIterator() { }
3552 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
3554 : Self(Self), Iter(Iter) { }
3556 TemplateArgumentLocInventIterator &operator++() {
3561 TemplateArgumentLocInventIterator operator++(int) {
3562 TemplateArgumentLocInventIterator Old(*this);
3567 reference operator*() const {
3568 TemplateArgumentLoc Result;
3569 Self.InventTemplateArgumentLoc(*Iter, Result);
3573 pointer operator->() const { return pointer(**this); }
3575 friend bool operator==(const TemplateArgumentLocInventIterator &X,
3576 const TemplateArgumentLocInventIterator &Y) {
3577 return X.Iter == Y.Iter;
3580 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
3581 const TemplateArgumentLocInventIterator &Y) {
3582 return X.Iter != Y.Iter;
3586 template<typename Derived>
3587 template<typename InputIterator>
3588 bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
3590 TemplateArgumentListInfo &Outputs) {
3591 for (; First != Last; ++First) {
3592 TemplateArgumentLoc Out;
3593 TemplateArgumentLoc In = *First;
3595 if (In.getArgument().getKind() == TemplateArgument::Pack) {
3596 // Unpack argument packs, which we translate them into separate
3598 // FIXME: We could do much better if we could guarantee that the
3599 // TemplateArgumentLocInfo for the pack expansion would be usable for
3600 // all of the template arguments in the argument pack.
3601 typedef TemplateArgumentLocInventIterator<Derived,
3602 TemplateArgument::pack_iterator>
3604 if (TransformTemplateArguments(PackLocIterator(*this,
3605 In.getArgument().pack_begin()),
3606 PackLocIterator(*this,
3607 In.getArgument().pack_end()),
3614 if (In.getArgument().isPackExpansion()) {
3615 // We have a pack expansion, for which we will be substituting into
3617 SourceLocation Ellipsis;
3618 Optional<unsigned> OrigNumExpansions;
3619 TemplateArgumentLoc Pattern
3620 = getSema().getTemplateArgumentPackExpansionPattern(
3621 In, Ellipsis, OrigNumExpansions);
3623 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3624 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3625 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3627 // Determine whether the set of unexpanded parameter packs can and should
3630 bool RetainExpansion = false;
3631 Optional<unsigned> NumExpansions = OrigNumExpansions;
3632 if (getDerived().TryExpandParameterPacks(Ellipsis,
3633 Pattern.getSourceRange(),
3641 // The transform has determined that we should perform a simple
3642 // transformation on the pack expansion, producing another pack
3644 TemplateArgumentLoc OutPattern;
3645 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3646 if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
3649 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
3651 if (Out.getArgument().isNull())
3654 Outputs.addArgument(Out);
3658 // The transform has determined that we should perform an elementwise
3659 // expansion of the pattern. Do so.
3660 for (unsigned I = 0; I != *NumExpansions; ++I) {
3661 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3663 if (getDerived().TransformTemplateArgument(Pattern, Out))
3666 if (Out.getArgument().containsUnexpandedParameterPack()) {
3667 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3669 if (Out.getArgument().isNull())
3673 Outputs.addArgument(Out);
3676 // If we're supposed to retain a pack expansion, do so by temporarily
3677 // forgetting the partially-substituted parameter pack.
3678 if (RetainExpansion) {
3679 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3681 if (getDerived().TransformTemplateArgument(Pattern, Out))
3684 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3686 if (Out.getArgument().isNull())
3689 Outputs.addArgument(Out);
3696 if (getDerived().TransformTemplateArgument(In, Out))
3699 Outputs.addArgument(Out);
3706 //===----------------------------------------------------------------------===//
3707 // Type transformation
3708 //===----------------------------------------------------------------------===//
3710 template<typename Derived>
3711 QualType TreeTransform<Derived>::TransformType(QualType T) {
3712 if (getDerived().AlreadyTransformed(T))
3715 // Temporary workaround. All of these transformations should
3716 // eventually turn into transformations on TypeLocs.
3717 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
3718 getDerived().getBaseLocation());
3720 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
3725 return NewDI->getType();
3728 template<typename Derived>
3729 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
3730 // Refine the base location to the type's location.
3731 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
3732 getDerived().getBaseEntity());
3733 if (getDerived().AlreadyTransformed(DI->getType()))
3738 TypeLoc TL = DI->getTypeLoc();
3739 TLB.reserve(TL.getFullDataSize());
3741 QualType Result = getDerived().TransformType(TLB, TL);
3742 if (Result.isNull())
3745 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3748 template<typename Derived>
3750 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
3751 switch (T.getTypeLocClass()) {
3752 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3753 #define TYPELOC(CLASS, PARENT) \
3754 case TypeLoc::CLASS: \
3755 return getDerived().Transform##CLASS##Type(TLB, \
3756 T.castAs<CLASS##TypeLoc>());
3757 #include "clang/AST/TypeLocNodes.def"
3760 llvm_unreachable("unhandled type loc!");
3763 /// FIXME: By default, this routine adds type qualifiers only to types
3764 /// that can have qualifiers, and silently suppresses those qualifiers
3765 /// that are not permitted (e.g., qualifiers on reference or function
3766 /// types). This is the right thing for template instantiation, but
3767 /// probably not for other clients.
3768 template<typename Derived>
3770 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
3771 QualifiedTypeLoc T) {
3772 Qualifiers Quals = T.getType().getLocalQualifiers();
3774 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
3775 if (Result.isNull())
3778 // Silently suppress qualifiers if the result type can't be qualified.
3779 // FIXME: this is the right thing for template instantiation, but
3780 // probably not for other clients.
3781 if (Result->isFunctionType() || Result->isReferenceType())
3784 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
3786 if (Quals.hasObjCLifetime()) {
3787 if (!Result->isObjCLifetimeType() && !Result->isDependentType())
3788 Quals.removeObjCLifetime();
3789 else if (Result.getObjCLifetime()) {
3791 // A lifetime qualifier applied to a substituted template parameter
3792 // overrides the lifetime qualifier from the template argument.
3793 const AutoType *AutoTy;
3794 if (const SubstTemplateTypeParmType *SubstTypeParam
3795 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
3796 QualType Replacement = SubstTypeParam->getReplacementType();
3797 Qualifiers Qs = Replacement.getQualifiers();
3798 Qs.removeObjCLifetime();
3800 = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
3802 Result = SemaRef.Context.getSubstTemplateTypeParmType(
3803 SubstTypeParam->getReplacedParameter(),
3805 TLB.TypeWasModifiedSafely(Result);
3806 } else if ((AutoTy = dyn_cast<AutoType>(Result)) && AutoTy->isDeduced()) {
3807 // 'auto' types behave the same way as template parameters.
3808 QualType Deduced = AutoTy->getDeducedType();
3809 Qualifiers Qs = Deduced.getQualifiers();
3810 Qs.removeObjCLifetime();
3811 Deduced = SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(),
3813 Result = SemaRef.Context.getAutoType(Deduced, AutoTy->isDecltypeAuto(),
3814 AutoTy->isDependentType());
3815 TLB.TypeWasModifiedSafely(Result);
3817 // Otherwise, complain about the addition of a qualifier to an
3818 // already-qualified type.
3819 SourceRange R = T.getUnqualifiedLoc().getSourceRange();
3820 SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
3823 Quals.removeObjCLifetime();
3827 if (!Quals.empty()) {
3828 Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
3829 // BuildQualifiedType might not add qualifiers if they are invalid.
3830 if (Result.hasLocalQualifiers())
3831 TLB.push<QualifiedTypeLoc>(Result);
3832 // No location information to preserve.
3838 template<typename Derived>
3840 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
3841 QualType ObjectType,
3842 NamedDecl *UnqualLookup,
3844 if (getDerived().AlreadyTransformed(TL.getType()))
3847 TypeSourceInfo *TSI =
3848 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
3850 return TSI->getTypeLoc();
3854 template<typename Derived>
3856 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3857 QualType ObjectType,
3858 NamedDecl *UnqualLookup,
3860 if (getDerived().AlreadyTransformed(TSInfo->getType()))
3863 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
3867 template <typename Derived>
3868 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
3869 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
3871 QualType T = TL.getType();
3872 assert(!getDerived().AlreadyTransformed(T));
3877 if (isa<TemplateSpecializationType>(T)) {
3878 TemplateSpecializationTypeLoc SpecTL =
3879 TL.castAs<TemplateSpecializationTypeLoc>();
3881 TemplateName Template
3882 = getDerived().TransformTemplateName(SS,
3883 SpecTL.getTypePtr()->getTemplateName(),
3884 SpecTL.getTemplateNameLoc(),
3885 ObjectType, UnqualLookup);
3886 if (Template.isNull())
3889 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
3891 } else if (isa<DependentTemplateSpecializationType>(T)) {
3892 DependentTemplateSpecializationTypeLoc SpecTL =
3893 TL.castAs<DependentTemplateSpecializationTypeLoc>();
3895 TemplateName Template
3896 = getDerived().RebuildTemplateName(SS,
3897 *SpecTL.getTypePtr()->getIdentifier(),
3898 SpecTL.getTemplateNameLoc(),
3899 ObjectType, UnqualLookup);
3900 if (Template.isNull())
3903 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
3908 // Nothing special needs to be done for these.
3909 Result = getDerived().TransformType(TLB, TL);
3912 if (Result.isNull())
3915 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3918 template <class TyLoc> static inline
3919 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
3920 TyLoc NewT = TLB.push<TyLoc>(T.getType());
3921 NewT.setNameLoc(T.getNameLoc());
3925 template<typename Derived>
3926 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
3928 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
3929 NewT.setBuiltinLoc(T.getBuiltinLoc());
3930 if (T.needsExtraLocalData())
3931 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
3935 template<typename Derived>
3936 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
3939 return TransformTypeSpecType(TLB, T);
3942 template <typename Derived>
3943 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
3944 AdjustedTypeLoc TL) {
3945 // Adjustments applied during transformation are handled elsewhere.
3946 return getDerived().TransformType(TLB, TL.getOriginalLoc());
3949 template<typename Derived>
3950 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
3951 DecayedTypeLoc TL) {
3952 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
3953 if (OriginalType.isNull())
3956 QualType Result = TL.getType();
3957 if (getDerived().AlwaysRebuild() ||
3958 OriginalType != TL.getOriginalLoc().getType())
3959 Result = SemaRef.Context.getDecayedType(OriginalType);
3960 TLB.push<DecayedTypeLoc>(Result);
3961 // Nothing to set for DecayedTypeLoc.
3965 template<typename Derived>
3966 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
3967 PointerTypeLoc TL) {
3968 QualType PointeeType
3969 = getDerived().TransformType(TLB, TL.getPointeeLoc());
3970 if (PointeeType.isNull())
3973 QualType Result = TL.getType();
3974 if (PointeeType->getAs<ObjCObjectType>()) {
3975 // A dependent pointer type 'T *' has is being transformed such
3976 // that an Objective-C class type is being replaced for 'T'. The
3977 // resulting pointer type is an ObjCObjectPointerType, not a
3979 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
3981 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
3982 NewT.setStarLoc(TL.getStarLoc());
3986 if (getDerived().AlwaysRebuild() ||
3987 PointeeType != TL.getPointeeLoc().getType()) {
3988 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
3989 if (Result.isNull())
3993 // Objective-C ARC can add lifetime qualifiers to the type that we're
3995 TLB.TypeWasModifiedSafely(Result->getPointeeType());
3997 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
3998 NewT.setSigilLoc(TL.getSigilLoc());
4002 template<typename Derived>
4004 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4005 BlockPointerTypeLoc TL) {
4006 QualType PointeeType
4007 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4008 if (PointeeType.isNull())
4011 QualType Result = TL.getType();
4012 if (getDerived().AlwaysRebuild() ||
4013 PointeeType != TL.getPointeeLoc().getType()) {
4014 Result = getDerived().RebuildBlockPointerType(PointeeType,
4016 if (Result.isNull())
4020 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4021 NewT.setSigilLoc(TL.getSigilLoc());
4025 /// Transforms a reference type. Note that somewhat paradoxically we
4026 /// don't care whether the type itself is an l-value type or an r-value
4027 /// type; we only care if the type was *written* as an l-value type
4028 /// or an r-value type.
4029 template<typename Derived>
4031 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4032 ReferenceTypeLoc TL) {
4033 const ReferenceType *T = TL.getTypePtr();
4035 // Note that this works with the pointee-as-written.
4036 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4037 if (PointeeType.isNull())
4040 QualType Result = TL.getType();
4041 if (getDerived().AlwaysRebuild() ||
4042 PointeeType != T->getPointeeTypeAsWritten()) {
4043 Result = getDerived().RebuildReferenceType(PointeeType,
4044 T->isSpelledAsLValue(),
4046 if (Result.isNull())
4050 // Objective-C ARC can add lifetime qualifiers to the type that we're
4052 TLB.TypeWasModifiedSafely(
4053 Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4055 // r-value references can be rebuilt as l-value references.
4056 ReferenceTypeLoc NewTL;
4057 if (isa<LValueReferenceType>(Result))
4058 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4060 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4061 NewTL.setSigilLoc(TL.getSigilLoc());
4066 template<typename Derived>
4068 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4069 LValueReferenceTypeLoc TL) {
4070 return TransformReferenceType(TLB, TL);
4073 template<typename Derived>
4075 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4076 RValueReferenceTypeLoc TL) {
4077 return TransformReferenceType(TLB, TL);
4080 template<typename Derived>
4082 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4083 MemberPointerTypeLoc TL) {
4084 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4085 if (PointeeType.isNull())
4088 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4089 TypeSourceInfo *NewClsTInfo = nullptr;
4091 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4096 const MemberPointerType *T = TL.getTypePtr();
4097 QualType OldClsType = QualType(T->getClass(), 0);
4098 QualType NewClsType;
4100 NewClsType = NewClsTInfo->getType();
4102 NewClsType = getDerived().TransformType(OldClsType);
4103 if (NewClsType.isNull())
4107 QualType Result = TL.getType();
4108 if (getDerived().AlwaysRebuild() ||
4109 PointeeType != T->getPointeeType() ||
4110 NewClsType != OldClsType) {
4111 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4113 if (Result.isNull())
4117 // If we had to adjust the pointee type when building a member pointer, make
4118 // sure to push TypeLoc info for it.
4119 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4120 if (MPT && PointeeType != MPT->getPointeeType()) {
4121 assert(isa<AdjustedType>(MPT->getPointeeType()));
4122 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4125 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4126 NewTL.setSigilLoc(TL.getSigilLoc());
4127 NewTL.setClassTInfo(NewClsTInfo);
4132 template<typename Derived>
4134 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4135 ConstantArrayTypeLoc TL) {
4136 const ConstantArrayType *T = TL.getTypePtr();
4137 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4138 if (ElementType.isNull())
4141 QualType Result = TL.getType();
4142 if (getDerived().AlwaysRebuild() ||
4143 ElementType != T->getElementType()) {
4144 Result = getDerived().RebuildConstantArrayType(ElementType,
4145 T->getSizeModifier(),
4147 T->getIndexTypeCVRQualifiers(),
4148 TL.getBracketsRange());
4149 if (Result.isNull())
4153 // We might have either a ConstantArrayType or a VariableArrayType now:
4154 // a ConstantArrayType is allowed to have an element type which is a
4155 // VariableArrayType if the type is dependent. Fortunately, all array
4156 // types have the same location layout.
4157 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4158 NewTL.setLBracketLoc(TL.getLBracketLoc());
4159 NewTL.setRBracketLoc(TL.getRBracketLoc());
4161 Expr *Size = TL.getSizeExpr();
4163 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4164 Sema::ConstantEvaluated);
4165 Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4166 Size = SemaRef.ActOnConstantExpression(Size).get();
4168 NewTL.setSizeExpr(Size);
4173 template<typename Derived>
4174 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4175 TypeLocBuilder &TLB,
4176 IncompleteArrayTypeLoc TL) {
4177 const IncompleteArrayType *T = TL.getTypePtr();
4178 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4179 if (ElementType.isNull())
4182 QualType Result = TL.getType();
4183 if (getDerived().AlwaysRebuild() ||
4184 ElementType != T->getElementType()) {
4185 Result = getDerived().RebuildIncompleteArrayType(ElementType,
4186 T->getSizeModifier(),
4187 T->getIndexTypeCVRQualifiers(),
4188 TL.getBracketsRange());
4189 if (Result.isNull())
4193 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4194 NewTL.setLBracketLoc(TL.getLBracketLoc());
4195 NewTL.setRBracketLoc(TL.getRBracketLoc());
4196 NewTL.setSizeExpr(nullptr);
4201 template<typename Derived>
4203 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4204 VariableArrayTypeLoc TL) {
4205 const VariableArrayType *T = TL.getTypePtr();
4206 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4207 if (ElementType.isNull())
4210 ExprResult SizeResult
4211 = getDerived().TransformExpr(T->getSizeExpr());
4212 if (SizeResult.isInvalid())
4215 Expr *Size = SizeResult.get();
4217 QualType Result = TL.getType();
4218 if (getDerived().AlwaysRebuild() ||
4219 ElementType != T->getElementType() ||
4220 Size != T->getSizeExpr()) {
4221 Result = getDerived().RebuildVariableArrayType(ElementType,
4222 T->getSizeModifier(),
4224 T->getIndexTypeCVRQualifiers(),
4225 TL.getBracketsRange());
4226 if (Result.isNull())
4230 // We might have constant size array now, but fortunately it has the same
4232 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4233 NewTL.setLBracketLoc(TL.getLBracketLoc());
4234 NewTL.setRBracketLoc(TL.getRBracketLoc());
4235 NewTL.setSizeExpr(Size);
4240 template<typename Derived>
4242 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4243 DependentSizedArrayTypeLoc TL) {
4244 const DependentSizedArrayType *T = TL.getTypePtr();
4245 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4246 if (ElementType.isNull())
4249 // Array bounds are constant expressions.
4250 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4251 Sema::ConstantEvaluated);
4253 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4254 Expr *origSize = TL.getSizeExpr();
4255 if (!origSize) origSize = T->getSizeExpr();
4257 ExprResult sizeResult
4258 = getDerived().TransformExpr(origSize);
4259 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4260 if (sizeResult.isInvalid())
4263 Expr *size = sizeResult.get();
4265 QualType Result = TL.getType();
4266 if (getDerived().AlwaysRebuild() ||
4267 ElementType != T->getElementType() ||
4269 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4270 T->getSizeModifier(),
4272 T->getIndexTypeCVRQualifiers(),
4273 TL.getBracketsRange());
4274 if (Result.isNull())
4278 // We might have any sort of array type now, but fortunately they
4279 // all have the same location layout.
4280 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4281 NewTL.setLBracketLoc(TL.getLBracketLoc());
4282 NewTL.setRBracketLoc(TL.getRBracketLoc());
4283 NewTL.setSizeExpr(size);
4288 template<typename Derived>
4289 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4290 TypeLocBuilder &TLB,
4291 DependentSizedExtVectorTypeLoc TL) {
4292 const DependentSizedExtVectorType *T = TL.getTypePtr();
4294 // FIXME: ext vector locs should be nested
4295 QualType ElementType = getDerived().TransformType(T->getElementType());
4296 if (ElementType.isNull())
4299 // Vector sizes are constant expressions.
4300 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4301 Sema::ConstantEvaluated);
4303 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4304 Size = SemaRef.ActOnConstantExpression(Size);
4305 if (Size.isInvalid())
4308 QualType Result = TL.getType();
4309 if (getDerived().AlwaysRebuild() ||
4310 ElementType != T->getElementType() ||
4311 Size.get() != T->getSizeExpr()) {
4312 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4314 T->getAttributeLoc());
4315 if (Result.isNull())
4319 // Result might be dependent or not.
4320 if (isa<DependentSizedExtVectorType>(Result)) {
4321 DependentSizedExtVectorTypeLoc NewTL
4322 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4323 NewTL.setNameLoc(TL.getNameLoc());
4325 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4326 NewTL.setNameLoc(TL.getNameLoc());
4332 template<typename Derived>
4333 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
4335 const VectorType *T = TL.getTypePtr();
4336 QualType ElementType = getDerived().TransformType(T->getElementType());
4337 if (ElementType.isNull())
4340 QualType Result = TL.getType();
4341 if (getDerived().AlwaysRebuild() ||
4342 ElementType != T->getElementType()) {
4343 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
4344 T->getVectorKind());
4345 if (Result.isNull())
4349 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4350 NewTL.setNameLoc(TL.getNameLoc());
4355 template<typename Derived>
4356 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
4357 ExtVectorTypeLoc TL) {
4358 const VectorType *T = TL.getTypePtr();
4359 QualType ElementType = getDerived().TransformType(T->getElementType());
4360 if (ElementType.isNull())
4363 QualType Result = TL.getType();
4364 if (getDerived().AlwaysRebuild() ||
4365 ElementType != T->getElementType()) {
4366 Result = getDerived().RebuildExtVectorType(ElementType,
4367 T->getNumElements(),
4368 /*FIXME*/ SourceLocation());
4369 if (Result.isNull())
4373 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4374 NewTL.setNameLoc(TL.getNameLoc());
4379 template <typename Derived>
4380 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
4381 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
4382 bool ExpectParameterPack) {
4383 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
4384 TypeSourceInfo *NewDI = nullptr;
4386 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
4387 // If we're substituting into a pack expansion type and we know the
4388 // length we want to expand to, just substitute for the pattern.
4389 TypeLoc OldTL = OldDI->getTypeLoc();
4390 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
4393 TypeLoc NewTL = OldDI->getTypeLoc();
4394 TLB.reserve(NewTL.getFullDataSize());
4396 QualType Result = getDerived().TransformType(TLB,
4397 OldExpansionTL.getPatternLoc());
4398 if (Result.isNull())
4401 Result = RebuildPackExpansionType(Result,
4402 OldExpansionTL.getPatternLoc().getSourceRange(),
4403 OldExpansionTL.getEllipsisLoc(),
4405 if (Result.isNull())
4408 PackExpansionTypeLoc NewExpansionTL
4409 = TLB.push<PackExpansionTypeLoc>(Result);
4410 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
4411 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
4413 NewDI = getDerived().TransformType(OldDI);
4417 if (NewDI == OldDI && indexAdjustment == 0)
4420 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
4421 OldParm->getDeclContext(),
4422 OldParm->getInnerLocStart(),
4423 OldParm->getLocation(),
4424 OldParm->getIdentifier(),
4427 OldParm->getStorageClass(),
4428 /* DefArg */ nullptr);
4429 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
4430 OldParm->getFunctionScopeIndex() + indexAdjustment);
4434 template<typename Derived>
4435 bool TreeTransform<Derived>::
4436 TransformFunctionTypeParams(SourceLocation Loc,
4437 ParmVarDecl **Params, unsigned NumParams,
4438 const QualType *ParamTypes,
4439 SmallVectorImpl<QualType> &OutParamTypes,
4440 SmallVectorImpl<ParmVarDecl*> *PVars) {
4441 int indexAdjustment = 0;
4443 for (unsigned i = 0; i != NumParams; ++i) {
4444 if (ParmVarDecl *OldParm = Params[i]) {
4445 assert(OldParm->getFunctionScopeIndex() == i);
4447 Optional<unsigned> NumExpansions;
4448 ParmVarDecl *NewParm = nullptr;
4449 if (OldParm->isParameterPack()) {
4450 // We have a function parameter pack that may need to be expanded.
4451 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4453 // Find the parameter packs that could be expanded.
4454 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
4455 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
4456 TypeLoc Pattern = ExpansionTL.getPatternLoc();
4457 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
4458 assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
4460 // Determine whether we should expand the parameter packs.
4461 bool ShouldExpand = false;
4462 bool RetainExpansion = false;
4463 Optional<unsigned> OrigNumExpansions =
4464 ExpansionTL.getTypePtr()->getNumExpansions();
4465 NumExpansions = OrigNumExpansions;
4466 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
4467 Pattern.getSourceRange(),
4476 // Expand the function parameter pack into multiple, separate
4478 getDerived().ExpandingFunctionParameterPack(OldParm);
4479 for (unsigned I = 0; I != *NumExpansions; ++I) {
4480 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4481 ParmVarDecl *NewParm
4482 = getDerived().TransformFunctionTypeParam(OldParm,
4485 /*ExpectParameterPack=*/false);
4489 OutParamTypes.push_back(NewParm->getType());
4491 PVars->push_back(NewParm);
4494 // If we're supposed to retain a pack expansion, do so by temporarily
4495 // forgetting the partially-substituted parameter pack.
4496 if (RetainExpansion) {
4497 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4498 ParmVarDecl *NewParm
4499 = getDerived().TransformFunctionTypeParam(OldParm,
4502 /*ExpectParameterPack=*/false);
4506 OutParamTypes.push_back(NewParm->getType());
4508 PVars->push_back(NewParm);
4511 // The next parameter should have the same adjustment as the
4512 // last thing we pushed, but we post-incremented indexAdjustment
4513 // on every push. Also, if we push nothing, the adjustment should
4517 // We're done with the pack expansion.
4521 // We'll substitute the parameter now without expanding the pack
4523 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4524 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
4527 /*ExpectParameterPack=*/true);
4529 NewParm = getDerived().TransformFunctionTypeParam(
4530 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
4536 OutParamTypes.push_back(NewParm->getType());
4538 PVars->push_back(NewParm);
4542 // Deal with the possibility that we don't have a parameter
4543 // declaration for this parameter.
4544 QualType OldType = ParamTypes[i];
4545 bool IsPackExpansion = false;
4546 Optional<unsigned> NumExpansions;
4548 if (const PackExpansionType *Expansion
4549 = dyn_cast<PackExpansionType>(OldType)) {
4550 // We have a function parameter pack that may need to be expanded.
4551 QualType Pattern = Expansion->getPattern();
4552 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4553 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4555 // Determine whether we should expand the parameter packs.
4556 bool ShouldExpand = false;
4557 bool RetainExpansion = false;
4558 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
4567 // Expand the function parameter pack into multiple, separate
4569 for (unsigned I = 0; I != *NumExpansions; ++I) {
4570 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4571 QualType NewType = getDerived().TransformType(Pattern);
4572 if (NewType.isNull())
4575 OutParamTypes.push_back(NewType);
4577 PVars->push_back(nullptr);
4580 // We're done with the pack expansion.
4584 // If we're supposed to retain a pack expansion, do so by temporarily
4585 // forgetting the partially-substituted parameter pack.
4586 if (RetainExpansion) {
4587 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4588 QualType NewType = getDerived().TransformType(Pattern);
4589 if (NewType.isNull())
4592 OutParamTypes.push_back(NewType);
4594 PVars->push_back(nullptr);
4597 // We'll substitute the parameter now without expanding the pack
4599 OldType = Expansion->getPattern();
4600 IsPackExpansion = true;
4601 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4602 NewType = getDerived().TransformType(OldType);
4604 NewType = getDerived().TransformType(OldType);
4607 if (NewType.isNull())
4610 if (IsPackExpansion)
4611 NewType = getSema().Context.getPackExpansionType(NewType,
4614 OutParamTypes.push_back(NewType);
4616 PVars->push_back(nullptr);
4621 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
4622 if (ParmVarDecl *parm = (*PVars)[i])
4623 assert(parm->getFunctionScopeIndex() == i);
4630 template<typename Derived>
4632 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
4633 FunctionProtoTypeLoc TL) {
4634 SmallVector<QualType, 4> ExceptionStorage;
4635 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
4636 return getDerived().TransformFunctionProtoType(
4637 TLB, TL, nullptr, 0,
4638 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
4639 return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
4640 ExceptionStorage, Changed);
4644 template<typename Derived> template<typename Fn>
4645 QualType TreeTransform<Derived>::TransformFunctionProtoType(
4646 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
4647 unsigned ThisTypeQuals, Fn TransformExceptionSpec) {
4648 // Transform the parameters and return type.
4650 // We are required to instantiate the params and return type in source order.
4651 // When the function has a trailing return type, we instantiate the
4652 // parameters before the return type, since the return type can then refer
4653 // to the parameters themselves (via decltype, sizeof, etc.).
4655 SmallVector<QualType, 4> ParamTypes;
4656 SmallVector<ParmVarDecl*, 4> ParamDecls;
4657 const FunctionProtoType *T = TL.getTypePtr();
4659 QualType ResultType;
4661 if (T->hasTrailingReturn()) {
4662 if (getDerived().TransformFunctionTypeParams(
4663 TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
4664 TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
4668 // C++11 [expr.prim.general]p3:
4669 // If a declaration declares a member function or member function
4670 // template of a class X, the expression this is a prvalue of type
4671 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4672 // and the end of the function-definition, member-declarator, or
4674 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
4676 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4677 if (ResultType.isNull())
4682 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4683 if (ResultType.isNull())
4686 if (getDerived().TransformFunctionTypeParams(
4687 TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
4688 TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
4692 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
4694 bool EPIChanged = false;
4695 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
4698 // FIXME: Need to transform ConsumedParameters for variadic template
4701 QualType Result = TL.getType();
4702 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
4703 T->getNumParams() != ParamTypes.size() ||
4704 !std::equal(T->param_type_begin(), T->param_type_end(),
4705 ParamTypes.begin()) || EPIChanged) {
4706 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
4707 if (Result.isNull())
4711 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
4712 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4713 NewTL.setLParenLoc(TL.getLParenLoc());
4714 NewTL.setRParenLoc(TL.getRParenLoc());
4715 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4716 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
4717 NewTL.setParam(i, ParamDecls[i]);
4722 template<typename Derived>
4723 bool TreeTransform<Derived>::TransformExceptionSpec(
4724 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
4725 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
4726 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
4728 // Instantiate a dynamic noexcept expression, if any.
4729 if (ESI.Type == EST_ComputedNoexcept) {
4730 EnterExpressionEvaluationContext Unevaluated(getSema(),
4731 Sema::ConstantEvaluated);
4732 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
4733 if (NoexceptExpr.isInvalid())
4736 NoexceptExpr = getSema().CheckBooleanCondition(
4737 NoexceptExpr.get(), NoexceptExpr.get()->getLocStart());
4738 if (NoexceptExpr.isInvalid())
4741 if (!NoexceptExpr.get()->isValueDependent()) {
4742 NoexceptExpr = getSema().VerifyIntegerConstantExpression(
4743 NoexceptExpr.get(), nullptr,
4744 diag::err_noexcept_needs_constant_expression,
4745 /*AllowFold*/false);
4746 if (NoexceptExpr.isInvalid())
4750 if (ESI.NoexceptExpr != NoexceptExpr.get())
4752 ESI.NoexceptExpr = NoexceptExpr.get();
4755 if (ESI.Type != EST_Dynamic)
4758 // Instantiate a dynamic exception specification's type.
4759 for (QualType T : ESI.Exceptions) {
4760 if (const PackExpansionType *PackExpansion =
4761 T->getAs<PackExpansionType>()) {
4764 // We have a pack expansion. Instantiate it.
4765 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4766 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
4768 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4770 // Determine whether the set of unexpanded parameter packs can and
4773 bool Expand = false;
4774 bool RetainExpansion = false;
4775 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
4776 // FIXME: Track the location of the ellipsis (and track source location
4777 // information for the types in the exception specification in general).
4778 if (getDerived().TryExpandParameterPacks(
4779 Loc, SourceRange(), Unexpanded, Expand,
4780 RetainExpansion, NumExpansions))
4784 // We can't expand this pack expansion into separate arguments yet;
4785 // just substitute into the pattern and create a new pack expansion
4787 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4788 QualType U = getDerived().TransformType(PackExpansion->getPattern());
4792 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
4793 Exceptions.push_back(U);
4797 // Substitute into the pack expansion pattern for each slice of the
4799 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
4800 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
4802 QualType U = getDerived().TransformType(PackExpansion->getPattern());
4803 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
4806 Exceptions.push_back(U);
4809 QualType U = getDerived().TransformType(T);
4810 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
4815 Exceptions.push_back(U);
4819 ESI.Exceptions = Exceptions;
4823 template<typename Derived>
4824 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
4825 TypeLocBuilder &TLB,
4826 FunctionNoProtoTypeLoc TL) {
4827 const FunctionNoProtoType *T = TL.getTypePtr();
4828 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4829 if (ResultType.isNull())
4832 QualType Result = TL.getType();
4833 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
4834 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
4836 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
4837 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4838 NewTL.setLParenLoc(TL.getLParenLoc());
4839 NewTL.setRParenLoc(TL.getRParenLoc());
4840 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4845 template<typename Derived> QualType
4846 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
4847 UnresolvedUsingTypeLoc TL) {
4848 const UnresolvedUsingType *T = TL.getTypePtr();
4849 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
4853 QualType Result = TL.getType();
4854 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
4855 Result = getDerived().RebuildUnresolvedUsingType(D);
4856 if (Result.isNull())
4860 // We might get an arbitrary type spec type back. We should at
4861 // least always get a type spec type, though.
4862 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
4863 NewTL.setNameLoc(TL.getNameLoc());
4868 template<typename Derived>
4869 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
4870 TypedefTypeLoc TL) {
4871 const TypedefType *T = TL.getTypePtr();
4872 TypedefNameDecl *Typedef
4873 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4878 QualType Result = TL.getType();
4879 if (getDerived().AlwaysRebuild() ||
4880 Typedef != T->getDecl()) {
4881 Result = getDerived().RebuildTypedefType(Typedef);
4882 if (Result.isNull())
4886 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
4887 NewTL.setNameLoc(TL.getNameLoc());
4892 template<typename Derived>
4893 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
4894 TypeOfExprTypeLoc TL) {
4895 // typeof expressions are not potentially evaluated contexts
4896 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4897 Sema::ReuseLambdaContextDecl);
4899 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
4903 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
4907 QualType Result = TL.getType();
4908 if (getDerived().AlwaysRebuild() ||
4909 E.get() != TL.getUnderlyingExpr()) {
4910 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
4911 if (Result.isNull())
4916 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
4917 NewTL.setTypeofLoc(TL.getTypeofLoc());
4918 NewTL.setLParenLoc(TL.getLParenLoc());
4919 NewTL.setRParenLoc(TL.getRParenLoc());
4924 template<typename Derived>
4925 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
4927 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
4928 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
4932 QualType Result = TL.getType();
4933 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
4934 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
4935 if (Result.isNull())
4939 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
4940 NewTL.setTypeofLoc(TL.getTypeofLoc());
4941 NewTL.setLParenLoc(TL.getLParenLoc());
4942 NewTL.setRParenLoc(TL.getRParenLoc());
4943 NewTL.setUnderlyingTInfo(New_Under_TI);
4948 template<typename Derived>
4949 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
4950 DecltypeTypeLoc TL) {
4951 const DecltypeType *T = TL.getTypePtr();
4953 // decltype expressions are not potentially evaluated contexts
4954 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4955 nullptr, /*IsDecltype=*/ true);
4957 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
4961 E = getSema().ActOnDecltypeExpression(E.get());
4965 QualType Result = TL.getType();
4966 if (getDerived().AlwaysRebuild() ||
4967 E.get() != T->getUnderlyingExpr()) {
4968 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
4969 if (Result.isNull())
4974 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
4975 NewTL.setNameLoc(TL.getNameLoc());
4980 template<typename Derived>
4981 QualType TreeTransform<Derived>::TransformUnaryTransformType(
4982 TypeLocBuilder &TLB,
4983 UnaryTransformTypeLoc TL) {
4984 QualType Result = TL.getType();
4985 if (Result->isDependentType()) {
4986 const UnaryTransformType *T = TL.getTypePtr();
4988 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
4989 Result = getDerived().RebuildUnaryTransformType(NewBase,
4992 if (Result.isNull())
4996 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
4997 NewTL.setKWLoc(TL.getKWLoc());
4998 NewTL.setParensRange(TL.getParensRange());
4999 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5003 template<typename Derived>
5004 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5006 const AutoType *T = TL.getTypePtr();
5007 QualType OldDeduced = T->getDeducedType();
5008 QualType NewDeduced;
5009 if (!OldDeduced.isNull()) {
5010 NewDeduced = getDerived().TransformType(OldDeduced);
5011 if (NewDeduced.isNull())
5015 QualType Result = TL.getType();
5016 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5017 T->isDependentType()) {
5018 Result = getDerived().RebuildAutoType(NewDeduced, T->isDecltypeAuto());
5019 if (Result.isNull())
5023 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5024 NewTL.setNameLoc(TL.getNameLoc());
5029 template<typename Derived>
5030 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5032 const RecordType *T = TL.getTypePtr();
5034 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5039 QualType Result = TL.getType();
5040 if (getDerived().AlwaysRebuild() ||
5041 Record != T->getDecl()) {
5042 Result = getDerived().RebuildRecordType(Record);
5043 if (Result.isNull())
5047 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5048 NewTL.setNameLoc(TL.getNameLoc());
5053 template<typename Derived>
5054 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5056 const EnumType *T = TL.getTypePtr();
5058 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5063 QualType Result = TL.getType();
5064 if (getDerived().AlwaysRebuild() ||
5065 Enum != T->getDecl()) {
5066 Result = getDerived().RebuildEnumType(Enum);
5067 if (Result.isNull())
5071 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5072 NewTL.setNameLoc(TL.getNameLoc());
5077 template<typename Derived>
5078 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5079 TypeLocBuilder &TLB,
5080 InjectedClassNameTypeLoc TL) {
5081 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5082 TL.getTypePtr()->getDecl());
5083 if (!D) return QualType();
5085 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5086 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5090 template<typename Derived>
5091 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5092 TypeLocBuilder &TLB,
5093 TemplateTypeParmTypeLoc TL) {
5094 return TransformTypeSpecType(TLB, TL);
5097 template<typename Derived>
5098 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5099 TypeLocBuilder &TLB,
5100 SubstTemplateTypeParmTypeLoc TL) {
5101 const SubstTemplateTypeParmType *T = TL.getTypePtr();
5103 // Substitute into the replacement type, which itself might involve something
5104 // that needs to be transformed. This only tends to occur with default
5105 // template arguments of template template parameters.
5106 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5107 QualType Replacement = getDerived().TransformType(T->getReplacementType());
5108 if (Replacement.isNull())
5111 // Always canonicalize the replacement type.
5112 Replacement = SemaRef.Context.getCanonicalType(Replacement);
5114 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5117 // Propagate type-source information.
5118 SubstTemplateTypeParmTypeLoc NewTL
5119 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5120 NewTL.setNameLoc(TL.getNameLoc());
5125 template<typename Derived>
5126 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5127 TypeLocBuilder &TLB,
5128 SubstTemplateTypeParmPackTypeLoc TL) {
5129 return TransformTypeSpecType(TLB, TL);
5132 template<typename Derived>
5133 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5134 TypeLocBuilder &TLB,
5135 TemplateSpecializationTypeLoc TL) {
5136 const TemplateSpecializationType *T = TL.getTypePtr();
5138 // The nested-name-specifier never matters in a TemplateSpecializationType,
5139 // because we can't have a dependent nested-name-specifier anyway.
5141 TemplateName Template
5142 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5143 TL.getTemplateNameLoc());
5144 if (Template.isNull())
5147 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5150 template<typename Derived>
5151 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5153 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5154 if (ValueType.isNull())
5157 QualType Result = TL.getType();
5158 if (getDerived().AlwaysRebuild() ||
5159 ValueType != TL.getValueLoc().getType()) {
5160 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5161 if (Result.isNull())
5165 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5166 NewTL.setKWLoc(TL.getKWLoc());
5167 NewTL.setLParenLoc(TL.getLParenLoc());
5168 NewTL.setRParenLoc(TL.getRParenLoc());
5173 /// \brief Simple iterator that traverses the template arguments in a
5174 /// container that provides a \c getArgLoc() member function.
5176 /// This iterator is intended to be used with the iterator form of
5177 /// \c TreeTransform<Derived>::TransformTemplateArguments().
5178 template<typename ArgLocContainer>
5179 class TemplateArgumentLocContainerIterator {
5180 ArgLocContainer *Container;
5184 typedef TemplateArgumentLoc value_type;
5185 typedef TemplateArgumentLoc reference;
5186 typedef int difference_type;
5187 typedef std::input_iterator_tag iterator_category;
5190 TemplateArgumentLoc Arg;
5193 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5195 const TemplateArgumentLoc *operator->() const {
5201 TemplateArgumentLocContainerIterator() {}
5203 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5205 : Container(&Container), Index(Index) { }
5207 TemplateArgumentLocContainerIterator &operator++() {
5212 TemplateArgumentLocContainerIterator operator++(int) {
5213 TemplateArgumentLocContainerIterator Old(*this);
5218 TemplateArgumentLoc operator*() const {
5219 return Container->getArgLoc(Index);
5222 pointer operator->() const {
5223 return pointer(Container->getArgLoc(Index));
5226 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5227 const TemplateArgumentLocContainerIterator &Y) {
5228 return X.Container == Y.Container && X.Index == Y.Index;
5231 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
5232 const TemplateArgumentLocContainerIterator &Y) {
5238 template <typename Derived>
5239 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5240 TypeLocBuilder &TLB,
5241 TemplateSpecializationTypeLoc TL,
5242 TemplateName Template) {
5243 TemplateArgumentListInfo NewTemplateArgs;
5244 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5245 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5246 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
5248 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5249 ArgIterator(TL, TL.getNumArgs()),
5253 // FIXME: maybe don't rebuild if all the template arguments are the same.
5256 getDerived().RebuildTemplateSpecializationType(Template,
5257 TL.getTemplateNameLoc(),
5260 if (!Result.isNull()) {
5261 // Specializations of template template parameters are represented as
5262 // TemplateSpecializationTypes, and substitution of type alias templates
5263 // within a dependent context can transform them into
5264 // DependentTemplateSpecializationTypes.
5265 if (isa<DependentTemplateSpecializationType>(Result)) {
5266 DependentTemplateSpecializationTypeLoc NewTL
5267 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5268 NewTL.setElaboratedKeywordLoc(SourceLocation());
5269 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
5270 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5271 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5272 NewTL.setLAngleLoc(TL.getLAngleLoc());
5273 NewTL.setRAngleLoc(TL.getRAngleLoc());
5274 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5275 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5279 TemplateSpecializationTypeLoc NewTL
5280 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5281 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5282 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5283 NewTL.setLAngleLoc(TL.getLAngleLoc());
5284 NewTL.setRAngleLoc(TL.getRAngleLoc());
5285 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5286 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5292 template <typename Derived>
5293 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
5294 TypeLocBuilder &TLB,
5295 DependentTemplateSpecializationTypeLoc TL,
5296 TemplateName Template,
5298 TemplateArgumentListInfo NewTemplateArgs;
5299 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5300 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5301 typedef TemplateArgumentLocContainerIterator<
5302 DependentTemplateSpecializationTypeLoc> ArgIterator;
5303 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5304 ArgIterator(TL, TL.getNumArgs()),
5308 // FIXME: maybe don't rebuild if all the template arguments are the same.
5310 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
5312 = getSema().Context.getDependentTemplateSpecializationType(
5313 TL.getTypePtr()->getKeyword(),
5314 DTN->getQualifier(),
5315 DTN->getIdentifier(),
5318 DependentTemplateSpecializationTypeLoc NewTL
5319 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5320 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5321 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
5322 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5323 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5324 NewTL.setLAngleLoc(TL.getLAngleLoc());
5325 NewTL.setRAngleLoc(TL.getRAngleLoc());
5326 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5327 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5332 = getDerived().RebuildTemplateSpecializationType(Template,
5333 TL.getTemplateNameLoc(),
5336 if (!Result.isNull()) {
5337 /// FIXME: Wrap this in an elaborated-type-specifier?
5338 TemplateSpecializationTypeLoc NewTL
5339 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5340 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5341 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5342 NewTL.setLAngleLoc(TL.getLAngleLoc());
5343 NewTL.setRAngleLoc(TL.getRAngleLoc());
5344 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5345 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5351 template<typename Derived>
5353 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
5354 ElaboratedTypeLoc TL) {
5355 const ElaboratedType *T = TL.getTypePtr();
5357 NestedNameSpecifierLoc QualifierLoc;
5358 // NOTE: the qualifier in an ElaboratedType is optional.
5359 if (TL.getQualifierLoc()) {
5361 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5366 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
5367 if (NamedT.isNull())
5370 // C++0x [dcl.type.elab]p2:
5371 // If the identifier resolves to a typedef-name or the simple-template-id
5372 // resolves to an alias template specialization, the
5373 // elaborated-type-specifier is ill-formed.
5374 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
5375 if (const TemplateSpecializationType *TST =
5376 NamedT->getAs<TemplateSpecializationType>()) {
5377 TemplateName Template = TST->getTemplateName();
5378 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
5379 Template.getAsTemplateDecl())) {
5380 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
5381 diag::err_tag_reference_non_tag) << 4;
5382 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
5387 QualType Result = TL.getType();
5388 if (getDerived().AlwaysRebuild() ||
5389 QualifierLoc != TL.getQualifierLoc() ||
5390 NamedT != T->getNamedType()) {
5391 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
5393 QualifierLoc, NamedT);
5394 if (Result.isNull())
5398 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5399 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5400 NewTL.setQualifierLoc(QualifierLoc);
5404 template<typename Derived>
5405 QualType TreeTransform<Derived>::TransformAttributedType(
5406 TypeLocBuilder &TLB,
5407 AttributedTypeLoc TL) {
5408 const AttributedType *oldType = TL.getTypePtr();
5409 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
5410 if (modifiedType.isNull())
5413 QualType result = TL.getType();
5415 // FIXME: dependent operand expressions?
5416 if (getDerived().AlwaysRebuild() ||
5417 modifiedType != oldType->getModifiedType()) {
5418 // TODO: this is really lame; we should really be rebuilding the
5419 // equivalent type from first principles.
5420 QualType equivalentType
5421 = getDerived().TransformType(oldType->getEquivalentType());
5422 if (equivalentType.isNull())
5425 // Check whether we can add nullability; it is only represented as
5426 // type sugar, and therefore cannot be diagnosed in any other way.
5427 if (auto nullability = oldType->getImmediateNullability()) {
5428 if (!modifiedType->canHaveNullability()) {
5429 SemaRef.Diag(TL.getAttrNameLoc(), diag::err_nullability_nonpointer)
5430 << DiagNullabilityKind(*nullability, false) << modifiedType;
5435 result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
5440 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
5441 newTL.setAttrNameLoc(TL.getAttrNameLoc());
5442 if (TL.hasAttrOperand())
5443 newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5444 if (TL.hasAttrExprOperand())
5445 newTL.setAttrExprOperand(TL.getAttrExprOperand());
5446 else if (TL.hasAttrEnumOperand())
5447 newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
5452 template<typename Derived>
5454 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
5456 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
5460 QualType Result = TL.getType();
5461 if (getDerived().AlwaysRebuild() ||
5462 Inner != TL.getInnerLoc().getType()) {
5463 Result = getDerived().RebuildParenType(Inner);
5464 if (Result.isNull())
5468 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
5469 NewTL.setLParenLoc(TL.getLParenLoc());
5470 NewTL.setRParenLoc(TL.getRParenLoc());
5474 template<typename Derived>
5475 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
5476 DependentNameTypeLoc TL) {
5477 const DependentNameType *T = TL.getTypePtr();
5479 NestedNameSpecifierLoc QualifierLoc
5480 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5485 = getDerived().RebuildDependentNameType(T->getKeyword(),
5486 TL.getElaboratedKeywordLoc(),
5490 if (Result.isNull())
5493 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5494 QualType NamedT = ElabT->getNamedType();
5495 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5497 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5498 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5499 NewTL.setQualifierLoc(QualifierLoc);
5501 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5502 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5503 NewTL.setQualifierLoc(QualifierLoc);
5504 NewTL.setNameLoc(TL.getNameLoc());
5509 template<typename Derived>
5510 QualType TreeTransform<Derived>::
5511 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5512 DependentTemplateSpecializationTypeLoc TL) {
5513 NestedNameSpecifierLoc QualifierLoc;
5514 if (TL.getQualifierLoc()) {
5516 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5522 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
5525 template<typename Derived>
5526 QualType TreeTransform<Derived>::
5527 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5528 DependentTemplateSpecializationTypeLoc TL,
5529 NestedNameSpecifierLoc QualifierLoc) {
5530 const DependentTemplateSpecializationType *T = TL.getTypePtr();
5532 TemplateArgumentListInfo NewTemplateArgs;
5533 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5534 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5536 typedef TemplateArgumentLocContainerIterator<
5537 DependentTemplateSpecializationTypeLoc> ArgIterator;
5538 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5539 ArgIterator(TL, TL.getNumArgs()),
5544 = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
5547 TL.getTemplateNameLoc(),
5549 if (Result.isNull())
5552 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
5553 QualType NamedT = ElabT->getNamedType();
5555 // Copy information relevant to the template specialization.
5556 TemplateSpecializationTypeLoc NamedTL
5557 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5558 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5559 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5560 NamedTL.setLAngleLoc(TL.getLAngleLoc());
5561 NamedTL.setRAngleLoc(TL.getRAngleLoc());
5562 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5563 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5565 // Copy information relevant to the elaborated type.
5566 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5567 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5568 NewTL.setQualifierLoc(QualifierLoc);
5569 } else if (isa<DependentTemplateSpecializationType>(Result)) {
5570 DependentTemplateSpecializationTypeLoc SpecTL
5571 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5572 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5573 SpecTL.setQualifierLoc(QualifierLoc);
5574 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5575 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5576 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5577 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5578 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5579 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5581 TemplateSpecializationTypeLoc SpecTL
5582 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5583 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5584 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5585 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5586 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5587 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5588 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5593 template<typename Derived>
5594 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
5595 PackExpansionTypeLoc TL) {
5597 = getDerived().TransformType(TLB, TL.getPatternLoc());
5598 if (Pattern.isNull())
5601 QualType Result = TL.getType();
5602 if (getDerived().AlwaysRebuild() ||
5603 Pattern != TL.getPatternLoc().getType()) {
5604 Result = getDerived().RebuildPackExpansionType(Pattern,
5605 TL.getPatternLoc().getSourceRange(),
5606 TL.getEllipsisLoc(),
5607 TL.getTypePtr()->getNumExpansions());
5608 if (Result.isNull())
5612 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
5613 NewT.setEllipsisLoc(TL.getEllipsisLoc());
5617 template<typename Derived>
5619 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
5620 ObjCInterfaceTypeLoc TL) {
5621 // ObjCInterfaceType is never dependent.
5622 TLB.pushFullCopy(TL);
5623 return TL.getType();
5626 template<typename Derived>
5628 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
5629 ObjCObjectTypeLoc TL) {
5630 // Transform base type.
5631 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
5632 if (BaseType.isNull())
5635 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
5637 // Transform type arguments.
5638 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
5639 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
5640 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
5641 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
5642 QualType TypeArg = TypeArgInfo->getType();
5643 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
5646 // We have a pack expansion. Instantiate it.
5647 const auto *PackExpansion = PackExpansionLoc.getType()
5648 ->castAs<PackExpansionType>();
5649 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5650 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5652 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5654 // Determine whether the set of unexpanded parameter packs can
5655 // and should be expanded.
5656 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
5657 bool Expand = false;
5658 bool RetainExpansion = false;
5659 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5660 if (getDerived().TryExpandParameterPacks(
5661 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
5662 Unexpanded, Expand, RetainExpansion, NumExpansions))
5666 // We can't expand this pack expansion into separate arguments yet;
5667 // just substitute into the pattern and create a new pack expansion
5669 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5671 TypeLocBuilder TypeArgBuilder;
5672 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
5673 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
5675 if (NewPatternType.isNull())
5678 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
5679 NewPatternType, NumExpansions);
5680 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
5681 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
5682 NewTypeArgInfos.push_back(
5683 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
5687 // Substitute into the pack expansion pattern for each slice of the
5689 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5690 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5692 TypeLocBuilder TypeArgBuilder;
5693 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
5695 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
5697 if (NewTypeArg.isNull())
5700 NewTypeArgInfos.push_back(
5701 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
5707 TypeLocBuilder TypeArgBuilder;
5708 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
5709 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
5710 if (NewTypeArg.isNull())
5713 // If nothing changed, just keep the old TypeSourceInfo.
5714 if (NewTypeArg == TypeArg) {
5715 NewTypeArgInfos.push_back(TypeArgInfo);
5719 NewTypeArgInfos.push_back(
5720 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
5724 QualType Result = TL.getType();
5725 if (getDerived().AlwaysRebuild() || AnyChanged) {
5726 // Rebuild the type.
5727 Result = getDerived().RebuildObjCObjectType(
5730 TL.getTypeArgsLAngleLoc(),
5732 TL.getTypeArgsRAngleLoc(),
5733 TL.getProtocolLAngleLoc(),
5734 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
5735 TL.getNumProtocols()),
5736 TL.getProtocolLocs(),
5737 TL.getProtocolRAngleLoc());
5739 if (Result.isNull())
5743 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
5744 assert(TL.hasBaseTypeAsWritten() && "Can't be dependent");
5745 NewT.setHasBaseTypeAsWritten(true);
5746 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
5747 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
5748 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
5749 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
5750 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
5751 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
5752 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
5753 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
5757 template<typename Derived>
5759 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
5760 ObjCObjectPointerTypeLoc TL) {
5761 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5762 if (PointeeType.isNull())
5765 QualType Result = TL.getType();
5766 if (getDerived().AlwaysRebuild() ||
5767 PointeeType != TL.getPointeeLoc().getType()) {
5768 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
5770 if (Result.isNull())
5774 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5775 NewT.setStarLoc(TL.getStarLoc());
5779 //===----------------------------------------------------------------------===//
5780 // Statement transformation
5781 //===----------------------------------------------------------------------===//
5782 template<typename Derived>
5784 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
5788 template<typename Derived>
5790 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
5791 return getDerived().TransformCompoundStmt(S, false);
5794 template<typename Derived>
5796 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
5798 Sema::CompoundScopeRAII CompoundScope(getSema());
5800 bool SubStmtInvalid = false;
5801 bool SubStmtChanged = false;
5802 SmallVector<Stmt*, 8> Statements;
5803 for (auto *B : S->body()) {
5804 StmtResult Result = getDerived().TransformStmt(B);
5805 if (Result.isInvalid()) {
5806 // Immediately fail if this was a DeclStmt, since it's very
5807 // likely that this will cause problems for future statements.
5808 if (isa<DeclStmt>(B))
5811 // Otherwise, just keep processing substatements and fail later.
5812 SubStmtInvalid = true;
5816 SubStmtChanged = SubStmtChanged || Result.get() != B;
5817 Statements.push_back(Result.getAs<Stmt>());
5823 if (!getDerived().AlwaysRebuild() &&
5827 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
5833 template<typename Derived>
5835 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
5836 ExprResult LHS, RHS;
5838 EnterExpressionEvaluationContext Unevaluated(SemaRef,
5839 Sema::ConstantEvaluated);
5841 // Transform the left-hand case value.
5842 LHS = getDerived().TransformExpr(S->getLHS());
5843 LHS = SemaRef.ActOnConstantExpression(LHS);
5844 if (LHS.isInvalid())
5847 // Transform the right-hand case value (for the GNU case-range extension).
5848 RHS = getDerived().TransformExpr(S->getRHS());
5849 RHS = SemaRef.ActOnConstantExpression(RHS);
5850 if (RHS.isInvalid())
5854 // Build the case statement.
5855 // Case statements are always rebuilt so that they will attached to their
5856 // transformed switch statement.
5857 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
5859 S->getEllipsisLoc(),
5862 if (Case.isInvalid())
5865 // Transform the statement following the case
5866 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5867 if (SubStmt.isInvalid())
5870 // Attach the body to the case statement
5871 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
5874 template<typename Derived>
5876 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
5877 // Transform the statement following the default case
5878 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5879 if (SubStmt.isInvalid())
5882 // Default statements are always rebuilt
5883 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
5887 template<typename Derived>
5889 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
5890 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5891 if (SubStmt.isInvalid())
5894 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
5900 // FIXME: Pass the real colon location in.
5901 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
5902 cast<LabelDecl>(LD), SourceLocation(),
5906 template <typename Derived>
5907 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
5911 switch (R->getKind()) {
5912 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
5914 #define PRAGMA_SPELLING_ATTR(X) \
5916 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
5917 #include "clang/Basic/AttrList.inc"
5923 template <typename Derived>
5924 StmtResult TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
5925 bool AttrsChanged = false;
5926 SmallVector<const Attr *, 1> Attrs;
5928 // Visit attributes and keep track if any are transformed.
5929 for (const auto *I : S->getAttrs()) {
5930 const Attr *R = getDerived().TransformAttr(I);
5931 AttrsChanged |= (I != R);
5935 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5936 if (SubStmt.isInvalid())
5939 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
5942 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
5946 template<typename Derived>
5948 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
5949 // Transform the condition
5951 VarDecl *ConditionVar = nullptr;
5952 if (S->getConditionVariable()) {
5954 = cast_or_null<VarDecl>(
5955 getDerived().TransformDefinition(
5956 S->getConditionVariable()->getLocation(),
5957 S->getConditionVariable()));
5961 Cond = getDerived().TransformExpr(S->getCond());
5963 if (Cond.isInvalid())
5966 // Convert the condition to a boolean value.
5968 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr, S->getIfLoc(),
5970 if (CondE.isInvalid())
5977 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5978 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5981 // Transform the "then" branch.
5982 StmtResult Then = getDerived().TransformStmt(S->getThen());
5983 if (Then.isInvalid())
5986 // Transform the "else" branch.
5987 StmtResult Else = getDerived().TransformStmt(S->getElse());
5988 if (Else.isInvalid())
5991 if (!getDerived().AlwaysRebuild() &&
5992 FullCond.get() == S->getCond() &&
5993 ConditionVar == S->getConditionVariable() &&
5994 Then.get() == S->getThen() &&
5995 Else.get() == S->getElse())
5998 return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
6000 S->getElseLoc(), Else.get());
6003 template<typename Derived>
6005 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6006 // Transform the condition.
6008 VarDecl *ConditionVar = nullptr;
6009 if (S->getConditionVariable()) {
6011 = cast_or_null<VarDecl>(
6012 getDerived().TransformDefinition(
6013 S->getConditionVariable()->getLocation(),
6014 S->getConditionVariable()));
6018 Cond = getDerived().TransformExpr(S->getCond());
6020 if (Cond.isInvalid())
6024 // Rebuild the switch statement.
6026 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
6028 if (Switch.isInvalid())
6031 // Transform the body of the switch statement.
6032 StmtResult Body = getDerived().TransformStmt(S->getBody());
6033 if (Body.isInvalid())
6036 // Complete the switch statement.
6037 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6041 template<typename Derived>
6043 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6044 // Transform the condition
6046 VarDecl *ConditionVar = nullptr;
6047 if (S->getConditionVariable()) {
6049 = cast_or_null<VarDecl>(
6050 getDerived().TransformDefinition(
6051 S->getConditionVariable()->getLocation(),
6052 S->getConditionVariable()));
6056 Cond = getDerived().TransformExpr(S->getCond());
6058 if (Cond.isInvalid())
6062 // Convert the condition to a boolean value.
6063 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
6066 if (CondE.isInvalid())
6072 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
6073 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
6076 // Transform the body
6077 StmtResult Body = getDerived().TransformStmt(S->getBody());
6078 if (Body.isInvalid())
6081 if (!getDerived().AlwaysRebuild() &&
6082 FullCond.get() == S->getCond() &&
6083 ConditionVar == S->getConditionVariable() &&
6084 Body.get() == S->getBody())
6087 return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
6088 ConditionVar, Body.get());
6091 template<typename Derived>
6093 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6094 // Transform the body
6095 StmtResult Body = getDerived().TransformStmt(S->getBody());
6096 if (Body.isInvalid())
6099 // Transform the condition
6100 ExprResult Cond = getDerived().TransformExpr(S->getCond());
6101 if (Cond.isInvalid())
6104 if (!getDerived().AlwaysRebuild() &&
6105 Cond.get() == S->getCond() &&
6106 Body.get() == S->getBody())
6109 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6110 /*FIXME:*/S->getWhileLoc(), Cond.get(),
6114 template<typename Derived>
6116 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6117 // Transform the initialization statement
6118 StmtResult Init = getDerived().TransformStmt(S->getInit());
6119 if (Init.isInvalid())
6122 // Transform the condition
6124 VarDecl *ConditionVar = nullptr;
6125 if (S->getConditionVariable()) {
6127 = cast_or_null<VarDecl>(
6128 getDerived().TransformDefinition(
6129 S->getConditionVariable()->getLocation(),
6130 S->getConditionVariable()));
6134 Cond = getDerived().TransformExpr(S->getCond());
6136 if (Cond.isInvalid())
6140 // Convert the condition to a boolean value.
6141 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
6144 if (CondE.isInvalid())
6151 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
6152 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
6155 // Transform the increment
6156 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6157 if (Inc.isInvalid())
6160 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6161 if (S->getInc() && !FullInc.get())
6164 // Transform the body
6165 StmtResult Body = getDerived().TransformStmt(S->getBody());
6166 if (Body.isInvalid())
6169 if (!getDerived().AlwaysRebuild() &&
6170 Init.get() == S->getInit() &&
6171 FullCond.get() == S->getCond() &&
6172 Inc.get() == S->getInc() &&
6173 Body.get() == S->getBody())
6176 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6177 Init.get(), FullCond, ConditionVar,
6178 FullInc, S->getRParenLoc(), Body.get());
6181 template<typename Derived>
6183 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6184 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6189 // Goto statements must always be rebuilt, to resolve the label.
6190 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
6191 cast<LabelDecl>(LD));
6194 template<typename Derived>
6196 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
6197 ExprResult Target = getDerived().TransformExpr(S->getTarget());
6198 if (Target.isInvalid())
6200 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6202 if (!getDerived().AlwaysRebuild() &&
6203 Target.get() == S->getTarget())
6206 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6210 template<typename Derived>
6212 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6216 template<typename Derived>
6218 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6222 template<typename Derived>
6224 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
6225 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
6226 /*NotCopyInit*/false);
6227 if (Result.isInvalid())
6230 // FIXME: We always rebuild the return statement because there is no way
6231 // to tell whether the return type of the function has changed.
6232 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
6235 template<typename Derived>
6237 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
6238 bool DeclChanged = false;
6239 SmallVector<Decl *, 4> Decls;
6240 for (auto *D : S->decls()) {
6241 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
6245 if (Transformed != D)
6248 Decls.push_back(Transformed);
6251 if (!getDerived().AlwaysRebuild() && !DeclChanged)
6254 return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
6257 template<typename Derived>
6259 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
6261 SmallVector<Expr*, 8> Constraints;
6262 SmallVector<Expr*, 8> Exprs;
6263 SmallVector<IdentifierInfo *, 4> Names;
6265 ExprResult AsmString;
6266 SmallVector<Expr*, 8> Clobbers;
6268 bool ExprsChanged = false;
6270 // Go through the outputs.
6271 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
6272 Names.push_back(S->getOutputIdentifier(I));
6274 // No need to transform the constraint literal.
6275 Constraints.push_back(S->getOutputConstraintLiteral(I));
6277 // Transform the output expr.
6278 Expr *OutputExpr = S->getOutputExpr(I);
6279 ExprResult Result = getDerived().TransformExpr(OutputExpr);
6280 if (Result.isInvalid())
6283 ExprsChanged |= Result.get() != OutputExpr;
6285 Exprs.push_back(Result.get());
6288 // Go through the inputs.
6289 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
6290 Names.push_back(S->getInputIdentifier(I));
6292 // No need to transform the constraint literal.
6293 Constraints.push_back(S->getInputConstraintLiteral(I));
6295 // Transform the input expr.
6296 Expr *InputExpr = S->getInputExpr(I);
6297 ExprResult Result = getDerived().TransformExpr(InputExpr);
6298 if (Result.isInvalid())
6301 ExprsChanged |= Result.get() != InputExpr;
6303 Exprs.push_back(Result.get());
6306 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
6309 // Go through the clobbers.
6310 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
6311 Clobbers.push_back(S->getClobberStringLiteral(I));
6313 // No need to transform the asm string literal.
6314 AsmString = S->getAsmString();
6315 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
6316 S->isVolatile(), S->getNumOutputs(),
6317 S->getNumInputs(), Names.data(),
6318 Constraints, Exprs, AsmString.get(),
6319 Clobbers, S->getRParenLoc());
6322 template<typename Derived>
6324 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
6325 ArrayRef<Token> AsmToks =
6326 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
6328 bool HadError = false, HadChange = false;
6330 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
6331 SmallVector<Expr*, 8> TransformedExprs;
6332 TransformedExprs.reserve(SrcExprs.size());
6333 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
6334 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
6335 if (!Result.isUsable()) {
6338 HadChange |= (Result.get() != SrcExprs[i]);
6339 TransformedExprs.push_back(Result.get());
6343 if (HadError) return StmtError();
6344 if (!HadChange && !getDerived().AlwaysRebuild())
6347 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
6348 AsmToks, S->getAsmString(),
6349 S->getNumOutputs(), S->getNumInputs(),
6350 S->getAllConstraints(), S->getClobbers(),
6351 TransformedExprs, S->getEndLoc());
6354 template<typename Derived>
6356 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
6357 // Transform the body of the @try.
6358 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
6359 if (TryBody.isInvalid())
6362 // Transform the @catch statements (if present).
6363 bool AnyCatchChanged = false;
6364 SmallVector<Stmt*, 8> CatchStmts;
6365 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
6366 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
6367 if (Catch.isInvalid())
6369 if (Catch.get() != S->getCatchStmt(I))
6370 AnyCatchChanged = true;
6371 CatchStmts.push_back(Catch.get());
6374 // Transform the @finally statement (if present).
6376 if (S->getFinallyStmt()) {
6377 Finally = getDerived().TransformStmt(S->getFinallyStmt());
6378 if (Finally.isInvalid())
6382 // If nothing changed, just retain this statement.
6383 if (!getDerived().AlwaysRebuild() &&
6384 TryBody.get() == S->getTryBody() &&
6386 Finally.get() == S->getFinallyStmt())
6389 // Build a new statement.
6390 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
6391 CatchStmts, Finally.get());
6394 template<typename Derived>
6396 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
6397 // Transform the @catch parameter, if there is one.
6398 VarDecl *Var = nullptr;
6399 if (VarDecl *FromVar = S->getCatchParamDecl()) {
6400 TypeSourceInfo *TSInfo = nullptr;
6401 if (FromVar->getTypeSourceInfo()) {
6402 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
6409 T = TSInfo->getType();
6411 T = getDerived().TransformType(FromVar->getType());
6416 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
6421 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
6422 if (Body.isInvalid())
6425 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
6430 template<typename Derived>
6432 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
6433 // Transform the body.
6434 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
6435 if (Body.isInvalid())
6438 // If nothing changed, just retain this statement.
6439 if (!getDerived().AlwaysRebuild() &&
6440 Body.get() == S->getFinallyBody())
6443 // Build a new statement.
6444 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
6448 template<typename Derived>
6450 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
6452 if (S->getThrowExpr()) {
6453 Operand = getDerived().TransformExpr(S->getThrowExpr());
6454 if (Operand.isInvalid())
6458 if (!getDerived().AlwaysRebuild() &&
6459 Operand.get() == S->getThrowExpr())
6462 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
6465 template<typename Derived>
6467 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
6468 ObjCAtSynchronizedStmt *S) {
6469 // Transform the object we are locking.
6470 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
6471 if (Object.isInvalid())
6474 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
6476 if (Object.isInvalid())
6479 // Transform the body.
6480 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
6481 if (Body.isInvalid())
6484 // If nothing change, just retain the current statement.
6485 if (!getDerived().AlwaysRebuild() &&
6486 Object.get() == S->getSynchExpr() &&
6487 Body.get() == S->getSynchBody())
6490 // Build a new statement.
6491 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
6492 Object.get(), Body.get());
6495 template<typename Derived>
6497 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
6498 ObjCAutoreleasePoolStmt *S) {
6499 // Transform the body.
6500 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
6501 if (Body.isInvalid())
6504 // If nothing changed, just retain this statement.
6505 if (!getDerived().AlwaysRebuild() &&
6506 Body.get() == S->getSubStmt())
6509 // Build a new statement.
6510 return getDerived().RebuildObjCAutoreleasePoolStmt(
6511 S->getAtLoc(), Body.get());
6514 template<typename Derived>
6516 TreeTransform<Derived>::TransformObjCForCollectionStmt(
6517 ObjCForCollectionStmt *S) {
6518 // Transform the element statement.
6519 StmtResult Element = getDerived().TransformStmt(S->getElement());
6520 if (Element.isInvalid())
6523 // Transform the collection expression.
6524 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
6525 if (Collection.isInvalid())
6528 // Transform the body.
6529 StmtResult Body = getDerived().TransformStmt(S->getBody());
6530 if (Body.isInvalid())
6533 // If nothing changed, just retain this statement.
6534 if (!getDerived().AlwaysRebuild() &&
6535 Element.get() == S->getElement() &&
6536 Collection.get() == S->getCollection() &&
6537 Body.get() == S->getBody())
6540 // Build a new statement.
6541 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
6548 template <typename Derived>
6549 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
6550 // Transform the exception declaration, if any.
6551 VarDecl *Var = nullptr;
6552 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
6554 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
6558 Var = getDerived().RebuildExceptionDecl(
6559 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
6560 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
6561 if (!Var || Var->isInvalidDecl())
6565 // Transform the actual exception handler.
6566 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
6567 if (Handler.isInvalid())
6570 if (!getDerived().AlwaysRebuild() && !Var &&
6571 Handler.get() == S->getHandlerBlock())
6574 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
6577 template <typename Derived>
6578 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
6579 // Transform the try block itself.
6580 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
6581 if (TryBlock.isInvalid())
6584 // Transform the handlers.
6585 bool HandlerChanged = false;
6586 SmallVector<Stmt *, 8> Handlers;
6587 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
6588 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
6589 if (Handler.isInvalid())
6592 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
6593 Handlers.push_back(Handler.getAs<Stmt>());
6596 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
6600 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
6604 template<typename Derived>
6606 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
6607 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
6608 if (Range.isInvalid())
6611 StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
6612 if (BeginEnd.isInvalid())
6615 ExprResult Cond = getDerived().TransformExpr(S->getCond());
6616 if (Cond.isInvalid())
6619 Cond = SemaRef.CheckBooleanCondition(Cond.get(), S->getColonLoc());
6620 if (Cond.isInvalid())
6623 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
6625 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6626 if (Inc.isInvalid())
6629 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
6631 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
6632 if (LoopVar.isInvalid())
6635 StmtResult NewStmt = S;
6636 if (getDerived().AlwaysRebuild() ||
6637 Range.get() != S->getRangeStmt() ||
6638 BeginEnd.get() != S->getBeginEndStmt() ||
6639 Cond.get() != S->getCond() ||
6640 Inc.get() != S->getInc() ||
6641 LoopVar.get() != S->getLoopVarStmt()) {
6642 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6643 S->getColonLoc(), Range.get(),
6644 BeginEnd.get(), Cond.get(),
6645 Inc.get(), LoopVar.get(),
6647 if (NewStmt.isInvalid())
6651 StmtResult Body = getDerived().TransformStmt(S->getBody());
6652 if (Body.isInvalid())
6655 // Body has changed but we didn't rebuild the for-range statement. Rebuild
6656 // it now so we have a new statement to attach the body to.
6657 if (Body.get() != S->getBody() && NewStmt.get() == S) {
6658 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6659 S->getColonLoc(), Range.get(),
6660 BeginEnd.get(), Cond.get(),
6661 Inc.get(), LoopVar.get(),
6663 if (NewStmt.isInvalid())
6667 if (NewStmt.get() == S)
6670 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
6673 template<typename Derived>
6675 TreeTransform<Derived>::TransformMSDependentExistsStmt(
6676 MSDependentExistsStmt *S) {
6677 // Transform the nested-name-specifier, if any.
6678 NestedNameSpecifierLoc QualifierLoc;
6679 if (S->getQualifierLoc()) {
6681 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
6686 // Transform the declaration name.
6687 DeclarationNameInfo NameInfo = S->getNameInfo();
6688 if (NameInfo.getName()) {
6689 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
6690 if (!NameInfo.getName())
6694 // Check whether anything changed.
6695 if (!getDerived().AlwaysRebuild() &&
6696 QualifierLoc == S->getQualifierLoc() &&
6697 NameInfo.getName() == S->getNameInfo().getName())
6700 // Determine whether this name exists, if we can.
6702 SS.Adopt(QualifierLoc);
6703 bool Dependent = false;
6704 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
6705 case Sema::IER_Exists:
6706 if (S->isIfExists())
6709 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6711 case Sema::IER_DoesNotExist:
6712 if (S->isIfNotExists())
6715 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6717 case Sema::IER_Dependent:
6721 case Sema::IER_Error:
6725 // We need to continue with the instantiation, so do so now.
6726 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
6727 if (SubStmt.isInvalid())
6730 // If we have resolved the name, just transform to the substatement.
6734 // The name is still dependent, so build a dependent expression again.
6735 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
6742 template<typename Derived>
6744 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
6745 NestedNameSpecifierLoc QualifierLoc;
6746 if (E->getQualifierLoc()) {
6748 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6753 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
6754 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
6758 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
6759 if (Base.isInvalid())
6762 return new (SemaRef.getASTContext())
6763 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
6764 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
6765 QualifierLoc, E->getMemberLoc());
6768 template <typename Derived>
6769 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
6770 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
6771 if (TryBlock.isInvalid())
6774 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
6775 if (Handler.isInvalid())
6778 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
6779 Handler.get() == S->getHandler())
6782 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
6783 TryBlock.get(), Handler.get());
6786 template <typename Derived>
6787 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
6788 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
6789 if (Block.isInvalid())
6792 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
6795 template <typename Derived>
6796 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
6797 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
6798 if (FilterExpr.isInvalid())
6801 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
6802 if (Block.isInvalid())
6805 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
6809 template <typename Derived>
6810 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
6811 if (isa<SEHFinallyStmt>(Handler))
6812 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
6814 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
6817 template<typename Derived>
6819 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
6823 //===----------------------------------------------------------------------===//
6824 // OpenMP directive transformation
6825 //===----------------------------------------------------------------------===//
6826 template <typename Derived>
6827 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
6828 OMPExecutableDirective *D) {
6830 // Transform the clauses
6831 llvm::SmallVector<OMPClause *, 16> TClauses;
6832 ArrayRef<OMPClause *> Clauses = D->clauses();
6833 TClauses.reserve(Clauses.size());
6834 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
6837 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
6838 OMPClause *Clause = getDerived().TransformOMPClause(*I);
6839 getDerived().getSema().EndOpenMPClause();
6841 TClauses.push_back(Clause);
6843 TClauses.push_back(nullptr);
6846 StmtResult AssociatedStmt;
6847 if (D->hasAssociatedStmt()) {
6848 if (!D->getAssociatedStmt()) {
6851 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
6852 /*CurScope=*/nullptr);
6855 Sema::CompoundScopeRAII CompoundScope(getSema());
6856 Body = getDerived().TransformStmt(
6857 cast<CapturedStmt>(D->getAssociatedStmt())->getCapturedStmt());
6860 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
6861 if (AssociatedStmt.isInvalid()) {
6865 if (TClauses.size() != Clauses.size()) {
6869 // Transform directive name for 'omp critical' directive.
6870 DeclarationNameInfo DirName;
6871 if (D->getDirectiveKind() == OMPD_critical) {
6872 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
6873 DirName = getDerived().TransformDeclarationNameInfo(DirName);
6875 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
6876 if (D->getDirectiveKind() == OMPD_cancellation_point) {
6877 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
6878 } else if (D->getDirectiveKind() == OMPD_cancel) {
6879 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
6882 return getDerived().RebuildOMPExecutableDirective(
6883 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
6884 AssociatedStmt.get(), D->getLocStart(), D->getLocEnd());
6887 template <typename Derived>
6889 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
6890 DeclarationNameInfo DirName;
6891 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
6893 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6894 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6898 template <typename Derived>
6900 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
6901 DeclarationNameInfo DirName;
6902 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
6904 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6905 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6909 template <typename Derived>
6911 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
6912 DeclarationNameInfo DirName;
6913 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
6915 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6916 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6920 template <typename Derived>
6922 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
6923 DeclarationNameInfo DirName;
6924 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
6926 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6927 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6931 template <typename Derived>
6933 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
6934 DeclarationNameInfo DirName;
6935 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
6937 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6938 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6942 template <typename Derived>
6944 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
6945 DeclarationNameInfo DirName;
6946 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
6948 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6949 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6953 template <typename Derived>
6955 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
6956 DeclarationNameInfo DirName;
6957 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
6959 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6960 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6964 template <typename Derived>
6966 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
6967 DeclarationNameInfo DirName;
6968 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
6970 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6971 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6975 template <typename Derived>
6977 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
6978 getDerived().getSema().StartOpenMPDSABlock(
6979 OMPD_critical, D->getDirectiveName(), nullptr, D->getLocStart());
6980 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6981 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6985 template <typename Derived>
6986 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
6987 OMPParallelForDirective *D) {
6988 DeclarationNameInfo DirName;
6989 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
6990 nullptr, D->getLocStart());
6991 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6992 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6996 template <typename Derived>
6997 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
6998 OMPParallelForSimdDirective *D) {
6999 DeclarationNameInfo DirName;
7000 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
7001 nullptr, D->getLocStart());
7002 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7003 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7007 template <typename Derived>
7008 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
7009 OMPParallelSectionsDirective *D) {
7010 DeclarationNameInfo DirName;
7011 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
7012 nullptr, D->getLocStart());
7013 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7014 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7018 template <typename Derived>
7020 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
7021 DeclarationNameInfo DirName;
7022 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
7024 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7025 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7029 template <typename Derived>
7030 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
7031 OMPTaskyieldDirective *D) {
7032 DeclarationNameInfo DirName;
7033 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
7035 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7036 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7040 template <typename Derived>
7042 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
7043 DeclarationNameInfo DirName;
7044 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
7046 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7047 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7051 template <typename Derived>
7053 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
7054 DeclarationNameInfo DirName;
7055 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
7057 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7058 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7062 template <typename Derived>
7063 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
7064 OMPTaskgroupDirective *D) {
7065 DeclarationNameInfo DirName;
7066 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
7068 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7069 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7073 template <typename Derived>
7075 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
7076 DeclarationNameInfo DirName;
7077 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
7079 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7080 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7084 template <typename Derived>
7086 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
7087 DeclarationNameInfo DirName;
7088 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
7090 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7091 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7095 template <typename Derived>
7097 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
7098 DeclarationNameInfo DirName;
7099 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
7101 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7102 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7106 template <typename Derived>
7108 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
7109 DeclarationNameInfo DirName;
7110 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
7112 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7113 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7117 template <typename Derived>
7119 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
7120 DeclarationNameInfo DirName;
7121 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
7123 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7124 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7128 template <typename Derived>
7129 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
7130 OMPCancellationPointDirective *D) {
7131 DeclarationNameInfo DirName;
7132 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
7133 nullptr, D->getLocStart());
7134 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7135 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7139 template <typename Derived>
7141 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
7142 DeclarationNameInfo DirName;
7143 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
7145 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7146 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7150 //===----------------------------------------------------------------------===//
7151 // OpenMP clause transformation
7152 //===----------------------------------------------------------------------===//
7153 template <typename Derived>
7154 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
7155 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
7156 if (Cond.isInvalid())
7158 return getDerived().RebuildOMPIfClause(Cond.get(), C->getLocStart(),
7159 C->getLParenLoc(), C->getLocEnd());
7162 template <typename Derived>
7163 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
7164 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
7165 if (Cond.isInvalid())
7167 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getLocStart(),
7168 C->getLParenLoc(), C->getLocEnd());
7171 template <typename Derived>
7173 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
7174 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
7175 if (NumThreads.isInvalid())
7177 return getDerived().RebuildOMPNumThreadsClause(
7178 NumThreads.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7181 template <typename Derived>
7183 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
7184 ExprResult E = getDerived().TransformExpr(C->getSafelen());
7187 return getDerived().RebuildOMPSafelenClause(
7188 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7191 template <typename Derived>
7193 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
7194 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
7197 return getDerived().RebuildOMPCollapseClause(
7198 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7201 template <typename Derived>
7203 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
7204 return getDerived().RebuildOMPDefaultClause(
7205 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getLocStart(),
7206 C->getLParenLoc(), C->getLocEnd());
7209 template <typename Derived>
7211 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
7212 return getDerived().RebuildOMPProcBindClause(
7213 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getLocStart(),
7214 C->getLParenLoc(), C->getLocEnd());
7217 template <typename Derived>
7219 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
7220 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
7223 return getDerived().RebuildOMPScheduleClause(
7224 C->getScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
7225 C->getScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
7228 template <typename Derived>
7230 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
7231 // No need to rebuild this clause, no template-dependent parameters.
7235 template <typename Derived>
7237 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
7238 // No need to rebuild this clause, no template-dependent parameters.
7242 template <typename Derived>
7244 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
7245 // No need to rebuild this clause, no template-dependent parameters.
7249 template <typename Derived>
7251 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
7252 // No need to rebuild this clause, no template-dependent parameters.
7256 template <typename Derived>
7257 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
7258 // No need to rebuild this clause, no template-dependent parameters.
7262 template <typename Derived>
7263 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
7264 // No need to rebuild this clause, no template-dependent parameters.
7268 template <typename Derived>
7270 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
7271 // No need to rebuild this clause, no template-dependent parameters.
7275 template <typename Derived>
7277 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
7278 // No need to rebuild this clause, no template-dependent parameters.
7282 template <typename Derived>
7284 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
7285 // No need to rebuild this clause, no template-dependent parameters.
7289 template <typename Derived>
7291 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
7292 llvm::SmallVector<Expr *, 16> Vars;
7293 Vars.reserve(C->varlist_size());
7294 for (auto *VE : C->varlists()) {
7295 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7296 if (EVar.isInvalid())
7298 Vars.push_back(EVar.get());
7300 return getDerived().RebuildOMPPrivateClause(
7301 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7304 template <typename Derived>
7305 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
7306 OMPFirstprivateClause *C) {
7307 llvm::SmallVector<Expr *, 16> Vars;
7308 Vars.reserve(C->varlist_size());
7309 for (auto *VE : C->varlists()) {
7310 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7311 if (EVar.isInvalid())
7313 Vars.push_back(EVar.get());
7315 return getDerived().RebuildOMPFirstprivateClause(
7316 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7319 template <typename Derived>
7321 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
7322 llvm::SmallVector<Expr *, 16> Vars;
7323 Vars.reserve(C->varlist_size());
7324 for (auto *VE : C->varlists()) {
7325 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7326 if (EVar.isInvalid())
7328 Vars.push_back(EVar.get());
7330 return getDerived().RebuildOMPLastprivateClause(
7331 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7334 template <typename Derived>
7336 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
7337 llvm::SmallVector<Expr *, 16> Vars;
7338 Vars.reserve(C->varlist_size());
7339 for (auto *VE : C->varlists()) {
7340 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7341 if (EVar.isInvalid())
7343 Vars.push_back(EVar.get());
7345 return getDerived().RebuildOMPSharedClause(Vars, C->getLocStart(),
7346 C->getLParenLoc(), C->getLocEnd());
7349 template <typename Derived>
7351 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
7352 llvm::SmallVector<Expr *, 16> Vars;
7353 Vars.reserve(C->varlist_size());
7354 for (auto *VE : C->varlists()) {
7355 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7356 if (EVar.isInvalid())
7358 Vars.push_back(EVar.get());
7360 CXXScopeSpec ReductionIdScopeSpec;
7361 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
7363 DeclarationNameInfo NameInfo = C->getNameInfo();
7364 if (NameInfo.getName()) {
7365 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7366 if (!NameInfo.getName())
7369 return getDerived().RebuildOMPReductionClause(
7370 Vars, C->getLocStart(), C->getLParenLoc(), C->getColonLoc(),
7371 C->getLocEnd(), ReductionIdScopeSpec, NameInfo);
7374 template <typename Derived>
7376 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
7377 llvm::SmallVector<Expr *, 16> Vars;
7378 Vars.reserve(C->varlist_size());
7379 for (auto *VE : C->varlists()) {
7380 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7381 if (EVar.isInvalid())
7383 Vars.push_back(EVar.get());
7385 ExprResult Step = getDerived().TransformExpr(C->getStep());
7386 if (Step.isInvalid())
7388 return getDerived().RebuildOMPLinearClause(Vars, Step.get(), C->getLocStart(),
7390 C->getColonLoc(), C->getLocEnd());
7393 template <typename Derived>
7395 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
7396 llvm::SmallVector<Expr *, 16> Vars;
7397 Vars.reserve(C->varlist_size());
7398 for (auto *VE : C->varlists()) {
7399 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7400 if (EVar.isInvalid())
7402 Vars.push_back(EVar.get());
7404 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
7405 if (Alignment.isInvalid())
7407 return getDerived().RebuildOMPAlignedClause(
7408 Vars, Alignment.get(), C->getLocStart(), C->getLParenLoc(),
7409 C->getColonLoc(), C->getLocEnd());
7412 template <typename Derived>
7414 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
7415 llvm::SmallVector<Expr *, 16> Vars;
7416 Vars.reserve(C->varlist_size());
7417 for (auto *VE : C->varlists()) {
7418 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7419 if (EVar.isInvalid())
7421 Vars.push_back(EVar.get());
7423 return getDerived().RebuildOMPCopyinClause(Vars, C->getLocStart(),
7424 C->getLParenLoc(), C->getLocEnd());
7427 template <typename Derived>
7429 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
7430 llvm::SmallVector<Expr *, 16> Vars;
7431 Vars.reserve(C->varlist_size());
7432 for (auto *VE : C->varlists()) {
7433 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7434 if (EVar.isInvalid())
7436 Vars.push_back(EVar.get());
7438 return getDerived().RebuildOMPCopyprivateClause(
7439 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7442 template <typename Derived>
7443 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
7444 llvm::SmallVector<Expr *, 16> Vars;
7445 Vars.reserve(C->varlist_size());
7446 for (auto *VE : C->varlists()) {
7447 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7448 if (EVar.isInvalid())
7450 Vars.push_back(EVar.get());
7452 return getDerived().RebuildOMPFlushClause(Vars, C->getLocStart(),
7453 C->getLParenLoc(), C->getLocEnd());
7456 template <typename Derived>
7458 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
7459 llvm::SmallVector<Expr *, 16> Vars;
7460 Vars.reserve(C->varlist_size());
7461 for (auto *VE : C->varlists()) {
7462 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7463 if (EVar.isInvalid())
7465 Vars.push_back(EVar.get());
7467 return getDerived().RebuildOMPDependClause(
7468 C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
7469 C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7472 //===----------------------------------------------------------------------===//
7473 // Expression transformation
7474 //===----------------------------------------------------------------------===//
7475 template<typename Derived>
7477 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
7478 if (!E->isTypeDependent())
7481 return getDerived().RebuildPredefinedExpr(E->getLocation(),
7485 template<typename Derived>
7487 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
7488 NestedNameSpecifierLoc QualifierLoc;
7489 if (E->getQualifierLoc()) {
7491 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7497 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
7502 DeclarationNameInfo NameInfo = E->getNameInfo();
7503 if (NameInfo.getName()) {
7504 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7505 if (!NameInfo.getName())
7509 if (!getDerived().AlwaysRebuild() &&
7510 QualifierLoc == E->getQualifierLoc() &&
7511 ND == E->getDecl() &&
7512 NameInfo.getName() == E->getDecl()->getDeclName() &&
7513 !E->hasExplicitTemplateArgs()) {
7515 // Mark it referenced in the new context regardless.
7516 // FIXME: this is a bit instantiation-specific.
7517 SemaRef.MarkDeclRefReferenced(E);
7522 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
7523 if (E->hasExplicitTemplateArgs()) {
7524 TemplateArgs = &TransArgs;
7525 TransArgs.setLAngleLoc(E->getLAngleLoc());
7526 TransArgs.setRAngleLoc(E->getRAngleLoc());
7527 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7528 E->getNumTemplateArgs(),
7533 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
7537 template<typename Derived>
7539 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
7543 template<typename Derived>
7545 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
7549 template<typename Derived>
7551 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
7555 template<typename Derived>
7557 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
7561 template<typename Derived>
7563 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
7567 template<typename Derived>
7569 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
7570 if (FunctionDecl *FD = E->getDirectCallee())
7571 SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
7572 return SemaRef.MaybeBindToTemporary(E);
7575 template<typename Derived>
7577 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
7578 ExprResult ControllingExpr =
7579 getDerived().TransformExpr(E->getControllingExpr());
7580 if (ControllingExpr.isInvalid())
7583 SmallVector<Expr *, 4> AssocExprs;
7584 SmallVector<TypeSourceInfo *, 4> AssocTypes;
7585 for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
7586 TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
7588 TypeSourceInfo *AssocType = getDerived().TransformType(TS);
7591 AssocTypes.push_back(AssocType);
7593 AssocTypes.push_back(nullptr);
7596 ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
7597 if (AssocExpr.isInvalid())
7599 AssocExprs.push_back(AssocExpr.get());
7602 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
7605 ControllingExpr.get(),
7610 template<typename Derived>
7612 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
7613 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
7614 if (SubExpr.isInvalid())
7617 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
7620 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
7624 /// \brief The operand of a unary address-of operator has special rules: it's
7625 /// allowed to refer to a non-static member of a class even if there's no 'this'
7626 /// object available.
7627 template<typename Derived>
7629 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
7630 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
7631 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
7633 return getDerived().TransformExpr(E);
7636 template<typename Derived>
7638 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
7640 if (E->getOpcode() == UO_AddrOf)
7641 SubExpr = TransformAddressOfOperand(E->getSubExpr());
7643 SubExpr = TransformExpr(E->getSubExpr());
7644 if (SubExpr.isInvalid())
7647 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
7650 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
7655 template<typename Derived>
7657 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
7658 // Transform the type.
7659 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
7663 // Transform all of the components into components similar to what the
7665 // FIXME: It would be slightly more efficient in the non-dependent case to
7666 // just map FieldDecls, rather than requiring the rebuilder to look for
7667 // the fields again. However, __builtin_offsetof is rare enough in
7668 // template code that we don't care.
7669 bool ExprChanged = false;
7670 typedef Sema::OffsetOfComponent Component;
7671 typedef OffsetOfExpr::OffsetOfNode Node;
7672 SmallVector<Component, 4> Components;
7673 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
7674 const Node &ON = E->getComponent(I);
7676 Comp.isBrackets = true;
7677 Comp.LocStart = ON.getSourceRange().getBegin();
7678 Comp.LocEnd = ON.getSourceRange().getEnd();
7679 switch (ON.getKind()) {
7681 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
7682 ExprResult Index = getDerived().TransformExpr(FromIndex);
7683 if (Index.isInvalid())
7686 ExprChanged = ExprChanged || Index.get() != FromIndex;
7687 Comp.isBrackets = true;
7688 Comp.U.E = Index.get();
7693 case Node::Identifier:
7694 Comp.isBrackets = false;
7695 Comp.U.IdentInfo = ON.getFieldName();
7696 if (!Comp.U.IdentInfo)
7702 // Will be recomputed during the rebuild.
7706 Components.push_back(Comp);
7709 // If nothing changed, retain the existing expression.
7710 if (!getDerived().AlwaysRebuild() &&
7711 Type == E->getTypeSourceInfo() &&
7715 // Build a new offsetof expression.
7716 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
7717 Components.data(), Components.size(),
7721 template<typename Derived>
7723 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
7724 assert(getDerived().AlreadyTransformed(E->getType()) &&
7725 "opaque value expression requires transformation");
7729 template<typename Derived>
7731 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
7735 template<typename Derived>
7737 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
7738 // Rebuild the syntactic form. The original syntactic form has
7739 // opaque-value expressions in it, so strip those away and rebuild
7740 // the result. This is a really awful way of doing this, but the
7741 // better solution (rebuilding the semantic expressions and
7742 // rebinding OVEs as necessary) doesn't work; we'd need
7743 // TreeTransform to not strip away implicit conversions.
7744 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
7745 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
7746 if (result.isInvalid()) return ExprError();
7748 // If that gives us a pseudo-object result back, the pseudo-object
7749 // expression must have been an lvalue-to-rvalue conversion which we
7751 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
7752 result = SemaRef.checkPseudoObjectRValue(result.get());
7757 template<typename Derived>
7759 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
7760 UnaryExprOrTypeTraitExpr *E) {
7761 if (E->isArgumentType()) {
7762 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
7764 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
7768 if (!getDerived().AlwaysRebuild() && OldT == NewT)
7771 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
7773 E->getSourceRange());
7776 // C++0x [expr.sizeof]p1:
7777 // The operand is either an expression, which is an unevaluated operand
7779 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
7780 Sema::ReuseLambdaContextDecl);
7782 // Try to recover if we have something like sizeof(T::X) where X is a type.
7783 // Notably, there must be *exactly* one set of parens if X is a type.
7784 TypeSourceInfo *RecoveryTSI = nullptr;
7786 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
7788 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
7789 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
7790 PE, DRE, false, &RecoveryTSI);
7792 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
7795 return getDerived().RebuildUnaryExprOrTypeTrait(
7796 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
7797 } else if (SubExpr.isInvalid())
7800 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
7803 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
7804 E->getOperatorLoc(),
7806 E->getSourceRange());
7809 template<typename Derived>
7811 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
7812 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7813 if (LHS.isInvalid())
7816 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7817 if (RHS.isInvalid())
7821 if (!getDerived().AlwaysRebuild() &&
7822 LHS.get() == E->getLHS() &&
7823 RHS.get() == E->getRHS())
7826 return getDerived().RebuildArraySubscriptExpr(LHS.get(),
7827 /*FIXME:*/E->getLHS()->getLocStart(),
7829 E->getRBracketLoc());
7832 template<typename Derived>
7834 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
7835 // Transform the callee.
7836 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
7837 if (Callee.isInvalid())
7840 // Transform arguments.
7841 bool ArgChanged = false;
7842 SmallVector<Expr*, 8> Args;
7843 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
7847 if (!getDerived().AlwaysRebuild() &&
7848 Callee.get() == E->getCallee() &&
7850 return SemaRef.MaybeBindToTemporary(E);
7852 // FIXME: Wrong source location information for the '('.
7853 SourceLocation FakeLParenLoc
7854 = ((Expr *)Callee.get())->getSourceRange().getBegin();
7855 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
7860 template<typename Derived>
7862 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
7863 ExprResult Base = getDerived().TransformExpr(E->getBase());
7864 if (Base.isInvalid())
7867 NestedNameSpecifierLoc QualifierLoc;
7868 if (E->hasQualifier()) {
7870 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7875 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
7878 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
7879 E->getMemberDecl()));
7883 NamedDecl *FoundDecl = E->getFoundDecl();
7884 if (FoundDecl == E->getMemberDecl()) {
7887 FoundDecl = cast_or_null<NamedDecl>(
7888 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
7893 if (!getDerived().AlwaysRebuild() &&
7894 Base.get() == E->getBase() &&
7895 QualifierLoc == E->getQualifierLoc() &&
7896 Member == E->getMemberDecl() &&
7897 FoundDecl == E->getFoundDecl() &&
7898 !E->hasExplicitTemplateArgs()) {
7900 // Mark it referenced in the new context regardless.
7901 // FIXME: this is a bit instantiation-specific.
7902 SemaRef.MarkMemberReferenced(E);
7907 TemplateArgumentListInfo TransArgs;
7908 if (E->hasExplicitTemplateArgs()) {
7909 TransArgs.setLAngleLoc(E->getLAngleLoc());
7910 TransArgs.setRAngleLoc(E->getRAngleLoc());
7911 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7912 E->getNumTemplateArgs(),
7917 // FIXME: Bogus source location for the operator
7918 SourceLocation FakeOperatorLoc =
7919 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
7921 // FIXME: to do this check properly, we will need to preserve the
7922 // first-qualifier-in-scope here, just in case we had a dependent
7923 // base (and therefore couldn't do the check) and a
7924 // nested-name-qualifier (and therefore could do the lookup).
7925 NamedDecl *FirstQualifierInScope = nullptr;
7927 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
7931 E->getMemberNameInfo(),
7934 (E->hasExplicitTemplateArgs()
7935 ? &TransArgs : nullptr),
7936 FirstQualifierInScope);
7939 template<typename Derived>
7941 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
7942 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7943 if (LHS.isInvalid())
7946 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7947 if (RHS.isInvalid())
7950 if (!getDerived().AlwaysRebuild() &&
7951 LHS.get() == E->getLHS() &&
7952 RHS.get() == E->getRHS())
7955 Sema::FPContractStateRAII FPContractState(getSema());
7956 getSema().FPFeatures.fp_contract = E->isFPContractable();
7958 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
7959 LHS.get(), RHS.get());
7962 template<typename Derived>
7964 TreeTransform<Derived>::TransformCompoundAssignOperator(
7965 CompoundAssignOperator *E) {
7966 return getDerived().TransformBinaryOperator(E);
7969 template<typename Derived>
7970 ExprResult TreeTransform<Derived>::
7971 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
7972 // Just rebuild the common and RHS expressions and see whether we
7975 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
7976 if (commonExpr.isInvalid())
7979 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
7980 if (rhs.isInvalid())
7983 if (!getDerived().AlwaysRebuild() &&
7984 commonExpr.get() == e->getCommon() &&
7985 rhs.get() == e->getFalseExpr())
7988 return getDerived().RebuildConditionalOperator(commonExpr.get(),
7989 e->getQuestionLoc(),
7995 template<typename Derived>
7997 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
7998 ExprResult Cond = getDerived().TransformExpr(E->getCond());
7999 if (Cond.isInvalid())
8002 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
8003 if (LHS.isInvalid())
8006 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
8007 if (RHS.isInvalid())
8010 if (!getDerived().AlwaysRebuild() &&
8011 Cond.get() == E->getCond() &&
8012 LHS.get() == E->getLHS() &&
8013 RHS.get() == E->getRHS())
8016 return getDerived().RebuildConditionalOperator(Cond.get(),
8017 E->getQuestionLoc(),
8023 template<typename Derived>
8025 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
8026 // Implicit casts are eliminated during transformation, since they
8027 // will be recomputed by semantic analysis after transformation.
8028 return getDerived().TransformExpr(E->getSubExprAsWritten());
8031 template<typename Derived>
8033 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
8034 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
8039 = getDerived().TransformExpr(E->getSubExprAsWritten());
8040 if (SubExpr.isInvalid())
8043 if (!getDerived().AlwaysRebuild() &&
8044 Type == E->getTypeInfoAsWritten() &&
8045 SubExpr.get() == E->getSubExpr())
8048 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
8054 template<typename Derived>
8056 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
8057 TypeSourceInfo *OldT = E->getTypeSourceInfo();
8058 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
8062 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
8063 if (Init.isInvalid())
8066 if (!getDerived().AlwaysRebuild() &&
8068 Init.get() == E->getInitializer())
8069 return SemaRef.MaybeBindToTemporary(E);
8071 // Note: the expression type doesn't necessarily match the
8072 // type-as-written, but that's okay, because it should always be
8073 // derivable from the initializer.
8075 return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
8076 /*FIXME:*/E->getInitializer()->getLocEnd(),
8080 template<typename Derived>
8082 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
8083 ExprResult Base = getDerived().TransformExpr(E->getBase());
8084 if (Base.isInvalid())
8087 if (!getDerived().AlwaysRebuild() &&
8088 Base.get() == E->getBase())
8091 // FIXME: Bad source location
8092 SourceLocation FakeOperatorLoc =
8093 SemaRef.getLocForEndOfToken(E->getBase()->getLocEnd());
8094 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
8095 E->getAccessorLoc(),
8099 template<typename Derived>
8101 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
8102 if (InitListExpr *Syntactic = E->getSyntacticForm())
8105 bool InitChanged = false;
8107 SmallVector<Expr*, 4> Inits;
8108 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
8109 Inits, &InitChanged))
8112 if (!getDerived().AlwaysRebuild() && !InitChanged) {
8113 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
8114 // in some cases. We can't reuse it in general, because the syntactic and
8115 // semantic forms are linked, and we can't know that semantic form will
8116 // match even if the syntactic form does.
8119 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
8120 E->getRBraceLoc(), E->getType());
8123 template<typename Derived>
8125 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
8128 // transform the initializer value
8129 ExprResult Init = getDerived().TransformExpr(E->getInit());
8130 if (Init.isInvalid())
8133 // transform the designators.
8134 SmallVector<Expr*, 4> ArrayExprs;
8135 bool ExprChanged = false;
8136 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
8137 DEnd = E->designators_end();
8139 if (D->isFieldDesignator()) {
8140 Desig.AddDesignator(Designator::getField(D->getFieldName(),
8146 if (D->isArrayDesignator()) {
8147 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
8148 if (Index.isInvalid())
8151 Desig.AddDesignator(Designator::getArray(Index.get(),
8152 D->getLBracketLoc()));
8154 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
8155 ArrayExprs.push_back(Index.get());
8159 assert(D->isArrayRangeDesignator() && "New kind of designator?");
8161 = getDerived().TransformExpr(E->getArrayRangeStart(*D));
8162 if (Start.isInvalid())
8165 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
8166 if (End.isInvalid())
8169 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
8171 D->getLBracketLoc(),
8172 D->getEllipsisLoc()));
8174 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
8175 End.get() != E->getArrayRangeEnd(*D);
8177 ArrayExprs.push_back(Start.get());
8178 ArrayExprs.push_back(End.get());
8181 if (!getDerived().AlwaysRebuild() &&
8182 Init.get() == E->getInit() &&
8186 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
8187 E->getEqualOrColonLoc(),
8188 E->usesGNUSyntax(), Init.get());
8191 // Seems that if TransformInitListExpr() only works on the syntactic form of an
8192 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
8193 template<typename Derived>
8195 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
8196 DesignatedInitUpdateExpr *E) {
8197 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
8202 template<typename Derived>
8204 TreeTransform<Derived>::TransformNoInitExpr(
8206 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
8210 template<typename Derived>
8212 TreeTransform<Derived>::TransformImplicitValueInitExpr(
8213 ImplicitValueInitExpr *E) {
8214 TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
8216 // FIXME: Will we ever have proper type location here? Will we actually
8217 // need to transform the type?
8218 QualType T = getDerived().TransformType(E->getType());
8222 if (!getDerived().AlwaysRebuild() &&
8226 return getDerived().RebuildImplicitValueInitExpr(T);
8229 template<typename Derived>
8231 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
8232 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
8236 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8237 if (SubExpr.isInvalid())
8240 if (!getDerived().AlwaysRebuild() &&
8241 TInfo == E->getWrittenTypeInfo() &&
8242 SubExpr.get() == E->getSubExpr())
8245 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
8246 TInfo, E->getRParenLoc());
8249 template<typename Derived>
8251 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
8252 bool ArgumentChanged = false;
8253 SmallVector<Expr*, 4> Inits;
8254 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
8258 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
8263 /// \brief Transform an address-of-label expression.
8265 /// By default, the transformation of an address-of-label expression always
8266 /// rebuilds the expression, so that the label identifier can be resolved to
8267 /// the corresponding label statement by semantic analysis.
8268 template<typename Derived>
8270 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
8271 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
8276 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
8277 cast<LabelDecl>(LD));
8280 template<typename Derived>
8282 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
8283 SemaRef.ActOnStartStmtExpr();
8285 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
8286 if (SubStmt.isInvalid()) {
8287 SemaRef.ActOnStmtExprError();
8291 if (!getDerived().AlwaysRebuild() &&
8292 SubStmt.get() == E->getSubStmt()) {
8293 // Calling this an 'error' is unintuitive, but it does the right thing.
8294 SemaRef.ActOnStmtExprError();
8295 return SemaRef.MaybeBindToTemporary(E);
8298 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
8303 template<typename Derived>
8305 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
8306 ExprResult Cond = getDerived().TransformExpr(E->getCond());
8307 if (Cond.isInvalid())
8310 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
8311 if (LHS.isInvalid())
8314 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
8315 if (RHS.isInvalid())
8318 if (!getDerived().AlwaysRebuild() &&
8319 Cond.get() == E->getCond() &&
8320 LHS.get() == E->getLHS() &&
8321 RHS.get() == E->getRHS())
8324 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
8325 Cond.get(), LHS.get(), RHS.get(),
8329 template<typename Derived>
8331 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
8335 template<typename Derived>
8337 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8338 switch (E->getOperator()) {
8342 case OO_Array_Delete:
8343 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
8346 // This is a call to an object's operator().
8347 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
8349 // Transform the object itself.
8350 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
8351 if (Object.isInvalid())
8354 // FIXME: Poor location information
8355 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
8356 static_cast<Expr *>(Object.get())->getLocEnd());
8358 // Transform the call arguments.
8359 SmallVector<Expr*, 8> Args;
8360 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
8364 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
8369 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8371 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
8372 #include "clang/Basic/OperatorKinds.def"
8377 case OO_Conditional:
8378 llvm_unreachable("conditional operator is not actually overloadable");
8381 case NUM_OVERLOADED_OPERATORS:
8382 llvm_unreachable("not an overloaded operator?");
8385 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
8386 if (Callee.isInvalid())
8390 if (E->getOperator() == OO_Amp)
8391 First = getDerived().TransformAddressOfOperand(E->getArg(0));
8393 First = getDerived().TransformExpr(E->getArg(0));
8394 if (First.isInvalid())
8398 if (E->getNumArgs() == 2) {
8399 Second = getDerived().TransformExpr(E->getArg(1));
8400 if (Second.isInvalid())
8404 if (!getDerived().AlwaysRebuild() &&
8405 Callee.get() == E->getCallee() &&
8406 First.get() == E->getArg(0) &&
8407 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
8408 return SemaRef.MaybeBindToTemporary(E);
8410 Sema::FPContractStateRAII FPContractState(getSema());
8411 getSema().FPFeatures.fp_contract = E->isFPContractable();
8413 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
8414 E->getOperatorLoc(),
8420 template<typename Derived>
8422 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
8423 return getDerived().TransformCallExpr(E);
8426 template<typename Derived>
8428 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
8429 // Transform the callee.
8430 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
8431 if (Callee.isInvalid())
8434 // Transform exec config.
8435 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
8439 // Transform arguments.
8440 bool ArgChanged = false;
8441 SmallVector<Expr*, 8> Args;
8442 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
8446 if (!getDerived().AlwaysRebuild() &&
8447 Callee.get() == E->getCallee() &&
8449 return SemaRef.MaybeBindToTemporary(E);
8451 // FIXME: Wrong source location information for the '('.
8452 SourceLocation FakeLParenLoc
8453 = ((Expr *)Callee.get())->getSourceRange().getBegin();
8454 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
8456 E->getRParenLoc(), EC.get());
8459 template<typename Derived>
8461 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
8462 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
8467 = getDerived().TransformExpr(E->getSubExprAsWritten());
8468 if (SubExpr.isInvalid())
8471 if (!getDerived().AlwaysRebuild() &&
8472 Type == E->getTypeInfoAsWritten() &&
8473 SubExpr.get() == E->getSubExpr())
8475 return getDerived().RebuildCXXNamedCastExpr(
8476 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
8477 Type, E->getAngleBrackets().getEnd(),
8478 // FIXME. this should be '(' location
8479 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
8482 template<typename Derived>
8484 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
8485 return getDerived().TransformCXXNamedCastExpr(E);
8488 template<typename Derived>
8490 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
8491 return getDerived().TransformCXXNamedCastExpr(E);
8494 template<typename Derived>
8496 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
8497 CXXReinterpretCastExpr *E) {
8498 return getDerived().TransformCXXNamedCastExpr(E);
8501 template<typename Derived>
8503 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
8504 return getDerived().TransformCXXNamedCastExpr(E);
8507 template<typename Derived>
8509 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
8510 CXXFunctionalCastExpr *E) {
8511 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
8516 = getDerived().TransformExpr(E->getSubExprAsWritten());
8517 if (SubExpr.isInvalid())
8520 if (!getDerived().AlwaysRebuild() &&
8521 Type == E->getTypeInfoAsWritten() &&
8522 SubExpr.get() == E->getSubExpr())
8525 return getDerived().RebuildCXXFunctionalCastExpr(Type,
8531 template<typename Derived>
8533 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
8534 if (E->isTypeOperand()) {
8535 TypeSourceInfo *TInfo
8536 = getDerived().TransformType(E->getTypeOperandSourceInfo());
8540 if (!getDerived().AlwaysRebuild() &&
8541 TInfo == E->getTypeOperandSourceInfo())
8544 return getDerived().RebuildCXXTypeidExpr(E->getType(),
8550 // We don't know whether the subexpression is potentially evaluated until
8551 // after we perform semantic analysis. We speculatively assume it is
8552 // unevaluated; it will get fixed later if the subexpression is in fact
8553 // potentially evaluated.
8554 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
8555 Sema::ReuseLambdaContextDecl);
8557 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
8558 if (SubExpr.isInvalid())
8561 if (!getDerived().AlwaysRebuild() &&
8562 SubExpr.get() == E->getExprOperand())
8565 return getDerived().RebuildCXXTypeidExpr(E->getType(),
8571 template<typename Derived>
8573 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
8574 if (E->isTypeOperand()) {
8575 TypeSourceInfo *TInfo
8576 = getDerived().TransformType(E->getTypeOperandSourceInfo());
8580 if (!getDerived().AlwaysRebuild() &&
8581 TInfo == E->getTypeOperandSourceInfo())
8584 return getDerived().RebuildCXXUuidofExpr(E->getType(),
8590 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8592 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
8593 if (SubExpr.isInvalid())
8596 if (!getDerived().AlwaysRebuild() &&
8597 SubExpr.get() == E->getExprOperand())
8600 return getDerived().RebuildCXXUuidofExpr(E->getType(),
8606 template<typename Derived>
8608 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
8612 template<typename Derived>
8614 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
8615 CXXNullPtrLiteralExpr *E) {
8619 template<typename Derived>
8621 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
8622 QualType T = getSema().getCurrentThisType();
8624 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
8625 // Make sure that we capture 'this'.
8626 getSema().CheckCXXThisCapture(E->getLocStart());
8630 return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
8633 template<typename Derived>
8635 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
8636 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8637 if (SubExpr.isInvalid())
8640 if (!getDerived().AlwaysRebuild() &&
8641 SubExpr.get() == E->getSubExpr())
8644 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
8645 E->isThrownVariableInScope());
8648 template<typename Derived>
8650 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
8652 = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
8657 if (!getDerived().AlwaysRebuild() &&
8658 Param == E->getParam())
8661 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
8664 template<typename Derived>
8666 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
8668 = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
8673 if (!getDerived().AlwaysRebuild() && Field == E->getField())
8676 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
8679 template<typename Derived>
8681 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
8682 CXXScalarValueInitExpr *E) {
8683 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
8687 if (!getDerived().AlwaysRebuild() &&
8688 T == E->getTypeSourceInfo())
8691 return getDerived().RebuildCXXScalarValueInitExpr(T,
8692 /*FIXME:*/T->getTypeLoc().getEndLoc(),
8696 template<typename Derived>
8698 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
8699 // Transform the type that we're allocating
8700 TypeSourceInfo *AllocTypeInfo
8701 = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
8705 // Transform the size of the array we're allocating (if any).
8706 ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
8707 if (ArraySize.isInvalid())
8710 // Transform the placement arguments (if any).
8711 bool ArgumentChanged = false;
8712 SmallVector<Expr*, 8> PlacementArgs;
8713 if (getDerived().TransformExprs(E->getPlacementArgs(),
8714 E->getNumPlacementArgs(), true,
8715 PlacementArgs, &ArgumentChanged))
8718 // Transform the initializer (if any).
8719 Expr *OldInit = E->getInitializer();
8722 NewInit = getDerived().TransformInitializer(OldInit, true);
8723 if (NewInit.isInvalid())
8726 // Transform new operator and delete operator.
8727 FunctionDecl *OperatorNew = nullptr;
8728 if (E->getOperatorNew()) {
8729 OperatorNew = cast_or_null<FunctionDecl>(
8730 getDerived().TransformDecl(E->getLocStart(),
8731 E->getOperatorNew()));
8736 FunctionDecl *OperatorDelete = nullptr;
8737 if (E->getOperatorDelete()) {
8738 OperatorDelete = cast_or_null<FunctionDecl>(
8739 getDerived().TransformDecl(E->getLocStart(),
8740 E->getOperatorDelete()));
8741 if (!OperatorDelete)
8745 if (!getDerived().AlwaysRebuild() &&
8746 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
8747 ArraySize.get() == E->getArraySize() &&
8748 NewInit.get() == OldInit &&
8749 OperatorNew == E->getOperatorNew() &&
8750 OperatorDelete == E->getOperatorDelete() &&
8752 // Mark any declarations we need as referenced.
8753 // FIXME: instantiation-specific.
8755 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
8757 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
8759 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
8760 QualType ElementType
8761 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
8762 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
8763 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
8764 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
8765 SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
8773 QualType AllocType = AllocTypeInfo->getType();
8774 if (!ArraySize.get()) {
8775 // If no array size was specified, but the new expression was
8776 // instantiated with an array type (e.g., "new T" where T is
8777 // instantiated with "int[4]"), extract the outer bound from the
8778 // array type as our array size. We do this with constant and
8779 // dependently-sized array types.
8780 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
8783 } else if (const ConstantArrayType *ConsArrayT
8784 = dyn_cast<ConstantArrayType>(ArrayT)) {
8785 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
8786 SemaRef.Context.getSizeType(),
8787 /*FIXME:*/ E->getLocStart());
8788 AllocType = ConsArrayT->getElementType();
8789 } else if (const DependentSizedArrayType *DepArrayT
8790 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
8791 if (DepArrayT->getSizeExpr()) {
8792 ArraySize = DepArrayT->getSizeExpr();
8793 AllocType = DepArrayT->getElementType();
8798 return getDerived().RebuildCXXNewExpr(E->getLocStart(),
8800 /*FIXME:*/E->getLocStart(),
8802 /*FIXME:*/E->getLocStart(),
8803 E->getTypeIdParens(),
8807 E->getDirectInitRange(),
8811 template<typename Derived>
8813 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
8814 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
8815 if (Operand.isInvalid())
8818 // Transform the delete operator, if known.
8819 FunctionDecl *OperatorDelete = nullptr;
8820 if (E->getOperatorDelete()) {
8821 OperatorDelete = cast_or_null<FunctionDecl>(
8822 getDerived().TransformDecl(E->getLocStart(),
8823 E->getOperatorDelete()));
8824 if (!OperatorDelete)
8828 if (!getDerived().AlwaysRebuild() &&
8829 Operand.get() == E->getArgument() &&
8830 OperatorDelete == E->getOperatorDelete()) {
8831 // Mark any declarations we need as referenced.
8832 // FIXME: instantiation-specific.
8834 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
8836 if (!E->getArgument()->isTypeDependent()) {
8837 QualType Destroyed = SemaRef.Context.getBaseElementType(
8838 E->getDestroyedType());
8839 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
8840 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
8841 SemaRef.MarkFunctionReferenced(E->getLocStart(),
8842 SemaRef.LookupDestructor(Record));
8849 return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
8850 E->isGlobalDelete(),
8855 template<typename Derived>
8857 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
8858 CXXPseudoDestructorExpr *E) {
8859 ExprResult Base = getDerived().TransformExpr(E->getBase());
8860 if (Base.isInvalid())
8863 ParsedType ObjectTypePtr;
8864 bool MayBePseudoDestructor = false;
8865 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
8866 E->getOperatorLoc(),
8867 E->isArrow()? tok::arrow : tok::period,
8869 MayBePseudoDestructor);
8870 if (Base.isInvalid())
8873 QualType ObjectType = ObjectTypePtr.get();
8874 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
8877 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
8882 SS.Adopt(QualifierLoc);
8884 PseudoDestructorTypeStorage Destroyed;
8885 if (E->getDestroyedTypeInfo()) {
8886 TypeSourceInfo *DestroyedTypeInfo
8887 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
8888 ObjectType, nullptr, SS);
8889 if (!DestroyedTypeInfo)
8891 Destroyed = DestroyedTypeInfo;
8892 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
8893 // We aren't likely to be able to resolve the identifier down to a type
8894 // now anyway, so just retain the identifier.
8895 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
8896 E->getDestroyedTypeLoc());
8898 // Look for a destructor known with the given name.
8899 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
8900 *E->getDestroyedTypeIdentifier(),
8901 E->getDestroyedTypeLoc(),
8909 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
8910 E->getDestroyedTypeLoc());
8913 TypeSourceInfo *ScopeTypeInfo = nullptr;
8914 if (E->getScopeTypeInfo()) {
8915 CXXScopeSpec EmptySS;
8916 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
8917 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
8922 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
8923 E->getOperatorLoc(),
8927 E->getColonColonLoc(),
8932 template<typename Derived>
8934 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
8935 UnresolvedLookupExpr *Old) {
8936 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
8937 Sema::LookupOrdinaryName);
8939 // Transform all the decls.
8940 for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
8941 E = Old->decls_end(); I != E; ++I) {
8942 NamedDecl *InstD = static_cast<NamedDecl*>(
8943 getDerived().TransformDecl(Old->getNameLoc(),
8946 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
8947 // This can happen because of dependent hiding.
8948 if (isa<UsingShadowDecl>(*I))
8956 // Expand using declarations.
8957 if (isa<UsingDecl>(InstD)) {
8958 UsingDecl *UD = cast<UsingDecl>(InstD);
8959 for (auto *I : UD->shadows())
8967 // Resolve a kind, but don't do any further analysis. If it's
8968 // ambiguous, the callee needs to deal with it.
8971 // Rebuild the nested-name qualifier, if present.
8973 if (Old->getQualifierLoc()) {
8974 NestedNameSpecifierLoc QualifierLoc
8975 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
8979 SS.Adopt(QualifierLoc);
8982 if (Old->getNamingClass()) {
8983 CXXRecordDecl *NamingClass
8984 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
8986 Old->getNamingClass()));
8992 R.setNamingClass(NamingClass);
8995 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
8997 // If we have neither explicit template arguments, nor the template keyword,
8998 // it's a normal declaration name.
8999 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid())
9000 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
9002 // If we have template arguments, rebuild them, then rebuild the
9003 // templateid expression.
9004 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
9005 if (Old->hasExplicitTemplateArgs() &&
9006 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
9007 Old->getNumTemplateArgs(),
9013 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
9014 Old->requiresADL(), &TransArgs);
9017 template<typename Derived>
9019 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
9020 bool ArgChanged = false;
9021 SmallVector<TypeSourceInfo *, 4> Args;
9022 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
9023 TypeSourceInfo *From = E->getArg(I);
9024 TypeLoc FromTL = From->getTypeLoc();
9025 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
9027 TLB.reserve(FromTL.getFullDataSize());
9028 QualType To = getDerived().TransformType(TLB, FromTL);
9032 if (To == From->getType())
9033 Args.push_back(From);
9035 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
9043 // We have a pack expansion. Instantiate it.
9044 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
9045 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
9046 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
9047 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
9049 // Determine whether the set of unexpanded parameter packs can and should
9052 bool RetainExpansion = false;
9053 Optional<unsigned> OrigNumExpansions =
9054 ExpansionTL.getTypePtr()->getNumExpansions();
9055 Optional<unsigned> NumExpansions = OrigNumExpansions;
9056 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
9057 PatternTL.getSourceRange(),
9059 Expand, RetainExpansion,
9064 // The transform has determined that we should perform a simple
9065 // transformation on the pack expansion, producing another pack
9067 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
9070 TLB.reserve(From->getTypeLoc().getFullDataSize());
9072 QualType To = getDerived().TransformType(TLB, PatternTL);
9076 To = getDerived().RebuildPackExpansionType(To,
9077 PatternTL.getSourceRange(),
9078 ExpansionTL.getEllipsisLoc(),
9083 PackExpansionTypeLoc ToExpansionTL
9084 = TLB.push<PackExpansionTypeLoc>(To);
9085 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
9086 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
9090 // Expand the pack expansion by substituting for each argument in the
9092 for (unsigned I = 0; I != *NumExpansions; ++I) {
9093 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
9095 TLB.reserve(PatternTL.getFullDataSize());
9096 QualType To = getDerived().TransformType(TLB, PatternTL);
9100 if (To->containsUnexpandedParameterPack()) {
9101 To = getDerived().RebuildPackExpansionType(To,
9102 PatternTL.getSourceRange(),
9103 ExpansionTL.getEllipsisLoc(),
9108 PackExpansionTypeLoc ToExpansionTL
9109 = TLB.push<PackExpansionTypeLoc>(To);
9110 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
9113 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
9116 if (!RetainExpansion)
9119 // If we're supposed to retain a pack expansion, do so by temporarily
9120 // forgetting the partially-substituted parameter pack.
9121 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
9124 TLB.reserve(From->getTypeLoc().getFullDataSize());
9126 QualType To = getDerived().TransformType(TLB, PatternTL);
9130 To = getDerived().RebuildPackExpansionType(To,
9131 PatternTL.getSourceRange(),
9132 ExpansionTL.getEllipsisLoc(),
9137 PackExpansionTypeLoc ToExpansionTL
9138 = TLB.push<PackExpansionTypeLoc>(To);
9139 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
9140 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
9143 if (!getDerived().AlwaysRebuild() && !ArgChanged)
9146 return getDerived().RebuildTypeTrait(E->getTrait(),
9152 template<typename Derived>
9154 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
9155 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
9159 if (!getDerived().AlwaysRebuild() &&
9160 T == E->getQueriedTypeSourceInfo())
9165 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
9166 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
9167 if (SubExpr.isInvalid())
9170 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
9174 return getDerived().RebuildArrayTypeTrait(E->getTrait(),
9181 template<typename Derived>
9183 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
9186 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
9187 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
9188 if (SubExpr.isInvalid())
9191 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
9195 return getDerived().RebuildExpressionTrait(
9196 E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
9199 template <typename Derived>
9200 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
9201 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
9202 TypeSourceInfo **RecoveryTSI) {
9203 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
9204 DRE, AddrTaken, RecoveryTSI);
9206 // Propagate both errors and recovered types, which return ExprEmpty.
9207 if (!NewDRE.isUsable())
9210 // We got an expr, wrap it up in parens.
9211 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
9213 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
9217 template <typename Derived>
9218 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
9219 DependentScopeDeclRefExpr *E) {
9220 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
9224 template<typename Derived>
9226 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
9227 DependentScopeDeclRefExpr *E,
9228 bool IsAddressOfOperand,
9229 TypeSourceInfo **RecoveryTSI) {
9230 assert(E->getQualifierLoc());
9231 NestedNameSpecifierLoc QualifierLoc
9232 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9235 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9237 // TODO: If this is a conversion-function-id, verify that the
9238 // destination type name (if present) resolves the same way after
9239 // instantiation as it did in the local scope.
9241 DeclarationNameInfo NameInfo
9242 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
9243 if (!NameInfo.getName())
9246 if (!E->hasExplicitTemplateArgs()) {
9247 if (!getDerived().AlwaysRebuild() &&
9248 QualifierLoc == E->getQualifierLoc() &&
9249 // Note: it is sufficient to compare the Name component of NameInfo:
9250 // if name has not changed, DNLoc has not changed either.
9251 NameInfo.getName() == E->getDeclName())
9254 return getDerived().RebuildDependentScopeDeclRefExpr(
9255 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
9256 IsAddressOfOperand, RecoveryTSI);
9259 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
9260 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9261 E->getNumTemplateArgs(),
9265 return getDerived().RebuildDependentScopeDeclRefExpr(
9266 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
9270 template<typename Derived>
9272 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
9273 // CXXConstructExprs other than for list-initialization and
9274 // CXXTemporaryObjectExpr are always implicit, so when we have
9275 // a 1-argument construction we just transform that argument.
9276 if ((E->getNumArgs() == 1 ||
9277 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
9278 (!getDerived().DropCallArgument(E->getArg(0))) &&
9279 !E->isListInitialization())
9280 return getDerived().TransformExpr(E->getArg(0));
9282 TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
9284 QualType T = getDerived().TransformType(E->getType());
9288 CXXConstructorDecl *Constructor
9289 = cast_or_null<CXXConstructorDecl>(
9290 getDerived().TransformDecl(E->getLocStart(),
9291 E->getConstructor()));
9295 bool ArgumentChanged = false;
9296 SmallVector<Expr*, 8> Args;
9297 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9301 if (!getDerived().AlwaysRebuild() &&
9302 T == E->getType() &&
9303 Constructor == E->getConstructor() &&
9305 // Mark the constructor as referenced.
9306 // FIXME: Instantiation-specific
9307 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
9311 return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
9312 Constructor, E->isElidable(),
9314 E->hadMultipleCandidates(),
9315 E->isListInitialization(),
9316 E->isStdInitListInitialization(),
9317 E->requiresZeroInitialization(),
9318 E->getConstructionKind(),
9319 E->getParenOrBraceRange());
9322 /// \brief Transform a C++ temporary-binding expression.
9324 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
9325 /// transform the subexpression and return that.
9326 template<typename Derived>
9328 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
9329 return getDerived().TransformExpr(E->getSubExpr());
9332 /// \brief Transform a C++ expression that contains cleanups that should
9333 /// be run after the expression is evaluated.
9335 /// Since ExprWithCleanups nodes are implicitly generated, we
9336 /// just transform the subexpression and return that.
9337 template<typename Derived>
9339 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
9340 return getDerived().TransformExpr(E->getSubExpr());
9343 template<typename Derived>
9345 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
9346 CXXTemporaryObjectExpr *E) {
9347 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9351 CXXConstructorDecl *Constructor
9352 = cast_or_null<CXXConstructorDecl>(
9353 getDerived().TransformDecl(E->getLocStart(),
9354 E->getConstructor()));
9358 bool ArgumentChanged = false;
9359 SmallVector<Expr*, 8> Args;
9360 Args.reserve(E->getNumArgs());
9361 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9365 if (!getDerived().AlwaysRebuild() &&
9366 T == E->getTypeSourceInfo() &&
9367 Constructor == E->getConstructor() &&
9369 // FIXME: Instantiation-specific
9370 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
9371 return SemaRef.MaybeBindToTemporary(E);
9374 // FIXME: Pass in E->isListInitialization().
9375 return getDerived().RebuildCXXTemporaryObjectExpr(T,
9376 /*FIXME:*/T->getTypeLoc().getEndLoc(),
9381 template<typename Derived>
9383 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
9384 // Transform any init-capture expressions before entering the scope of the
9385 // lambda body, because they are not semantically within that scope.
9386 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
9387 SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
9388 InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
9389 E->explicit_capture_begin());
9390 for (LambdaExpr::capture_iterator C = E->capture_begin(),
9391 CEnd = E->capture_end();
9393 if (!E->isInitCapture(C))
9395 EnterExpressionEvaluationContext EEEC(getSema(),
9396 Sema::PotentiallyEvaluated);
9397 ExprResult NewExprInitResult = getDerived().TransformInitializer(
9398 C->getCapturedVar()->getInit(),
9399 C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
9401 if (NewExprInitResult.isInvalid())
9403 Expr *NewExprInit = NewExprInitResult.get();
9405 VarDecl *OldVD = C->getCapturedVar();
9406 QualType NewInitCaptureType =
9407 getSema().performLambdaInitCaptureInitialization(C->getLocation(),
9408 OldVD->getType()->isReferenceType(), OldVD->getIdentifier(),
9410 NewExprInitResult = NewExprInit;
9411 InitCaptureExprsAndTypes[C - E->capture_begin()] =
9412 std::make_pair(NewExprInitResult, NewInitCaptureType);
9415 // Transform the template parameters, and add them to the current
9416 // instantiation scope. The null case is handled correctly.
9417 auto TPL = getDerived().TransformTemplateParameterList(
9418 E->getTemplateParameterList());
9420 // Transform the type of the original lambda's call operator.
9421 // The transformation MUST be done in the CurrentInstantiationScope since
9422 // it introduces a mapping of the original to the newly created
9423 // transformed parameters.
9424 TypeSourceInfo *NewCallOpTSI = nullptr;
9426 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
9427 FunctionProtoTypeLoc OldCallOpFPTL =
9428 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
9430 TypeLocBuilder NewCallOpTLBuilder;
9431 SmallVector<QualType, 4> ExceptionStorage;
9432 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
9433 QualType NewCallOpType = TransformFunctionProtoType(
9434 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, 0,
9435 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
9436 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
9437 ExceptionStorage, Changed);
9439 if (NewCallOpType.isNull())
9441 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
9445 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
9446 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
9447 LSI->GLTemplateParameterList = TPL;
9449 // Create the local class that will describe the lambda.
9450 CXXRecordDecl *Class
9451 = getSema().createLambdaClosureType(E->getIntroducerRange(),
9453 /*KnownDependent=*/false,
9454 E->getCaptureDefault());
9455 getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
9457 // Build the call operator.
9458 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
9459 Class, E->getIntroducerRange(), NewCallOpTSI,
9460 E->getCallOperator()->getLocEnd(),
9461 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams());
9462 LSI->CallOperator = NewCallOperator;
9464 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
9465 getDerived().transformedLocalDecl(E->getCallOperator(), NewCallOperator);
9467 // Introduce the context of the call operator.
9468 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
9469 /*NewThisContext*/false);
9471 // Enter the scope of the lambda.
9472 getSema().buildLambdaScope(LSI, NewCallOperator,
9473 E->getIntroducerRange(),
9474 E->getCaptureDefault(),
9475 E->getCaptureDefaultLoc(),
9476 E->hasExplicitParameters(),
9477 E->hasExplicitResultType(),
9480 bool Invalid = false;
9482 // Transform captures.
9483 bool FinishedExplicitCaptures = false;
9484 for (LambdaExpr::capture_iterator C = E->capture_begin(),
9485 CEnd = E->capture_end();
9487 // When we hit the first implicit capture, tell Sema that we've finished
9488 // the list of explicit captures.
9489 if (!FinishedExplicitCaptures && C->isImplicit()) {
9490 getSema().finishLambdaExplicitCaptures(LSI);
9491 FinishedExplicitCaptures = true;
9494 // Capturing 'this' is trivial.
9495 if (C->capturesThis()) {
9496 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
9499 // Captured expression will be recaptured during captured variables
9501 if (C->capturesVLAType())
9504 // Rebuild init-captures, including the implied field declaration.
9505 if (E->isInitCapture(C)) {
9506 InitCaptureInfoTy InitExprTypePair =
9507 InitCaptureExprsAndTypes[C - E->capture_begin()];
9508 ExprResult Init = InitExprTypePair.first;
9509 QualType InitQualType = InitExprTypePair.second;
9510 if (Init.isInvalid() || InitQualType.isNull()) {
9514 VarDecl *OldVD = C->getCapturedVar();
9515 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
9516 OldVD->getLocation(), InitExprTypePair.second,
9517 OldVD->getIdentifier(), Init.get());
9521 getDerived().transformedLocalDecl(OldVD, NewVD);
9523 getSema().buildInitCaptureField(LSI, NewVD);
9527 assert(C->capturesVariable() && "unexpected kind of lambda capture");
9529 // Determine the capture kind for Sema.
9530 Sema::TryCaptureKind Kind
9531 = C->isImplicit()? Sema::TryCapture_Implicit
9532 : C->getCaptureKind() == LCK_ByCopy
9533 ? Sema::TryCapture_ExplicitByVal
9534 : Sema::TryCapture_ExplicitByRef;
9535 SourceLocation EllipsisLoc;
9536 if (C->isPackExpansion()) {
9537 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
9538 bool ShouldExpand = false;
9539 bool RetainExpansion = false;
9540 Optional<unsigned> NumExpansions;
9541 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
9544 ShouldExpand, RetainExpansion,
9551 // The transform has determined that we should perform an expansion;
9552 // transform and capture each of the arguments.
9553 // expansion of the pattern. Do so.
9554 VarDecl *Pack = C->getCapturedVar();
9555 for (unsigned I = 0; I != *NumExpansions; ++I) {
9556 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
9557 VarDecl *CapturedVar
9558 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
9565 // Capture the transformed variable.
9566 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
9569 // FIXME: Retain a pack expansion if RetainExpansion is true.
9574 EllipsisLoc = C->getEllipsisLoc();
9577 // Transform the captured variable.
9578 VarDecl *CapturedVar
9579 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
9580 C->getCapturedVar()));
9581 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
9586 // Capture the transformed variable.
9587 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
9590 if (!FinishedExplicitCaptures)
9591 getSema().finishLambdaExplicitCaptures(LSI);
9593 // Enter a new evaluation context to insulate the lambda from any
9594 // cleanups from the enclosing full-expression.
9595 getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
9597 // Instantiate the body of the lambda expression.
9599 Invalid ? StmtError() : getDerived().TransformStmt(E->getBody());
9601 // ActOnLambda* will pop the function scope for us.
9602 FuncScopeCleanup.disable();
9604 if (Body.isInvalid()) {
9606 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
9607 /*IsInstantiation=*/true);
9611 // Copy the LSI before ActOnFinishFunctionBody removes it.
9612 // FIXME: This is dumb. Store the lambda information somewhere that outlives
9613 // the call operator.
9614 auto LSICopy = *LSI;
9615 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
9616 /*IsInstantiation*/ true);
9619 return getSema().BuildLambdaExpr(E->getLocStart(), Body.get()->getLocEnd(),
9623 template<typename Derived>
9625 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
9626 CXXUnresolvedConstructExpr *E) {
9627 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9631 bool ArgumentChanged = false;
9632 SmallVector<Expr*, 8> Args;
9633 Args.reserve(E->arg_size());
9634 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
9638 if (!getDerived().AlwaysRebuild() &&
9639 T == E->getTypeSourceInfo() &&
9643 // FIXME: we're faking the locations of the commas
9644 return getDerived().RebuildCXXUnresolvedConstructExpr(T,
9650 template<typename Derived>
9652 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
9653 CXXDependentScopeMemberExpr *E) {
9654 // Transform the base of the expression.
9655 ExprResult Base((Expr*) nullptr);
9658 QualType ObjectType;
9659 if (!E->isImplicitAccess()) {
9660 OldBase = E->getBase();
9661 Base = getDerived().TransformExpr(OldBase);
9662 if (Base.isInvalid())
9665 // Start the member reference and compute the object's type.
9666 ParsedType ObjectTy;
9667 bool MayBePseudoDestructor = false;
9668 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
9669 E->getOperatorLoc(),
9670 E->isArrow()? tok::arrow : tok::period,
9672 MayBePseudoDestructor);
9673 if (Base.isInvalid())
9676 ObjectType = ObjectTy.get();
9677 BaseType = ((Expr*) Base.get())->getType();
9680 BaseType = getDerived().TransformType(E->getBaseType());
9681 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
9684 // Transform the first part of the nested-name-specifier that qualifies
9686 NamedDecl *FirstQualifierInScope
9687 = getDerived().TransformFirstQualifierInScope(
9688 E->getFirstQualifierFoundInScope(),
9689 E->getQualifierLoc().getBeginLoc());
9691 NestedNameSpecifierLoc QualifierLoc;
9692 if (E->getQualifier()) {
9694 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
9696 FirstQualifierInScope);
9701 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9703 // TODO: If this is a conversion-function-id, verify that the
9704 // destination type name (if present) resolves the same way after
9705 // instantiation as it did in the local scope.
9707 DeclarationNameInfo NameInfo
9708 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
9709 if (!NameInfo.getName())
9712 if (!E->hasExplicitTemplateArgs()) {
9713 // This is a reference to a member without an explicitly-specified
9714 // template argument list. Optimize for this common case.
9715 if (!getDerived().AlwaysRebuild() &&
9716 Base.get() == OldBase &&
9717 BaseType == E->getBaseType() &&
9718 QualifierLoc == E->getQualifierLoc() &&
9719 NameInfo.getName() == E->getMember() &&
9720 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
9723 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
9726 E->getOperatorLoc(),
9729 FirstQualifierInScope,
9731 /*TemplateArgs*/nullptr);
9734 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
9735 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9736 E->getNumTemplateArgs(),
9740 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
9743 E->getOperatorLoc(),
9746 FirstQualifierInScope,
9751 template<typename Derived>
9753 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
9754 // Transform the base of the expression.
9755 ExprResult Base((Expr*) nullptr);
9757 if (!Old->isImplicitAccess()) {
9758 Base = getDerived().TransformExpr(Old->getBase());
9759 if (Base.isInvalid())
9761 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
9763 if (Base.isInvalid())
9765 BaseType = Base.get()->getType();
9767 BaseType = getDerived().TransformType(Old->getBaseType());
9770 NestedNameSpecifierLoc QualifierLoc;
9771 if (Old->getQualifierLoc()) {
9773 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
9778 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
9780 LookupResult R(SemaRef, Old->getMemberNameInfo(),
9781 Sema::LookupOrdinaryName);
9783 // Transform all the decls.
9784 for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
9785 E = Old->decls_end(); I != E; ++I) {
9786 NamedDecl *InstD = static_cast<NamedDecl*>(
9787 getDerived().TransformDecl(Old->getMemberLoc(),
9790 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
9791 // This can happen because of dependent hiding.
9792 if (isa<UsingShadowDecl>(*I))
9800 // Expand using declarations.
9801 if (isa<UsingDecl>(InstD)) {
9802 UsingDecl *UD = cast<UsingDecl>(InstD);
9803 for (auto *I : UD->shadows())
9813 // Determine the naming class.
9814 if (Old->getNamingClass()) {
9815 CXXRecordDecl *NamingClass
9816 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
9817 Old->getMemberLoc(),
9818 Old->getNamingClass()));
9822 R.setNamingClass(NamingClass);
9825 TemplateArgumentListInfo TransArgs;
9826 if (Old->hasExplicitTemplateArgs()) {
9827 TransArgs.setLAngleLoc(Old->getLAngleLoc());
9828 TransArgs.setRAngleLoc(Old->getRAngleLoc());
9829 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
9830 Old->getNumTemplateArgs(),
9835 // FIXME: to do this check properly, we will need to preserve the
9836 // first-qualifier-in-scope here, just in case we had a dependent
9837 // base (and therefore couldn't do the check) and a
9838 // nested-name-qualifier (and therefore could do the lookup).
9839 NamedDecl *FirstQualifierInScope = nullptr;
9841 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
9843 Old->getOperatorLoc(),
9847 FirstQualifierInScope,
9849 (Old->hasExplicitTemplateArgs()
9850 ? &TransArgs : nullptr));
9853 template<typename Derived>
9855 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
9856 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
9857 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
9858 if (SubExpr.isInvalid())
9861 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
9864 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
9867 template<typename Derived>
9869 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
9870 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
9871 if (Pattern.isInvalid())
9874 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
9877 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
9878 E->getNumExpansions());
9881 template<typename Derived>
9883 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
9884 // If E is not value-dependent, then nothing will change when we transform it.
9885 // Note: This is an instantiation-centric view.
9886 if (!E->isValueDependent())
9889 // Note: None of the implementations of TryExpandParameterPacks can ever
9890 // produce a diagnostic when given only a single unexpanded parameter pack,
9892 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
9893 bool ShouldExpand = false;
9894 bool RetainExpansion = false;
9895 Optional<unsigned> NumExpansions;
9896 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
9898 ShouldExpand, RetainExpansion,
9902 if (RetainExpansion)
9905 NamedDecl *Pack = E->getPack();
9906 if (!ShouldExpand) {
9907 Pack = cast_or_null<NamedDecl>(getDerived().TransformDecl(E->getPackLoc(),
9914 // We now know the length of the parameter pack, so build a new expression
9915 // that stores that length.
9916 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
9917 E->getPackLoc(), E->getRParenLoc(),
9921 template<typename Derived>
9923 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
9924 SubstNonTypeTemplateParmPackExpr *E) {
9925 // Default behavior is to do nothing with this transformation.
9929 template<typename Derived>
9931 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
9932 SubstNonTypeTemplateParmExpr *E) {
9933 // Default behavior is to do nothing with this transformation.
9937 template<typename Derived>
9939 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
9940 // Default behavior is to do nothing with this transformation.
9944 template<typename Derived>
9946 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
9947 MaterializeTemporaryExpr *E) {
9948 return getDerived().TransformExpr(E->GetTemporaryExpr());
9951 template<typename Derived>
9953 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
9954 Expr *Pattern = E->getPattern();
9956 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
9957 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
9958 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
9960 // Determine whether the set of unexpanded parameter packs can and should
9963 bool RetainExpansion = false;
9964 Optional<unsigned> NumExpansions;
9965 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
9966 Pattern->getSourceRange(),
9968 Expand, RetainExpansion,
9973 // Do not expand any packs here, just transform and rebuild a fold
9975 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
9978 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
9979 if (LHS.isInvalid())
9983 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
9984 if (RHS.isInvalid())
9987 if (!getDerived().AlwaysRebuild() &&
9988 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
9991 return getDerived().RebuildCXXFoldExpr(
9992 E->getLocStart(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
9993 RHS.get(), E->getLocEnd());
9996 // The transform has determined that we should perform an elementwise
9997 // expansion of the pattern. Do so.
9998 ExprResult Result = getDerived().TransformExpr(E->getInit());
9999 if (Result.isInvalid())
10001 bool LeftFold = E->isLeftFold();
10003 // If we're retaining an expansion for a right fold, it is the innermost
10004 // component and takes the init (if any).
10005 if (!LeftFold && RetainExpansion) {
10006 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
10008 ExprResult Out = getDerived().TransformExpr(Pattern);
10009 if (Out.isInvalid())
10012 Result = getDerived().RebuildCXXFoldExpr(
10013 E->getLocStart(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
10014 Result.get(), E->getLocEnd());
10015 if (Result.isInvalid())
10019 for (unsigned I = 0; I != *NumExpansions; ++I) {
10020 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
10021 getSema(), LeftFold ? I : *NumExpansions - I - 1);
10022 ExprResult Out = getDerived().TransformExpr(Pattern);
10023 if (Out.isInvalid())
10026 if (Out.get()->containsUnexpandedParameterPack()) {
10027 // We still have a pack; retain a pack expansion for this slice.
10028 Result = getDerived().RebuildCXXFoldExpr(
10030 LeftFold ? Result.get() : Out.get(),
10031 E->getOperator(), E->getEllipsisLoc(),
10032 LeftFold ? Out.get() : Result.get(),
10034 } else if (Result.isUsable()) {
10035 // We've got down to a single element; build a binary operator.
10036 Result = getDerived().RebuildBinaryOperator(
10037 E->getEllipsisLoc(), E->getOperator(),
10038 LeftFold ? Result.get() : Out.get(),
10039 LeftFold ? Out.get() : Result.get());
10043 if (Result.isInvalid())
10047 // If we're retaining an expansion for a left fold, it is the outermost
10048 // component and takes the complete expansion so far as its init (if any).
10049 if (LeftFold && RetainExpansion) {
10050 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
10052 ExprResult Out = getDerived().TransformExpr(Pattern);
10053 if (Out.isInvalid())
10056 Result = getDerived().RebuildCXXFoldExpr(
10057 E->getLocStart(), Result.get(),
10058 E->getOperator(), E->getEllipsisLoc(),
10059 Out.get(), E->getLocEnd());
10060 if (Result.isInvalid())
10064 // If we had no init and an empty pack, and we're not retaining an expansion,
10065 // then produce a fallback value or error.
10066 if (Result.isUnset())
10067 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
10073 template<typename Derived>
10075 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
10076 CXXStdInitializerListExpr *E) {
10077 return getDerived().TransformExpr(E->getSubExpr());
10080 template<typename Derived>
10082 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
10083 return SemaRef.MaybeBindToTemporary(E);
10086 template<typename Derived>
10088 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
10092 template<typename Derived>
10094 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
10095 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10096 if (SubExpr.isInvalid())
10097 return ExprError();
10099 if (!getDerived().AlwaysRebuild() &&
10100 SubExpr.get() == E->getSubExpr())
10103 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
10106 template<typename Derived>
10108 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
10109 // Transform each of the elements.
10110 SmallVector<Expr *, 8> Elements;
10111 bool ArgChanged = false;
10112 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
10113 /*IsCall=*/false, Elements, &ArgChanged))
10114 return ExprError();
10116 if (!getDerived().AlwaysRebuild() && !ArgChanged)
10117 return SemaRef.MaybeBindToTemporary(E);
10119 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
10124 template<typename Derived>
10126 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
10127 ObjCDictionaryLiteral *E) {
10128 // Transform each of the elements.
10129 SmallVector<ObjCDictionaryElement, 8> Elements;
10130 bool ArgChanged = false;
10131 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
10132 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
10134 if (OrigElement.isPackExpansion()) {
10135 // This key/value element is a pack expansion.
10136 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10137 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
10138 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
10139 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
10141 // Determine whether the set of unexpanded parameter packs can
10142 // and should be expanded.
10143 bool Expand = true;
10144 bool RetainExpansion = false;
10145 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
10146 Optional<unsigned> NumExpansions = OrigNumExpansions;
10147 SourceRange PatternRange(OrigElement.Key->getLocStart(),
10148 OrigElement.Value->getLocEnd());
10149 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
10152 Expand, RetainExpansion,
10154 return ExprError();
10157 // The transform has determined that we should perform a simple
10158 // transformation on the pack expansion, producing another pack
10160 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
10161 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
10162 if (Key.isInvalid())
10163 return ExprError();
10165 if (Key.get() != OrigElement.Key)
10168 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
10169 if (Value.isInvalid())
10170 return ExprError();
10172 if (Value.get() != OrigElement.Value)
10175 ObjCDictionaryElement Expansion = {
10176 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
10178 Elements.push_back(Expansion);
10182 // Record right away that the argument was changed. This needs
10183 // to happen even if the array expands to nothing.
10186 // The transform has determined that we should perform an elementwise
10187 // expansion of the pattern. Do so.
10188 for (unsigned I = 0; I != *NumExpansions; ++I) {
10189 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
10190 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
10191 if (Key.isInvalid())
10192 return ExprError();
10194 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
10195 if (Value.isInvalid())
10196 return ExprError();
10198 ObjCDictionaryElement Element = {
10199 Key.get(), Value.get(), SourceLocation(), NumExpansions
10202 // If any unexpanded parameter packs remain, we still have a
10204 // FIXME: Can this really happen?
10205 if (Key.get()->containsUnexpandedParameterPack() ||
10206 Value.get()->containsUnexpandedParameterPack())
10207 Element.EllipsisLoc = OrigElement.EllipsisLoc;
10209 Elements.push_back(Element);
10212 // FIXME: Retain a pack expansion if RetainExpansion is true.
10214 // We've finished with this pack expansion.
10218 // Transform and check key.
10219 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
10220 if (Key.isInvalid())
10221 return ExprError();
10223 if (Key.get() != OrigElement.Key)
10226 // Transform and check value.
10228 = getDerived().TransformExpr(OrigElement.Value);
10229 if (Value.isInvalid())
10230 return ExprError();
10232 if (Value.get() != OrigElement.Value)
10235 ObjCDictionaryElement Element = {
10236 Key.get(), Value.get(), SourceLocation(), None
10238 Elements.push_back(Element);
10241 if (!getDerived().AlwaysRebuild() && !ArgChanged)
10242 return SemaRef.MaybeBindToTemporary(E);
10244 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
10249 template<typename Derived>
10251 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
10252 TypeSourceInfo *EncodedTypeInfo
10253 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
10254 if (!EncodedTypeInfo)
10255 return ExprError();
10257 if (!getDerived().AlwaysRebuild() &&
10258 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
10261 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
10263 E->getRParenLoc());
10266 template<typename Derived>
10267 ExprResult TreeTransform<Derived>::
10268 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
10269 // This is a kind of implicit conversion, and it needs to get dropped
10270 // and recomputed for the same general reasons that ImplicitCastExprs
10271 // do, as well a more specific one: this expression is only valid when
10272 // it appears *immediately* as an argument expression.
10273 return getDerived().TransformExpr(E->getSubExpr());
10276 template<typename Derived>
10277 ExprResult TreeTransform<Derived>::
10278 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
10279 TypeSourceInfo *TSInfo
10280 = getDerived().TransformType(E->getTypeInfoAsWritten());
10282 return ExprError();
10284 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
10285 if (Result.isInvalid())
10286 return ExprError();
10288 if (!getDerived().AlwaysRebuild() &&
10289 TSInfo == E->getTypeInfoAsWritten() &&
10290 Result.get() == E->getSubExpr())
10293 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
10294 E->getBridgeKeywordLoc(), TSInfo,
10298 template<typename Derived>
10300 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
10301 // Transform arguments.
10302 bool ArgChanged = false;
10303 SmallVector<Expr*, 8> Args;
10304 Args.reserve(E->getNumArgs());
10305 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
10307 return ExprError();
10309 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
10310 // Class message: transform the receiver type.
10311 TypeSourceInfo *ReceiverTypeInfo
10312 = getDerived().TransformType(E->getClassReceiverTypeInfo());
10313 if (!ReceiverTypeInfo)
10314 return ExprError();
10316 // If nothing changed, just retain the existing message send.
10317 if (!getDerived().AlwaysRebuild() &&
10318 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
10319 return SemaRef.MaybeBindToTemporary(E);
10321 // Build a new class message send.
10322 SmallVector<SourceLocation, 16> SelLocs;
10323 E->getSelectorLocs(SelLocs);
10324 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
10327 E->getMethodDecl(),
10332 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
10333 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10334 // Build a new class message send to 'super'.
10335 SmallVector<SourceLocation, 16> SelLocs;
10336 E->getSelectorLocs(SelLocs);
10337 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
10340 E->getMethodDecl(),
10346 // Instance message: transform the receiver
10347 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
10348 "Only class and instance messages may be instantiated");
10349 ExprResult Receiver
10350 = getDerived().TransformExpr(E->getInstanceReceiver());
10351 if (Receiver.isInvalid())
10352 return ExprError();
10354 // If nothing changed, just retain the existing message send.
10355 if (!getDerived().AlwaysRebuild() &&
10356 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
10357 return SemaRef.MaybeBindToTemporary(E);
10359 // Build a new instance message send.
10360 SmallVector<SourceLocation, 16> SelLocs;
10361 E->getSelectorLocs(SelLocs);
10362 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
10365 E->getMethodDecl(),
10371 template<typename Derived>
10373 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
10377 template<typename Derived>
10379 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
10383 template<typename Derived>
10385 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
10386 // Transform the base expression.
10387 ExprResult Base = getDerived().TransformExpr(E->getBase());
10388 if (Base.isInvalid())
10389 return ExprError();
10391 // We don't need to transform the ivar; it will never change.
10393 // If nothing changed, just retain the existing expression.
10394 if (!getDerived().AlwaysRebuild() &&
10395 Base.get() == E->getBase())
10398 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
10400 E->isArrow(), E->isFreeIvar());
10403 template<typename Derived>
10405 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
10406 // 'super' and types never change. Property never changes. Just
10407 // retain the existing expression.
10408 if (!E->isObjectReceiver())
10411 // Transform the base expression.
10412 ExprResult Base = getDerived().TransformExpr(E->getBase());
10413 if (Base.isInvalid())
10414 return ExprError();
10416 // We don't need to transform the property; it will never change.
10418 // If nothing changed, just retain the existing expression.
10419 if (!getDerived().AlwaysRebuild() &&
10420 Base.get() == E->getBase())
10423 if (E->isExplicitProperty())
10424 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10425 E->getExplicitProperty(),
10428 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10429 SemaRef.Context.PseudoObjectTy,
10430 E->getImplicitPropertyGetter(),
10431 E->getImplicitPropertySetter(),
10435 template<typename Derived>
10437 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
10438 // Transform the base expression.
10439 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
10440 if (Base.isInvalid())
10441 return ExprError();
10443 // Transform the key expression.
10444 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
10445 if (Key.isInvalid())
10446 return ExprError();
10448 // If nothing changed, just retain the existing expression.
10449 if (!getDerived().AlwaysRebuild() &&
10450 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
10453 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
10454 Base.get(), Key.get(),
10455 E->getAtIndexMethodDecl(),
10456 E->setAtIndexMethodDecl());
10459 template<typename Derived>
10461 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
10462 // Transform the base expression.
10463 ExprResult Base = getDerived().TransformExpr(E->getBase());
10464 if (Base.isInvalid())
10465 return ExprError();
10467 // If nothing changed, just retain the existing expression.
10468 if (!getDerived().AlwaysRebuild() &&
10469 Base.get() == E->getBase())
10472 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
10477 template<typename Derived>
10479 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
10480 bool ArgumentChanged = false;
10481 SmallVector<Expr*, 8> SubExprs;
10482 SubExprs.reserve(E->getNumSubExprs());
10483 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10484 SubExprs, &ArgumentChanged))
10485 return ExprError();
10487 if (!getDerived().AlwaysRebuild() &&
10491 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
10493 E->getRParenLoc());
10496 template<typename Derived>
10498 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
10499 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
10500 if (SrcExpr.isInvalid())
10501 return ExprError();
10503 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10505 return ExprError();
10507 if (!getDerived().AlwaysRebuild() &&
10508 Type == E->getTypeSourceInfo() &&
10509 SrcExpr.get() == E->getSrcExpr())
10512 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
10513 SrcExpr.get(), Type,
10514 E->getRParenLoc());
10517 template<typename Derived>
10519 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
10520 BlockDecl *oldBlock = E->getBlockDecl();
10522 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
10523 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
10525 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
10526 blockScope->TheDecl->setBlockMissingReturnType(
10527 oldBlock->blockMissingReturnType());
10529 SmallVector<ParmVarDecl*, 4> params;
10530 SmallVector<QualType, 4> paramTypes;
10532 // Parameter substitution.
10533 if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
10534 oldBlock->param_begin(),
10535 oldBlock->param_size(),
10536 nullptr, paramTypes, ¶ms)) {
10537 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10538 return ExprError();
10541 const FunctionProtoType *exprFunctionType = E->getFunctionType();
10542 QualType exprResultType =
10543 getDerived().TransformType(exprFunctionType->getReturnType());
10545 QualType functionType =
10546 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes,
10547 exprFunctionType->getExtProtoInfo());
10548 blockScope->FunctionType = functionType;
10550 // Set the parameters on the block decl.
10551 if (!params.empty())
10552 blockScope->TheDecl->setParams(params);
10554 if (!oldBlock->blockMissingReturnType()) {
10555 blockScope->HasImplicitReturnType = false;
10556 blockScope->ReturnType = exprResultType;
10559 // Transform the body
10560 StmtResult body = getDerived().TransformStmt(E->getBody());
10561 if (body.isInvalid()) {
10562 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10563 return ExprError();
10567 // In builds with assertions, make sure that we captured everything we
10568 // captured before.
10569 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
10570 for (const auto &I : oldBlock->captures()) {
10571 VarDecl *oldCapture = I.getVariable();
10573 // Ignore parameter packs.
10574 if (isa<ParmVarDecl>(oldCapture) &&
10575 cast<ParmVarDecl>(oldCapture)->isParameterPack())
10578 VarDecl *newCapture =
10579 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
10581 assert(blockScope->CaptureMap.count(newCapture));
10583 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
10587 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
10588 /*Scope=*/nullptr);
10591 template<typename Derived>
10593 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
10594 llvm_unreachable("Cannot transform asType expressions yet");
10597 template<typename Derived>
10599 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
10600 QualType RetTy = getDerived().TransformType(E->getType());
10601 bool ArgumentChanged = false;
10602 SmallVector<Expr*, 8> SubExprs;
10603 SubExprs.reserve(E->getNumSubExprs());
10604 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10605 SubExprs, &ArgumentChanged))
10606 return ExprError();
10608 if (!getDerived().AlwaysRebuild() &&
10612 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
10613 RetTy, E->getOp(), E->getRParenLoc());
10616 //===----------------------------------------------------------------------===//
10617 // Type reconstruction
10618 //===----------------------------------------------------------------------===//
10620 template<typename Derived>
10621 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
10622 SourceLocation Star) {
10623 return SemaRef.BuildPointerType(PointeeType, Star,
10624 getDerived().getBaseEntity());
10627 template<typename Derived>
10628 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
10629 SourceLocation Star) {
10630 return SemaRef.BuildBlockPointerType(PointeeType, Star,
10631 getDerived().getBaseEntity());
10634 template<typename Derived>
10636 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
10637 bool WrittenAsLValue,
10638 SourceLocation Sigil) {
10639 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
10640 Sigil, getDerived().getBaseEntity());
10643 template<typename Derived>
10645 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
10646 QualType ClassType,
10647 SourceLocation Sigil) {
10648 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
10649 getDerived().getBaseEntity());
10652 template<typename Derived>
10653 QualType TreeTransform<Derived>::RebuildObjCObjectType(
10655 SourceLocation Loc,
10656 SourceLocation TypeArgsLAngleLoc,
10657 ArrayRef<TypeSourceInfo *> TypeArgs,
10658 SourceLocation TypeArgsRAngleLoc,
10659 SourceLocation ProtocolLAngleLoc,
10660 ArrayRef<ObjCProtocolDecl *> Protocols,
10661 ArrayRef<SourceLocation> ProtocolLocs,
10662 SourceLocation ProtocolRAngleLoc) {
10663 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
10664 TypeArgs, TypeArgsRAngleLoc,
10665 ProtocolLAngleLoc, Protocols, ProtocolLocs,
10667 /*FailOnError=*/true);
10670 template<typename Derived>
10671 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
10672 QualType PointeeType,
10673 SourceLocation Star) {
10674 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
10677 template<typename Derived>
10679 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
10680 ArrayType::ArraySizeModifier SizeMod,
10681 const llvm::APInt *Size,
10683 unsigned IndexTypeQuals,
10684 SourceRange BracketsRange) {
10685 if (SizeExpr || !Size)
10686 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
10687 IndexTypeQuals, BracketsRange,
10688 getDerived().getBaseEntity());
10690 QualType Types[] = {
10691 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
10692 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
10693 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
10695 const unsigned NumTypes = llvm::array_lengthof(Types);
10697 for (unsigned I = 0; I != NumTypes; ++I)
10698 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
10699 SizeType = Types[I];
10703 // Note that we can return a VariableArrayType here in the case where
10704 // the element type was a dependent VariableArrayType.
10705 IntegerLiteral *ArraySize
10706 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
10707 /*FIXME*/BracketsRange.getBegin());
10708 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
10709 IndexTypeQuals, BracketsRange,
10710 getDerived().getBaseEntity());
10713 template<typename Derived>
10715 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
10716 ArrayType::ArraySizeModifier SizeMod,
10717 const llvm::APInt &Size,
10718 unsigned IndexTypeQuals,
10719 SourceRange BracketsRange) {
10720 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
10721 IndexTypeQuals, BracketsRange);
10724 template<typename Derived>
10726 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
10727 ArrayType::ArraySizeModifier SizeMod,
10728 unsigned IndexTypeQuals,
10729 SourceRange BracketsRange) {
10730 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
10731 IndexTypeQuals, BracketsRange);
10734 template<typename Derived>
10736 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
10737 ArrayType::ArraySizeModifier SizeMod,
10739 unsigned IndexTypeQuals,
10740 SourceRange BracketsRange) {
10741 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10743 IndexTypeQuals, BracketsRange);
10746 template<typename Derived>
10748 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
10749 ArrayType::ArraySizeModifier SizeMod,
10751 unsigned IndexTypeQuals,
10752 SourceRange BracketsRange) {
10753 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10755 IndexTypeQuals, BracketsRange);
10758 template<typename Derived>
10759 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
10760 unsigned NumElements,
10761 VectorType::VectorKind VecKind) {
10762 // FIXME: semantic checking!
10763 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
10766 template<typename Derived>
10767 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
10768 unsigned NumElements,
10769 SourceLocation AttributeLoc) {
10770 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
10771 NumElements, true);
10772 IntegerLiteral *VectorSize
10773 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
10775 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
10778 template<typename Derived>
10780 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
10782 SourceLocation AttributeLoc) {
10783 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
10786 template<typename Derived>
10787 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
10789 MutableArrayRef<QualType> ParamTypes,
10790 const FunctionProtoType::ExtProtoInfo &EPI) {
10791 return SemaRef.BuildFunctionType(T, ParamTypes,
10792 getDerived().getBaseLocation(),
10793 getDerived().getBaseEntity(),
10797 template<typename Derived>
10798 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
10799 return SemaRef.Context.getFunctionNoProtoType(T);
10802 template<typename Derived>
10803 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
10804 assert(D && "no decl found");
10805 if (D->isInvalidDecl()) return QualType();
10807 // FIXME: Doesn't account for ObjCInterfaceDecl!
10809 if (isa<UsingDecl>(D)) {
10810 UsingDecl *Using = cast<UsingDecl>(D);
10811 assert(Using->hasTypename() &&
10812 "UnresolvedUsingTypenameDecl transformed to non-typename using");
10814 // A valid resolved using typename decl points to exactly one type decl.
10815 assert(++Using->shadow_begin() == Using->shadow_end());
10816 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
10819 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
10820 "UnresolvedUsingTypenameDecl transformed to non-using decl");
10821 Ty = cast<UnresolvedUsingTypenameDecl>(D);
10824 return SemaRef.Context.getTypeDeclType(Ty);
10827 template<typename Derived>
10828 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
10829 SourceLocation Loc) {
10830 return SemaRef.BuildTypeofExprType(E, Loc);
10833 template<typename Derived>
10834 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
10835 return SemaRef.Context.getTypeOfType(Underlying);
10838 template<typename Derived>
10839 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
10840 SourceLocation Loc) {
10841 return SemaRef.BuildDecltypeType(E, Loc);
10844 template<typename Derived>
10845 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
10846 UnaryTransformType::UTTKind UKind,
10847 SourceLocation Loc) {
10848 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
10851 template<typename Derived>
10852 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
10853 TemplateName Template,
10854 SourceLocation TemplateNameLoc,
10855 TemplateArgumentListInfo &TemplateArgs) {
10856 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
10859 template<typename Derived>
10860 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
10861 SourceLocation KWLoc) {
10862 return SemaRef.BuildAtomicType(ValueType, KWLoc);
10865 template<typename Derived>
10867 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10869 TemplateDecl *Template) {
10870 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
10874 template<typename Derived>
10876 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10877 const IdentifierInfo &Name,
10878 SourceLocation NameLoc,
10879 QualType ObjectType,
10880 NamedDecl *FirstQualifierInScope) {
10881 UnqualifiedId TemplateName;
10882 TemplateName.setIdentifier(&Name, NameLoc);
10883 Sema::TemplateTy Template;
10884 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10885 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10886 SS, TemplateKWLoc, TemplateName,
10887 ParsedType::make(ObjectType),
10888 /*EnteringContext=*/false,
10890 return Template.get();
10893 template<typename Derived>
10895 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10896 OverloadedOperatorKind Operator,
10897 SourceLocation NameLoc,
10898 QualType ObjectType) {
10899 UnqualifiedId Name;
10900 // FIXME: Bogus location information.
10901 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
10902 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
10903 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10904 Sema::TemplateTy Template;
10905 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10906 SS, TemplateKWLoc, Name,
10907 ParsedType::make(ObjectType),
10908 /*EnteringContext=*/false,
10910 return Template.get();
10913 template<typename Derived>
10915 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
10916 SourceLocation OpLoc,
10920 Expr *Callee = OrigCallee->IgnoreParenCasts();
10921 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
10923 if (First->getObjectKind() == OK_ObjCProperty) {
10924 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10925 if (BinaryOperator::isAssignmentOp(Opc))
10926 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
10928 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
10929 if (Result.isInvalid())
10930 return ExprError();
10931 First = Result.get();
10934 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
10935 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
10936 if (Result.isInvalid())
10937 return ExprError();
10938 Second = Result.get();
10941 // Determine whether this should be a builtin operation.
10942 if (Op == OO_Subscript) {
10943 if (!First->getType()->isOverloadableType() &&
10944 !Second->getType()->isOverloadableType())
10945 return getSema().CreateBuiltinArraySubscriptExpr(First,
10946 Callee->getLocStart(),
10948 } else if (Op == OO_Arrow) {
10949 // -> is never a builtin operation.
10950 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
10951 } else if (Second == nullptr || isPostIncDec) {
10952 if (!First->getType()->isOverloadableType()) {
10953 // The argument is not of overloadable type, so try to create a
10954 // built-in unary operation.
10955 UnaryOperatorKind Opc
10956 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10958 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
10961 if (!First->getType()->isOverloadableType() &&
10962 !Second->getType()->isOverloadableType()) {
10963 // Neither of the arguments is an overloadable type, so try to
10964 // create a built-in binary operation.
10965 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10967 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
10968 if (Result.isInvalid())
10969 return ExprError();
10975 // Compute the transformed set of functions (and function templates) to be
10976 // used during overload resolution.
10977 UnresolvedSet<16> Functions;
10979 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
10980 assert(ULE->requiresADL());
10981 Functions.append(ULE->decls_begin(), ULE->decls_end());
10983 // If we've resolved this to a particular non-member function, just call
10984 // that function. If we resolved it to a member function,
10985 // CreateOverloaded* will find that function for us.
10986 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
10987 if (!isa<CXXMethodDecl>(ND))
10988 Functions.addDecl(ND);
10991 // Add any functions found via argument-dependent lookup.
10992 Expr *Args[2] = { First, Second };
10993 unsigned NumArgs = 1 + (Second != nullptr);
10995 // Create the overloaded operator invocation for unary operators.
10996 if (NumArgs == 1 || isPostIncDec) {
10997 UnaryOperatorKind Opc
10998 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10999 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
11002 if (Op == OO_Subscript) {
11003 SourceLocation LBrace;
11004 SourceLocation RBrace;
11006 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
11007 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
11008 LBrace = SourceLocation::getFromRawEncoding(
11009 NameLoc.CXXOperatorName.BeginOpNameLoc);
11010 RBrace = SourceLocation::getFromRawEncoding(
11011 NameLoc.CXXOperatorName.EndOpNameLoc);
11013 LBrace = Callee->getLocStart();
11017 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
11021 // Create the overloaded operator invocation for binary operators.
11022 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
11024 = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
11025 if (Result.isInvalid())
11026 return ExprError();
11031 template<typename Derived>
11033 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
11034 SourceLocation OperatorLoc,
11037 TypeSourceInfo *ScopeType,
11038 SourceLocation CCLoc,
11039 SourceLocation TildeLoc,
11040 PseudoDestructorTypeStorage Destroyed) {
11041 QualType BaseType = Base->getType();
11042 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
11043 (!isArrow && !BaseType->getAs<RecordType>()) ||
11044 (isArrow && BaseType->getAs<PointerType>() &&
11045 !BaseType->getAs<PointerType>()->getPointeeType()
11046 ->template getAs<RecordType>())){
11047 // This pseudo-destructor expression is still a pseudo-destructor.
11048 return SemaRef.BuildPseudoDestructorExpr(
11049 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
11050 CCLoc, TildeLoc, Destroyed);
11053 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
11054 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
11055 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
11056 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
11057 NameInfo.setNamedTypeInfo(DestroyedType);
11059 // The scope type is now known to be a valid nested name specifier
11060 // component. Tack it on to the end of the nested name specifier.
11062 if (!ScopeType->getType()->getAs<TagType>()) {
11063 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
11064 diag::err_expected_class_or_namespace)
11065 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
11066 return ExprError();
11068 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
11072 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
11073 return getSema().BuildMemberReferenceExpr(Base, BaseType,
11074 OperatorLoc, isArrow,
11076 /*FIXME: FirstQualifier*/ nullptr,
11078 /*TemplateArgs*/ nullptr);
11081 template<typename Derived>
11083 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
11084 SourceLocation Loc = S->getLocStart();
11085 CapturedDecl *CD = S->getCapturedDecl();
11086 unsigned NumParams = CD->getNumParams();
11087 unsigned ContextParamPos = CD->getContextParamPosition();
11088 SmallVector<Sema::CapturedParamNameType, 4> Params;
11089 for (unsigned I = 0; I < NumParams; ++I) {
11090 if (I != ContextParamPos) {
11093 CD->getParam(I)->getName(),
11094 getDerived().TransformType(CD->getParam(I)->getType())));
11096 Params.push_back(std::make_pair(StringRef(), QualType()));
11099 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
11100 S->getCapturedRegionKind(), Params);
11103 Sema::CompoundScopeRAII CompoundScope(getSema());
11104 Body = getDerived().TransformStmt(S->getCapturedStmt());
11107 if (Body.isInvalid()) {
11108 getSema().ActOnCapturedRegionError();
11109 return StmtError();
11112 return getSema().ActOnCapturedRegionEnd(Body.get());
11115 } // end namespace clang