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 a new array type given the element type, size
689 /// modifier, size of the array (if known), size expression, and index type
692 /// By default, performs semantic analysis when building the array type.
693 /// Subclasses may override this routine to provide different behavior.
694 /// Also by default, all of the other Rebuild*Array
695 QualType RebuildArrayType(QualType ElementType,
696 ArrayType::ArraySizeModifier SizeMod,
697 const llvm::APInt *Size,
699 unsigned IndexTypeQuals,
700 SourceRange BracketsRange);
702 /// \brief Build a new constant array type given the element type, size
703 /// modifier, (known) size of the array, and index type qualifiers.
705 /// By default, performs semantic analysis when building the array type.
706 /// Subclasses may override this routine to provide different behavior.
707 QualType RebuildConstantArrayType(QualType ElementType,
708 ArrayType::ArraySizeModifier SizeMod,
709 const llvm::APInt &Size,
710 unsigned IndexTypeQuals,
711 SourceRange BracketsRange);
713 /// \brief Build a new incomplete array type given the element type, size
714 /// modifier, and index type qualifiers.
716 /// By default, performs semantic analysis when building the array type.
717 /// Subclasses may override this routine to provide different behavior.
718 QualType RebuildIncompleteArrayType(QualType ElementType,
719 ArrayType::ArraySizeModifier SizeMod,
720 unsigned IndexTypeQuals,
721 SourceRange BracketsRange);
723 /// \brief Build a new variable-length array type given the element type,
724 /// size modifier, size expression, 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 RebuildVariableArrayType(QualType ElementType,
729 ArrayType::ArraySizeModifier SizeMod,
731 unsigned IndexTypeQuals,
732 SourceRange BracketsRange);
734 /// \brief Build a new dependent-sized array type given the element type,
735 /// size modifier, size expression, 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 RebuildDependentSizedArrayType(QualType ElementType,
740 ArrayType::ArraySizeModifier SizeMod,
742 unsigned IndexTypeQuals,
743 SourceRange BracketsRange);
745 /// \brief Build a new vector type given the element type and
746 /// number of elements.
748 /// By default, performs semantic analysis when building the vector type.
749 /// Subclasses may override this routine to provide different behavior.
750 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
751 VectorType::VectorKind VecKind);
753 /// \brief Build a new extended vector type given the element type and
754 /// number of elements.
756 /// By default, performs semantic analysis when building the vector type.
757 /// Subclasses may override this routine to provide different behavior.
758 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
759 SourceLocation AttributeLoc);
761 /// \brief Build a new potentially dependently-sized extended vector type
762 /// given the element type and number of elements.
764 /// By default, performs semantic analysis when building the vector type.
765 /// Subclasses may override this routine to provide different behavior.
766 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
768 SourceLocation AttributeLoc);
770 /// \brief Build a new function type.
772 /// By default, performs semantic analysis when building the function type.
773 /// Subclasses may override this routine to provide different behavior.
774 QualType RebuildFunctionProtoType(QualType T,
775 MutableArrayRef<QualType> ParamTypes,
776 const FunctionProtoType::ExtProtoInfo &EPI);
778 /// \brief Build a new unprototyped function type.
779 QualType RebuildFunctionNoProtoType(QualType ResultType);
781 /// \brief Rebuild an unresolved typename type, given the decl that
782 /// the UnresolvedUsingTypenameDecl was transformed to.
783 QualType RebuildUnresolvedUsingType(Decl *D);
785 /// \brief Build a new typedef type.
786 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
787 return SemaRef.Context.getTypeDeclType(Typedef);
790 /// \brief Build a new class/struct/union type.
791 QualType RebuildRecordType(RecordDecl *Record) {
792 return SemaRef.Context.getTypeDeclType(Record);
795 /// \brief Build a new Enum type.
796 QualType RebuildEnumType(EnumDecl *Enum) {
797 return SemaRef.Context.getTypeDeclType(Enum);
800 /// \brief Build a new typeof(expr) type.
802 /// By default, performs semantic analysis when building the typeof type.
803 /// Subclasses may override this routine to provide different behavior.
804 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
806 /// \brief Build a new typeof(type) type.
808 /// By default, builds a new TypeOfType with the given underlying type.
809 QualType RebuildTypeOfType(QualType Underlying);
811 /// \brief Build a new unary transform type.
812 QualType RebuildUnaryTransformType(QualType BaseType,
813 UnaryTransformType::UTTKind UKind,
816 /// \brief Build a new C++11 decltype type.
818 /// By default, performs semantic analysis when building the decltype type.
819 /// Subclasses may override this routine to provide different behavior.
820 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
822 /// \brief Build a new C++11 auto type.
824 /// By default, builds a new AutoType with the given deduced type.
825 QualType RebuildAutoType(QualType Deduced, bool IsDecltypeAuto) {
826 // Note, IsDependent is always false here: we implicitly convert an 'auto'
827 // which has been deduced to a dependent type into an undeduced 'auto', so
828 // that we'll retry deduction after the transformation.
829 return SemaRef.Context.getAutoType(Deduced, IsDecltypeAuto,
830 /*IsDependent*/ false);
833 /// \brief Build a new template specialization type.
835 /// By default, performs semantic analysis when building the template
836 /// specialization type. Subclasses may override this routine to provide
837 /// different behavior.
838 QualType RebuildTemplateSpecializationType(TemplateName Template,
839 SourceLocation TemplateLoc,
840 TemplateArgumentListInfo &Args);
842 /// \brief Build a new parenthesized type.
844 /// By default, builds a new ParenType type from the inner type.
845 /// Subclasses may override this routine to provide different behavior.
846 QualType RebuildParenType(QualType InnerType) {
847 return SemaRef.Context.getParenType(InnerType);
850 /// \brief Build a new qualified name type.
852 /// By default, builds a new ElaboratedType type from the keyword,
853 /// the nested-name-specifier and the named type.
854 /// Subclasses may override this routine to provide different behavior.
855 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
856 ElaboratedTypeKeyword Keyword,
857 NestedNameSpecifierLoc QualifierLoc,
859 return SemaRef.Context.getElaboratedType(Keyword,
860 QualifierLoc.getNestedNameSpecifier(),
864 /// \brief Build a new typename type that refers to a template-id.
866 /// By default, builds a new DependentNameType type from the
867 /// nested-name-specifier and the given type. Subclasses may override
868 /// this routine to provide different behavior.
869 QualType RebuildDependentTemplateSpecializationType(
870 ElaboratedTypeKeyword Keyword,
871 NestedNameSpecifierLoc QualifierLoc,
872 const IdentifierInfo *Name,
873 SourceLocation NameLoc,
874 TemplateArgumentListInfo &Args) {
875 // Rebuild the template name.
876 // TODO: avoid TemplateName abstraction
878 SS.Adopt(QualifierLoc);
879 TemplateName InstName
880 = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(),
883 if (InstName.isNull())
886 // If it's still dependent, make a dependent specialization.
887 if (InstName.getAsDependentTemplateName())
888 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
889 QualifierLoc.getNestedNameSpecifier(),
893 // Otherwise, make an elaborated type wrapping a non-dependent
896 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
897 if (T.isNull()) return QualType();
899 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
902 return SemaRef.Context.getElaboratedType(Keyword,
903 QualifierLoc.getNestedNameSpecifier(),
907 /// \brief Build a new typename type that refers to an identifier.
909 /// By default, performs semantic analysis when building the typename type
910 /// (or elaborated type). Subclasses may override this routine to provide
911 /// different behavior.
912 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
913 SourceLocation KeywordLoc,
914 NestedNameSpecifierLoc QualifierLoc,
915 const IdentifierInfo *Id,
916 SourceLocation IdLoc) {
918 SS.Adopt(QualifierLoc);
920 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
921 // If the name is still dependent, just build a new dependent name type.
922 if (!SemaRef.computeDeclContext(SS))
923 return SemaRef.Context.getDependentNameType(Keyword,
924 QualifierLoc.getNestedNameSpecifier(),
928 if (Keyword == ETK_None || Keyword == ETK_Typename)
929 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
932 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
934 // We had a dependent elaborated-type-specifier that has been transformed
935 // into a non-dependent elaborated-type-specifier. Find the tag we're
937 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
938 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
942 if (SemaRef.RequireCompleteDeclContext(SS, DC))
945 TagDecl *Tag = nullptr;
946 SemaRef.LookupQualifiedName(Result, DC);
947 switch (Result.getResultKind()) {
948 case LookupResult::NotFound:
949 case LookupResult::NotFoundInCurrentInstantiation:
952 case LookupResult::Found:
953 Tag = Result.getAsSingle<TagDecl>();
956 case LookupResult::FoundOverloaded:
957 case LookupResult::FoundUnresolvedValue:
958 llvm_unreachable("Tag lookup cannot find non-tags");
960 case LookupResult::Ambiguous:
961 // Let the LookupResult structure handle ambiguities.
966 // Check where the name exists but isn't a tag type and use that to emit
967 // better diagnostics.
968 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
969 SemaRef.LookupQualifiedName(Result, DC);
970 switch (Result.getResultKind()) {
971 case LookupResult::Found:
972 case LookupResult::FoundOverloaded:
973 case LookupResult::FoundUnresolvedValue: {
974 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
976 if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
977 else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
978 else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
979 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
980 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
984 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
985 << Kind << Id << DC << QualifierLoc.getSourceRange();
991 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
993 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
994 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
998 // Build the elaborated-type-specifier type.
999 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1000 return SemaRef.Context.getElaboratedType(Keyword,
1001 QualifierLoc.getNestedNameSpecifier(),
1005 /// \brief Build a new pack expansion type.
1007 /// By default, builds a new PackExpansionType type from the given pattern.
1008 /// Subclasses may override this routine to provide different behavior.
1009 QualType RebuildPackExpansionType(QualType Pattern,
1010 SourceRange PatternRange,
1011 SourceLocation EllipsisLoc,
1012 Optional<unsigned> NumExpansions) {
1013 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1017 /// \brief Build a new atomic type given its value type.
1019 /// By default, performs semantic analysis when building the atomic type.
1020 /// Subclasses may override this routine to provide different behavior.
1021 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1023 /// \brief Build a new template name given a nested name specifier, a flag
1024 /// indicating whether the "template" keyword was provided, and the template
1025 /// that the template name refers to.
1027 /// By default, builds the new template name directly. Subclasses may override
1028 /// this routine to provide different behavior.
1029 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1031 TemplateDecl *Template);
1033 /// \brief Build a new template name given a nested name specifier and the
1034 /// name that is referred to as a template.
1036 /// By default, performs semantic analysis to determine whether the name can
1037 /// be resolved to a specific template, then builds the appropriate kind of
1038 /// template name. Subclasses may override this routine to provide different
1040 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1041 const IdentifierInfo &Name,
1042 SourceLocation NameLoc,
1043 QualType ObjectType,
1044 NamedDecl *FirstQualifierInScope);
1046 /// \brief Build a new template name given a nested name specifier and the
1047 /// overloaded operator name that is referred to as a template.
1049 /// By default, performs semantic analysis to determine whether the name can
1050 /// be resolved to a specific template, then builds the appropriate kind of
1051 /// template name. Subclasses may override this routine to provide different
1053 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1054 OverloadedOperatorKind Operator,
1055 SourceLocation NameLoc,
1056 QualType ObjectType);
1058 /// \brief Build a new template name given a template template parameter pack
1061 /// By default, performs semantic analysis to determine whether the name can
1062 /// be resolved to a specific template, then builds the appropriate kind of
1063 /// template name. Subclasses may override this routine to provide different
1065 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1066 const TemplateArgument &ArgPack) {
1067 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1070 /// \brief Build a new compound statement.
1072 /// By default, performs semantic analysis to build the new statement.
1073 /// Subclasses may override this routine to provide different behavior.
1074 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1075 MultiStmtArg Statements,
1076 SourceLocation RBraceLoc,
1078 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1082 /// \brief Build a new case statement.
1084 /// By default, performs semantic analysis to build the new statement.
1085 /// Subclasses may override this routine to provide different behavior.
1086 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1088 SourceLocation EllipsisLoc,
1090 SourceLocation ColonLoc) {
1091 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1095 /// \brief Attach the body to a new case statement.
1097 /// By default, performs semantic analysis to build the new statement.
1098 /// Subclasses may override this routine to provide different behavior.
1099 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1100 getSema().ActOnCaseStmtBody(S, Body);
1104 /// \brief Build a new default statement.
1106 /// By default, performs semantic analysis to build the new statement.
1107 /// Subclasses may override this routine to provide different behavior.
1108 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1109 SourceLocation ColonLoc,
1111 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1112 /*CurScope=*/nullptr);
1115 /// \brief Build a new label statement.
1117 /// By default, performs semantic analysis to build the new statement.
1118 /// Subclasses may override this routine to provide different behavior.
1119 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1120 SourceLocation ColonLoc, Stmt *SubStmt) {
1121 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1124 /// \brief Build a new label statement.
1126 /// By default, performs semantic analysis to build the new statement.
1127 /// Subclasses may override this routine to provide different behavior.
1128 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1129 ArrayRef<const Attr*> Attrs,
1131 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1134 /// \brief Build a new "if" statement.
1136 /// By default, performs semantic analysis to build the new statement.
1137 /// Subclasses may override this routine to provide different behavior.
1138 StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
1139 VarDecl *CondVar, Stmt *Then,
1140 SourceLocation ElseLoc, Stmt *Else) {
1141 return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
1144 /// \brief Start building a new switch statement.
1146 /// By default, performs semantic analysis to build the new statement.
1147 /// Subclasses may override this routine to provide different behavior.
1148 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1149 Expr *Cond, VarDecl *CondVar) {
1150 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
1154 /// \brief Attach the body to the switch statement.
1156 /// By default, performs semantic analysis to build the new statement.
1157 /// Subclasses may override this routine to provide different behavior.
1158 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1159 Stmt *Switch, Stmt *Body) {
1160 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1163 /// \brief Build a new while statement.
1165 /// By default, performs semantic analysis to build the new statement.
1166 /// Subclasses may override this routine to provide different behavior.
1167 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
1168 VarDecl *CondVar, Stmt *Body) {
1169 return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
1172 /// \brief Build a new do-while statement.
1174 /// By default, performs semantic analysis to build the new statement.
1175 /// Subclasses may override this routine to provide different behavior.
1176 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1177 SourceLocation WhileLoc, SourceLocation LParenLoc,
1178 Expr *Cond, SourceLocation RParenLoc) {
1179 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1183 /// \brief Build a new for statement.
1185 /// By default, performs semantic analysis to build the new statement.
1186 /// Subclasses may override this routine to provide different behavior.
1187 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1188 Stmt *Init, Sema::FullExprArg Cond,
1189 VarDecl *CondVar, Sema::FullExprArg Inc,
1190 SourceLocation RParenLoc, Stmt *Body) {
1191 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1192 CondVar, Inc, RParenLoc, Body);
1195 /// \brief Build a new goto statement.
1197 /// By default, performs semantic analysis to build the new statement.
1198 /// Subclasses may override this routine to provide different behavior.
1199 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1201 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1204 /// \brief Build a new indirect goto statement.
1206 /// By default, performs semantic analysis to build the new statement.
1207 /// Subclasses may override this routine to provide different behavior.
1208 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1209 SourceLocation StarLoc,
1211 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1214 /// \brief Build a new return statement.
1216 /// By default, performs semantic analysis to build the new statement.
1217 /// Subclasses may override this routine to provide different behavior.
1218 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1219 return getSema().BuildReturnStmt(ReturnLoc, Result);
1222 /// \brief Build a new declaration statement.
1224 /// By default, performs semantic analysis to build the new statement.
1225 /// Subclasses may override this routine to provide different behavior.
1226 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1227 SourceLocation StartLoc, SourceLocation EndLoc) {
1228 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1229 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1232 /// \brief Build a new inline asm statement.
1234 /// By default, performs semantic analysis to build the new statement.
1235 /// Subclasses may override this routine to provide different behavior.
1236 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1237 bool IsVolatile, unsigned NumOutputs,
1238 unsigned NumInputs, IdentifierInfo **Names,
1239 MultiExprArg Constraints, MultiExprArg Exprs,
1240 Expr *AsmString, MultiExprArg Clobbers,
1241 SourceLocation RParenLoc) {
1242 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1243 NumInputs, Names, Constraints, Exprs,
1244 AsmString, Clobbers, RParenLoc);
1247 /// \brief Build a new MS style inline asm statement.
1249 /// By default, performs semantic analysis to build the new statement.
1250 /// Subclasses may override this routine to provide different behavior.
1251 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1252 ArrayRef<Token> AsmToks,
1253 StringRef AsmString,
1254 unsigned NumOutputs, unsigned NumInputs,
1255 ArrayRef<StringRef> Constraints,
1256 ArrayRef<StringRef> Clobbers,
1257 ArrayRef<Expr*> Exprs,
1258 SourceLocation EndLoc) {
1259 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1260 NumOutputs, NumInputs,
1261 Constraints, Clobbers, Exprs, EndLoc);
1264 /// \brief Build a new Objective-C \@try statement.
1266 /// By default, performs semantic analysis to build the new statement.
1267 /// Subclasses may override this routine to provide different behavior.
1268 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1270 MultiStmtArg CatchStmts,
1272 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1276 /// \brief Rebuild an Objective-C exception declaration.
1278 /// By default, performs semantic analysis to build the new declaration.
1279 /// Subclasses may override this routine to provide different behavior.
1280 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1281 TypeSourceInfo *TInfo, QualType T) {
1282 return getSema().BuildObjCExceptionDecl(TInfo, T,
1283 ExceptionDecl->getInnerLocStart(),
1284 ExceptionDecl->getLocation(),
1285 ExceptionDecl->getIdentifier());
1288 /// \brief Build a new Objective-C \@catch statement.
1290 /// By default, performs semantic analysis to build the new statement.
1291 /// Subclasses may override this routine to provide different behavior.
1292 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1293 SourceLocation RParenLoc,
1296 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1300 /// \brief Build a new Objective-C \@finally statement.
1302 /// By default, performs semantic analysis to build the new statement.
1303 /// Subclasses may override this routine to provide different behavior.
1304 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1306 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1309 /// \brief Build a new Objective-C \@throw statement.
1311 /// By default, performs semantic analysis to build the new statement.
1312 /// Subclasses may override this routine to provide different behavior.
1313 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1315 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1318 /// \brief Build a new OpenMP executable directive.
1320 /// By default, performs semantic analysis to build the new statement.
1321 /// Subclasses may override this routine to provide different behavior.
1322 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1323 DeclarationNameInfo DirName,
1324 ArrayRef<OMPClause *> Clauses,
1325 Stmt *AStmt, SourceLocation StartLoc,
1326 SourceLocation EndLoc) {
1327 return getSema().ActOnOpenMPExecutableDirective(Kind, DirName, Clauses,
1328 AStmt, StartLoc, EndLoc);
1331 /// \brief Build a new OpenMP 'if' clause.
1333 /// By default, performs semantic analysis to build the new OpenMP clause.
1334 /// Subclasses may override this routine to provide different behavior.
1335 OMPClause *RebuildOMPIfClause(Expr *Condition,
1336 SourceLocation StartLoc,
1337 SourceLocation LParenLoc,
1338 SourceLocation EndLoc) {
1339 return getSema().ActOnOpenMPIfClause(Condition, StartLoc,
1343 /// \brief Build a new OpenMP 'final' clause.
1345 /// By default, performs semantic analysis to build the new OpenMP clause.
1346 /// Subclasses may override this routine to provide different behavior.
1347 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1348 SourceLocation LParenLoc,
1349 SourceLocation EndLoc) {
1350 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1354 /// \brief Build a new OpenMP 'num_threads' clause.
1356 /// By default, performs semantic analysis to build the new OpenMP clause.
1357 /// Subclasses may override this routine to provide different behavior.
1358 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1359 SourceLocation StartLoc,
1360 SourceLocation LParenLoc,
1361 SourceLocation EndLoc) {
1362 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1366 /// \brief Build a new OpenMP 'safelen' clause.
1368 /// By default, performs semantic analysis to build the new OpenMP clause.
1369 /// Subclasses may override this routine to provide different behavior.
1370 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1371 SourceLocation LParenLoc,
1372 SourceLocation EndLoc) {
1373 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1376 /// \brief Build a new OpenMP 'collapse' 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 *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1381 SourceLocation LParenLoc,
1382 SourceLocation EndLoc) {
1383 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1387 /// \brief Build a new OpenMP 'default' clause.
1389 /// By default, performs semantic analysis to build the new OpenMP clause.
1390 /// Subclasses may override this routine to provide different behavior.
1391 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1392 SourceLocation KindKwLoc,
1393 SourceLocation StartLoc,
1394 SourceLocation LParenLoc,
1395 SourceLocation EndLoc) {
1396 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1397 StartLoc, LParenLoc, EndLoc);
1400 /// \brief Build a new OpenMP 'proc_bind' clause.
1402 /// By default, performs semantic analysis to build the new OpenMP clause.
1403 /// Subclasses may override this routine to provide different behavior.
1404 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1405 SourceLocation KindKwLoc,
1406 SourceLocation StartLoc,
1407 SourceLocation LParenLoc,
1408 SourceLocation EndLoc) {
1409 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1410 StartLoc, LParenLoc, EndLoc);
1413 /// \brief Build a new OpenMP 'schedule' clause.
1415 /// By default, performs semantic analysis to build the new OpenMP clause.
1416 /// Subclasses may override this routine to provide different behavior.
1417 OMPClause *RebuildOMPScheduleClause(OpenMPScheduleClauseKind Kind,
1419 SourceLocation StartLoc,
1420 SourceLocation LParenLoc,
1421 SourceLocation KindLoc,
1422 SourceLocation CommaLoc,
1423 SourceLocation EndLoc) {
1424 return getSema().ActOnOpenMPScheduleClause(
1425 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1428 /// \brief Build a new OpenMP 'private' clause.
1430 /// By default, performs semantic analysis to build the new OpenMP clause.
1431 /// Subclasses may override this routine to provide different behavior.
1432 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1433 SourceLocation StartLoc,
1434 SourceLocation LParenLoc,
1435 SourceLocation EndLoc) {
1436 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1440 /// \brief Build a new OpenMP 'firstprivate' clause.
1442 /// By default, performs semantic analysis to build the new OpenMP clause.
1443 /// Subclasses may override this routine to provide different behavior.
1444 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1445 SourceLocation StartLoc,
1446 SourceLocation LParenLoc,
1447 SourceLocation EndLoc) {
1448 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1452 /// \brief Build a new OpenMP 'lastprivate' clause.
1454 /// By default, performs semantic analysis to build the new OpenMP clause.
1455 /// Subclasses may override this routine to provide different behavior.
1456 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1457 SourceLocation StartLoc,
1458 SourceLocation LParenLoc,
1459 SourceLocation EndLoc) {
1460 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1464 /// \brief Build a new OpenMP 'shared' clause.
1466 /// By default, performs semantic analysis to build the new OpenMP clause.
1467 /// Subclasses may override this routine to provide different behavior.
1468 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1469 SourceLocation StartLoc,
1470 SourceLocation LParenLoc,
1471 SourceLocation EndLoc) {
1472 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1476 /// \brief Build a new OpenMP 'reduction' clause.
1478 /// By default, performs semantic analysis to build the new statement.
1479 /// Subclasses may override this routine to provide different behavior.
1480 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1481 SourceLocation StartLoc,
1482 SourceLocation LParenLoc,
1483 SourceLocation ColonLoc,
1484 SourceLocation EndLoc,
1485 CXXScopeSpec &ReductionIdScopeSpec,
1486 const DeclarationNameInfo &ReductionId) {
1487 return getSema().ActOnOpenMPReductionClause(
1488 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1492 /// \brief Build a new OpenMP 'linear' clause.
1494 /// By default, performs semantic analysis to build the new OpenMP clause.
1495 /// Subclasses may override this routine to provide different behavior.
1496 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1497 SourceLocation StartLoc,
1498 SourceLocation LParenLoc,
1499 SourceLocation ColonLoc,
1500 SourceLocation EndLoc) {
1501 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1505 /// \brief Build a new OpenMP 'aligned' clause.
1507 /// By default, performs semantic analysis to build the new OpenMP clause.
1508 /// Subclasses may override this routine to provide different behavior.
1509 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1510 SourceLocation StartLoc,
1511 SourceLocation LParenLoc,
1512 SourceLocation ColonLoc,
1513 SourceLocation EndLoc) {
1514 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1515 LParenLoc, ColonLoc, EndLoc);
1518 /// \brief Build a new OpenMP 'copyin' clause.
1520 /// By default, performs semantic analysis to build the new OpenMP clause.
1521 /// Subclasses may override this routine to provide different behavior.
1522 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1523 SourceLocation StartLoc,
1524 SourceLocation LParenLoc,
1525 SourceLocation EndLoc) {
1526 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1530 /// \brief Build a new OpenMP 'copyprivate' clause.
1532 /// By default, performs semantic analysis to build the new OpenMP clause.
1533 /// Subclasses may override this routine to provide different behavior.
1534 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1535 SourceLocation StartLoc,
1536 SourceLocation LParenLoc,
1537 SourceLocation EndLoc) {
1538 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1542 /// \brief Build a new OpenMP 'flush' pseudo clause.
1544 /// By default, performs semantic analysis to build the new OpenMP clause.
1545 /// Subclasses may override this routine to provide different behavior.
1546 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1547 SourceLocation StartLoc,
1548 SourceLocation LParenLoc,
1549 SourceLocation EndLoc) {
1550 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1554 /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
1556 /// By default, performs semantic analysis to build the new statement.
1557 /// Subclasses may override this routine to provide different behavior.
1558 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1560 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1563 /// \brief Build a new Objective-C \@synchronized statement.
1565 /// By default, performs semantic analysis to build the new statement.
1566 /// Subclasses may override this routine to provide different behavior.
1567 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1568 Expr *Object, Stmt *Body) {
1569 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1572 /// \brief Build a new Objective-C \@autoreleasepool statement.
1574 /// By default, performs semantic analysis to build the new statement.
1575 /// Subclasses may override this routine to provide different behavior.
1576 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1578 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1581 /// \brief Build a new Objective-C fast enumeration statement.
1583 /// By default, performs semantic analysis to build the new statement.
1584 /// Subclasses may override this routine to provide different behavior.
1585 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1588 SourceLocation RParenLoc,
1590 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1594 if (ForEachStmt.isInvalid())
1597 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
1600 /// \brief Build a new C++ exception declaration.
1602 /// By default, performs semantic analysis to build the new decaration.
1603 /// Subclasses may override this routine to provide different behavior.
1604 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1605 TypeSourceInfo *Declarator,
1606 SourceLocation StartLoc,
1607 SourceLocation IdLoc,
1608 IdentifierInfo *Id) {
1609 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
1610 StartLoc, IdLoc, Id);
1612 getSema().CurContext->addDecl(Var);
1616 /// \brief Build a new C++ catch statement.
1618 /// By default, performs semantic analysis to build the new statement.
1619 /// Subclasses may override this routine to provide different behavior.
1620 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
1621 VarDecl *ExceptionDecl,
1623 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
1627 /// \brief Build a new C++ try statement.
1629 /// By default, performs semantic analysis to build the new statement.
1630 /// Subclasses may override this routine to provide different behavior.
1631 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
1632 ArrayRef<Stmt *> Handlers) {
1633 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
1636 /// \brief Build a new C++0x range-based for statement.
1638 /// By default, performs semantic analysis to build the new statement.
1639 /// Subclasses may override this routine to provide different behavior.
1640 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
1641 SourceLocation ColonLoc,
1642 Stmt *Range, Stmt *BeginEnd,
1643 Expr *Cond, Expr *Inc,
1645 SourceLocation RParenLoc) {
1646 // If we've just learned that the range is actually an Objective-C
1647 // collection, treat this as an Objective-C fast enumeration loop.
1648 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
1649 if (RangeStmt->isSingleDecl()) {
1650 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
1651 if (RangeVar->isInvalidDecl())
1654 Expr *RangeExpr = RangeVar->getInit();
1655 if (!RangeExpr->isTypeDependent() &&
1656 RangeExpr->getType()->isObjCObjectPointerType())
1657 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
1663 return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEnd,
1664 Cond, Inc, LoopVar, RParenLoc,
1665 Sema::BFRK_Rebuild);
1668 /// \brief Build a new C++0x range-based for statement.
1670 /// By default, performs semantic analysis to build the new statement.
1671 /// Subclasses may override this routine to provide different behavior.
1672 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
1674 NestedNameSpecifierLoc QualifierLoc,
1675 DeclarationNameInfo NameInfo,
1677 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
1678 QualifierLoc, NameInfo, Nested);
1681 /// \brief Attach body to a C++0x range-based for statement.
1683 /// By default, performs semantic analysis to finish the new statement.
1684 /// Subclasses may override this routine to provide different behavior.
1685 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
1686 return getSema().FinishCXXForRangeStmt(ForRange, Body);
1689 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
1690 Stmt *TryBlock, Stmt *Handler) {
1691 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
1694 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
1696 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
1699 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
1700 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
1703 /// \brief Build a new predefined expression.
1705 /// By default, performs semantic analysis to build the new expression.
1706 /// Subclasses may override this routine to provide different behavior.
1707 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
1708 PredefinedExpr::IdentType IT) {
1709 return getSema().BuildPredefinedExpr(Loc, IT);
1712 /// \brief Build a new expression that references a declaration.
1714 /// By default, performs semantic analysis to build the new expression.
1715 /// Subclasses may override this routine to provide different behavior.
1716 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
1719 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
1723 /// \brief Build a new expression that references a declaration.
1725 /// By default, performs semantic analysis to build the new expression.
1726 /// Subclasses may override this routine to provide different behavior.
1727 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
1729 const DeclarationNameInfo &NameInfo,
1730 TemplateArgumentListInfo *TemplateArgs) {
1732 SS.Adopt(QualifierLoc);
1734 // FIXME: loses template args.
1736 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
1739 /// \brief Build a new expression in parentheses.
1741 /// By default, performs semantic analysis to build the new expression.
1742 /// Subclasses may override this routine to provide different behavior.
1743 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
1744 SourceLocation RParen) {
1745 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
1748 /// \brief Build a new pseudo-destructor expression.
1750 /// By default, performs semantic analysis to build the new expression.
1751 /// Subclasses may override this routine to provide different behavior.
1752 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
1753 SourceLocation OperatorLoc,
1756 TypeSourceInfo *ScopeType,
1757 SourceLocation CCLoc,
1758 SourceLocation TildeLoc,
1759 PseudoDestructorTypeStorage Destroyed);
1761 /// \brief Build a new unary operator expression.
1763 /// By default, performs semantic analysis to build the new expression.
1764 /// Subclasses may override this routine to provide different behavior.
1765 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
1766 UnaryOperatorKind Opc,
1768 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
1771 /// \brief Build a new builtin offsetof expression.
1773 /// By default, performs semantic analysis to build the new expression.
1774 /// Subclasses may override this routine to provide different behavior.
1775 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
1776 TypeSourceInfo *Type,
1777 Sema::OffsetOfComponent *Components,
1778 unsigned NumComponents,
1779 SourceLocation RParenLoc) {
1780 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
1781 NumComponents, RParenLoc);
1784 /// \brief Build a new sizeof, alignof or vec_step expression with a
1787 /// By default, performs semantic analysis to build the new expression.
1788 /// Subclasses may override this routine to provide different behavior.
1789 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
1790 SourceLocation OpLoc,
1791 UnaryExprOrTypeTrait ExprKind,
1793 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
1796 /// \brief Build a new sizeof, alignof or vec step expression with an
1797 /// expression argument.
1799 /// By default, performs semantic analysis to build the new expression.
1800 /// Subclasses may override this routine to provide different behavior.
1801 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
1802 UnaryExprOrTypeTrait ExprKind,
1805 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
1806 if (Result.isInvalid())
1812 /// \brief Build a new array subscript expression.
1814 /// By default, performs semantic analysis to build the new expression.
1815 /// Subclasses may override this routine to provide different behavior.
1816 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
1817 SourceLocation LBracketLoc,
1819 SourceLocation RBracketLoc) {
1820 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
1825 /// \brief Build a new call expression.
1827 /// By default, performs semantic analysis to build the new expression.
1828 /// Subclasses may override this routine to provide different behavior.
1829 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
1831 SourceLocation RParenLoc,
1832 Expr *ExecConfig = nullptr) {
1833 return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
1834 Args, RParenLoc, ExecConfig);
1837 /// \brief Build a new member access expression.
1839 /// By default, performs semantic analysis to build the new expression.
1840 /// Subclasses may override this routine to provide different behavior.
1841 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
1843 NestedNameSpecifierLoc QualifierLoc,
1844 SourceLocation TemplateKWLoc,
1845 const DeclarationNameInfo &MemberNameInfo,
1847 NamedDecl *FoundDecl,
1848 const TemplateArgumentListInfo *ExplicitTemplateArgs,
1849 NamedDecl *FirstQualifierInScope) {
1850 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
1852 if (!Member->getDeclName()) {
1853 // We have a reference to an unnamed field. This is always the
1854 // base of an anonymous struct/union member access, i.e. the
1855 // field is always of record type.
1856 assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
1857 assert(Member->getType()->isRecordType() &&
1858 "unnamed member not of record type?");
1861 getSema().PerformObjectMemberConversion(BaseResult.get(),
1862 QualifierLoc.getNestedNameSpecifier(),
1864 if (BaseResult.isInvalid())
1866 Base = BaseResult.get();
1867 ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
1868 MemberExpr *ME = new (getSema().Context)
1869 MemberExpr(Base, isArrow, OpLoc, Member, MemberNameInfo,
1870 cast<FieldDecl>(Member)->getType(), VK, OK_Ordinary);
1875 SS.Adopt(QualifierLoc);
1877 Base = BaseResult.get();
1878 QualType BaseType = Base->getType();
1880 // FIXME: this involves duplicating earlier analysis in a lot of
1881 // cases; we should avoid this when possible.
1882 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
1883 R.addDecl(FoundDecl);
1886 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
1888 FirstQualifierInScope,
1889 R, ExplicitTemplateArgs);
1892 /// \brief Build a new binary operator expression.
1894 /// By default, performs semantic analysis to build the new expression.
1895 /// Subclasses may override this routine to provide different behavior.
1896 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
1897 BinaryOperatorKind Opc,
1898 Expr *LHS, Expr *RHS) {
1899 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
1902 /// \brief Build a new conditional operator expression.
1904 /// By default, performs semantic analysis to build the new expression.
1905 /// Subclasses may override this routine to provide different behavior.
1906 ExprResult RebuildConditionalOperator(Expr *Cond,
1907 SourceLocation QuestionLoc,
1909 SourceLocation ColonLoc,
1911 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
1915 /// \brief Build a new C-style cast expression.
1917 /// By default, performs semantic analysis to build the new expression.
1918 /// Subclasses may override this routine to provide different behavior.
1919 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
1920 TypeSourceInfo *TInfo,
1921 SourceLocation RParenLoc,
1923 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
1927 /// \brief Build a new compound literal expression.
1929 /// By default, performs semantic analysis to build the new expression.
1930 /// Subclasses may override this routine to provide different behavior.
1931 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
1932 TypeSourceInfo *TInfo,
1933 SourceLocation RParenLoc,
1935 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
1939 /// \brief Build a new extended vector element access expression.
1941 /// By default, performs semantic analysis to build the new expression.
1942 /// Subclasses may override this routine to provide different behavior.
1943 ExprResult RebuildExtVectorElementExpr(Expr *Base,
1944 SourceLocation OpLoc,
1945 SourceLocation AccessorLoc,
1946 IdentifierInfo &Accessor) {
1949 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
1950 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
1951 OpLoc, /*IsArrow*/ false,
1952 SS, SourceLocation(),
1953 /*FirstQualifierInScope*/ nullptr,
1955 /* TemplateArgs */ nullptr);
1958 /// \brief Build a new initializer list expression.
1960 /// By default, performs semantic analysis to build the new expression.
1961 /// Subclasses may override this routine to provide different behavior.
1962 ExprResult RebuildInitList(SourceLocation LBraceLoc,
1964 SourceLocation RBraceLoc,
1965 QualType ResultTy) {
1967 = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
1968 if (Result.isInvalid() || ResultTy->isDependentType())
1971 // Patch in the result type we were given, which may have been computed
1972 // when the initial InitListExpr was built.
1973 InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
1974 ILE->setType(ResultTy);
1978 /// \brief Build a new designated initializer expression.
1980 /// By default, performs semantic analysis to build the new expression.
1981 /// Subclasses may override this routine to provide different behavior.
1982 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
1983 MultiExprArg ArrayExprs,
1984 SourceLocation EqualOrColonLoc,
1988 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
1990 if (Result.isInvalid())
1996 /// \brief Build a new value-initialized expression.
1998 /// By default, builds the implicit value initialization without performing
1999 /// any semantic analysis. Subclasses may override this routine to provide
2000 /// different behavior.
2001 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2002 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2005 /// \brief Build a new \c va_arg expression.
2007 /// By default, performs semantic analysis to build the new expression.
2008 /// Subclasses may override this routine to provide different behavior.
2009 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2010 Expr *SubExpr, TypeSourceInfo *TInfo,
2011 SourceLocation RParenLoc) {
2012 return getSema().BuildVAArgExpr(BuiltinLoc,
2017 /// \brief Build a new expression list in parentheses.
2019 /// By default, performs semantic analysis to build the new expression.
2020 /// Subclasses may override this routine to provide different behavior.
2021 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2022 MultiExprArg SubExprs,
2023 SourceLocation RParenLoc) {
2024 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2027 /// \brief Build a new address-of-label expression.
2029 /// By default, performs semantic analysis, using the name of the label
2030 /// rather than attempting to map the label statement itself.
2031 /// Subclasses may override this routine to provide different behavior.
2032 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2033 SourceLocation LabelLoc, LabelDecl *Label) {
2034 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2037 /// \brief Build a new GNU statement expression.
2039 /// By default, performs semantic analysis to build the new expression.
2040 /// Subclasses may override this routine to provide different behavior.
2041 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2043 SourceLocation RParenLoc) {
2044 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2047 /// \brief Build a new __builtin_choose_expr expression.
2049 /// By default, performs semantic analysis to build the new expression.
2050 /// Subclasses may override this routine to provide different behavior.
2051 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2052 Expr *Cond, Expr *LHS, Expr *RHS,
2053 SourceLocation RParenLoc) {
2054 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2059 /// \brief Build a new generic selection expression.
2061 /// By default, performs semantic analysis to build the new expression.
2062 /// Subclasses may override this routine to provide different behavior.
2063 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2064 SourceLocation DefaultLoc,
2065 SourceLocation RParenLoc,
2066 Expr *ControllingExpr,
2067 ArrayRef<TypeSourceInfo *> Types,
2068 ArrayRef<Expr *> Exprs) {
2069 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2070 ControllingExpr, Types, Exprs);
2073 /// \brief Build a new overloaded operator call expression.
2075 /// By default, performs semantic analysis to build the new expression.
2076 /// The semantic analysis provides the behavior of template instantiation,
2077 /// copying with transformations that turn what looks like an overloaded
2078 /// operator call into a use of a builtin operator, performing
2079 /// argument-dependent lookup, etc. Subclasses may override this routine to
2080 /// provide different behavior.
2081 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2082 SourceLocation OpLoc,
2087 /// \brief Build a new C++ "named" cast expression, such as static_cast or
2088 /// reinterpret_cast.
2090 /// By default, this routine dispatches to one of the more-specific routines
2091 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2092 /// Subclasses may override this routine to provide different behavior.
2093 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2094 Stmt::StmtClass Class,
2095 SourceLocation LAngleLoc,
2096 TypeSourceInfo *TInfo,
2097 SourceLocation RAngleLoc,
2098 SourceLocation LParenLoc,
2100 SourceLocation RParenLoc) {
2102 case Stmt::CXXStaticCastExprClass:
2103 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2104 RAngleLoc, LParenLoc,
2105 SubExpr, RParenLoc);
2107 case Stmt::CXXDynamicCastExprClass:
2108 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2109 RAngleLoc, LParenLoc,
2110 SubExpr, RParenLoc);
2112 case Stmt::CXXReinterpretCastExprClass:
2113 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2114 RAngleLoc, LParenLoc,
2118 case Stmt::CXXConstCastExprClass:
2119 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2120 RAngleLoc, LParenLoc,
2121 SubExpr, RParenLoc);
2124 llvm_unreachable("Invalid C++ named cast");
2128 /// \brief Build a new C++ static_cast expression.
2130 /// By default, performs semantic analysis to build the new expression.
2131 /// Subclasses may override this routine to provide different behavior.
2132 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2133 SourceLocation LAngleLoc,
2134 TypeSourceInfo *TInfo,
2135 SourceLocation RAngleLoc,
2136 SourceLocation LParenLoc,
2138 SourceLocation RParenLoc) {
2139 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2141 SourceRange(LAngleLoc, RAngleLoc),
2142 SourceRange(LParenLoc, RParenLoc));
2145 /// \brief Build a new C++ dynamic_cast expression.
2147 /// By default, performs semantic analysis to build the new expression.
2148 /// Subclasses may override this routine to provide different behavior.
2149 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2150 SourceLocation LAngleLoc,
2151 TypeSourceInfo *TInfo,
2152 SourceLocation RAngleLoc,
2153 SourceLocation LParenLoc,
2155 SourceLocation RParenLoc) {
2156 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2158 SourceRange(LAngleLoc, RAngleLoc),
2159 SourceRange(LParenLoc, RParenLoc));
2162 /// \brief Build a new C++ reinterpret_cast expression.
2164 /// By default, performs semantic analysis to build the new expression.
2165 /// Subclasses may override this routine to provide different behavior.
2166 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2167 SourceLocation LAngleLoc,
2168 TypeSourceInfo *TInfo,
2169 SourceLocation RAngleLoc,
2170 SourceLocation LParenLoc,
2172 SourceLocation RParenLoc) {
2173 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2175 SourceRange(LAngleLoc, RAngleLoc),
2176 SourceRange(LParenLoc, RParenLoc));
2179 /// \brief Build a new C++ const_cast expression.
2181 /// By default, performs semantic analysis to build the new expression.
2182 /// Subclasses may override this routine to provide different behavior.
2183 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2184 SourceLocation LAngleLoc,
2185 TypeSourceInfo *TInfo,
2186 SourceLocation RAngleLoc,
2187 SourceLocation LParenLoc,
2189 SourceLocation RParenLoc) {
2190 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2192 SourceRange(LAngleLoc, RAngleLoc),
2193 SourceRange(LParenLoc, RParenLoc));
2196 /// \brief Build a new C++ functional-style cast expression.
2198 /// By default, performs semantic analysis to build the new expression.
2199 /// Subclasses may override this routine to provide different behavior.
2200 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2201 SourceLocation LParenLoc,
2203 SourceLocation RParenLoc) {
2204 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2205 MultiExprArg(&Sub, 1),
2209 /// \brief Build a new C++ typeid(type) expression.
2211 /// By default, performs semantic analysis to build the new expression.
2212 /// Subclasses may override this routine to provide different behavior.
2213 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2214 SourceLocation TypeidLoc,
2215 TypeSourceInfo *Operand,
2216 SourceLocation RParenLoc) {
2217 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2222 /// \brief Build a new C++ typeid(expr) expression.
2224 /// By default, performs semantic analysis to build the new expression.
2225 /// Subclasses may override this routine to provide different behavior.
2226 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2227 SourceLocation TypeidLoc,
2229 SourceLocation RParenLoc) {
2230 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2234 /// \brief Build a new C++ __uuidof(type) expression.
2236 /// By default, performs semantic analysis to build the new expression.
2237 /// Subclasses may override this routine to provide different behavior.
2238 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2239 SourceLocation TypeidLoc,
2240 TypeSourceInfo *Operand,
2241 SourceLocation RParenLoc) {
2242 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2246 /// \brief Build a new C++ __uuidof(expr) expression.
2248 /// By default, performs semantic analysis to build the new expression.
2249 /// Subclasses may override this routine to provide different behavior.
2250 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2251 SourceLocation TypeidLoc,
2253 SourceLocation RParenLoc) {
2254 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2258 /// \brief Build a new C++ "this" expression.
2260 /// By default, builds a new "this" expression without performing any
2261 /// semantic analysis. Subclasses may override this routine to provide
2262 /// different behavior.
2263 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2266 getSema().CheckCXXThisCapture(ThisLoc);
2267 return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
2270 /// \brief Build a new C++ throw expression.
2272 /// By default, performs semantic analysis to build the new expression.
2273 /// Subclasses may override this routine to provide different behavior.
2274 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2275 bool IsThrownVariableInScope) {
2276 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2279 /// \brief Build a new C++ default-argument expression.
2281 /// By default, builds a new default-argument expression, which does not
2282 /// require any semantic analysis. Subclasses may override this routine to
2283 /// provide different behavior.
2284 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
2285 ParmVarDecl *Param) {
2286 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
2289 /// \brief Build a new C++11 default-initialization expression.
2291 /// By default, builds a new default field initialization expression, which
2292 /// does not require any semantic analysis. Subclasses may override this
2293 /// routine to provide different behavior.
2294 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2296 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
2299 /// \brief Build a new C++ zero-initialization expression.
2301 /// By default, performs semantic analysis to build the new expression.
2302 /// Subclasses may override this routine to provide different behavior.
2303 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2304 SourceLocation LParenLoc,
2305 SourceLocation RParenLoc) {
2306 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
2310 /// \brief Build a new C++ "new" expression.
2312 /// By default, performs semantic analysis to build the new expression.
2313 /// Subclasses may override this routine to provide different behavior.
2314 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2316 SourceLocation PlacementLParen,
2317 MultiExprArg PlacementArgs,
2318 SourceLocation PlacementRParen,
2319 SourceRange TypeIdParens,
2320 QualType AllocatedType,
2321 TypeSourceInfo *AllocatedTypeInfo,
2323 SourceRange DirectInitRange,
2324 Expr *Initializer) {
2325 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2337 /// \brief Build a new C++ "delete" expression.
2339 /// By default, performs semantic analysis to build the new expression.
2340 /// Subclasses may override this routine to provide different behavior.
2341 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2342 bool IsGlobalDelete,
2345 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2349 /// \brief Build a new type trait expression.
2351 /// By default, performs semantic analysis to build the new expression.
2352 /// Subclasses may override this routine to provide different behavior.
2353 ExprResult RebuildTypeTrait(TypeTrait Trait,
2354 SourceLocation StartLoc,
2355 ArrayRef<TypeSourceInfo *> Args,
2356 SourceLocation RParenLoc) {
2357 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2360 /// \brief Build a new array type trait expression.
2362 /// By default, performs semantic analysis to build the new expression.
2363 /// Subclasses may override this routine to provide different behavior.
2364 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2365 SourceLocation StartLoc,
2366 TypeSourceInfo *TSInfo,
2368 SourceLocation RParenLoc) {
2369 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2372 /// \brief Build a new expression trait expression.
2374 /// By default, performs semantic analysis to build the new expression.
2375 /// Subclasses may override this routine to provide different behavior.
2376 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2377 SourceLocation StartLoc,
2379 SourceLocation RParenLoc) {
2380 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2383 /// \brief Build a new (previously unresolved) declaration reference
2386 /// By default, performs semantic analysis to build the new expression.
2387 /// Subclasses may override this routine to provide different behavior.
2388 ExprResult RebuildDependentScopeDeclRefExpr(
2389 NestedNameSpecifierLoc QualifierLoc,
2390 SourceLocation TemplateKWLoc,
2391 const DeclarationNameInfo &NameInfo,
2392 const TemplateArgumentListInfo *TemplateArgs,
2393 bool IsAddressOfOperand,
2394 TypeSourceInfo **RecoveryTSI) {
2396 SS.Adopt(QualifierLoc);
2398 if (TemplateArgs || TemplateKWLoc.isValid())
2399 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2402 return getSema().BuildQualifiedDeclarationNameExpr(
2403 SS, NameInfo, IsAddressOfOperand, RecoveryTSI);
2406 /// \brief Build a new template-id expression.
2408 /// By default, performs semantic analysis to build the new expression.
2409 /// Subclasses may override this routine to provide different behavior.
2410 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2411 SourceLocation TemplateKWLoc,
2414 const TemplateArgumentListInfo *TemplateArgs) {
2415 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2419 /// \brief Build a new object-construction expression.
2421 /// By default, performs semantic analysis to build the new expression.
2422 /// Subclasses may override this routine to provide different behavior.
2423 ExprResult RebuildCXXConstructExpr(QualType T,
2425 CXXConstructorDecl *Constructor,
2428 bool HadMultipleCandidates,
2429 bool ListInitialization,
2430 bool StdInitListInitialization,
2431 bool RequiresZeroInit,
2432 CXXConstructExpr::ConstructionKind ConstructKind,
2433 SourceRange ParenRange) {
2434 SmallVector<Expr*, 8> ConvertedArgs;
2435 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2439 return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
2441 HadMultipleCandidates,
2443 StdInitListInitialization,
2444 RequiresZeroInit, ConstructKind,
2448 /// \brief Build a new object-construction expression.
2450 /// By default, performs semantic analysis to build the new expression.
2451 /// Subclasses may override this routine to provide different behavior.
2452 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2453 SourceLocation LParenLoc,
2455 SourceLocation RParenLoc) {
2456 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2462 /// \brief Build a new object-construction expression.
2464 /// By default, performs semantic analysis to build the new expression.
2465 /// Subclasses may override this routine to provide different behavior.
2466 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2467 SourceLocation LParenLoc,
2469 SourceLocation RParenLoc) {
2470 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2476 /// \brief Build a new member reference expression.
2478 /// By default, performs semantic analysis to build the new expression.
2479 /// Subclasses may override this routine to provide different behavior.
2480 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2483 SourceLocation OperatorLoc,
2484 NestedNameSpecifierLoc QualifierLoc,
2485 SourceLocation TemplateKWLoc,
2486 NamedDecl *FirstQualifierInScope,
2487 const DeclarationNameInfo &MemberNameInfo,
2488 const TemplateArgumentListInfo *TemplateArgs) {
2490 SS.Adopt(QualifierLoc);
2492 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2493 OperatorLoc, IsArrow,
2495 FirstQualifierInScope,
2500 /// \brief Build a new member reference expression.
2502 /// By default, performs semantic analysis to build the new expression.
2503 /// Subclasses may override this routine to provide different behavior.
2504 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2505 SourceLocation OperatorLoc,
2507 NestedNameSpecifierLoc QualifierLoc,
2508 SourceLocation TemplateKWLoc,
2509 NamedDecl *FirstQualifierInScope,
2511 const TemplateArgumentListInfo *TemplateArgs) {
2513 SS.Adopt(QualifierLoc);
2515 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2516 OperatorLoc, IsArrow,
2518 FirstQualifierInScope,
2522 /// \brief Build a new noexcept expression.
2524 /// By default, performs semantic analysis to build the new expression.
2525 /// Subclasses may override this routine to provide different behavior.
2526 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2527 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2530 /// \brief Build a new expression to compute the length of a parameter pack.
2531 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
2532 SourceLocation PackLoc,
2533 SourceLocation RParenLoc,
2534 Optional<unsigned> Length) {
2536 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2537 OperatorLoc, Pack, PackLoc,
2538 RParenLoc, *Length);
2540 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2541 OperatorLoc, Pack, PackLoc,
2545 /// \brief Build a new Objective-C boxed expression.
2547 /// By default, performs semantic analysis to build the new expression.
2548 /// Subclasses may override this routine to provide different behavior.
2549 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
2550 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
2553 /// \brief Build a new Objective-C array literal.
2555 /// By default, performs semantic analysis to build the new expression.
2556 /// Subclasses may override this routine to provide different behavior.
2557 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
2558 Expr **Elements, unsigned NumElements) {
2559 return getSema().BuildObjCArrayLiteral(Range,
2560 MultiExprArg(Elements, NumElements));
2563 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
2564 Expr *Base, Expr *Key,
2565 ObjCMethodDecl *getterMethod,
2566 ObjCMethodDecl *setterMethod) {
2567 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
2568 getterMethod, setterMethod);
2571 /// \brief Build a new Objective-C dictionary literal.
2573 /// By default, performs semantic analysis to build the new expression.
2574 /// Subclasses may override this routine to provide different behavior.
2575 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
2576 ObjCDictionaryElement *Elements,
2577 unsigned NumElements) {
2578 return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElements);
2581 /// \brief Build a new Objective-C \@encode expression.
2583 /// By default, performs semantic analysis to build the new expression.
2584 /// Subclasses may override this routine to provide different behavior.
2585 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2586 TypeSourceInfo *EncodeTypeInfo,
2587 SourceLocation RParenLoc) {
2588 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
2591 /// \brief Build a new Objective-C class message.
2592 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2594 ArrayRef<SourceLocation> SelectorLocs,
2595 ObjCMethodDecl *Method,
2596 SourceLocation LBracLoc,
2598 SourceLocation RBracLoc) {
2599 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
2600 ReceiverTypeInfo->getType(),
2601 /*SuperLoc=*/SourceLocation(),
2602 Sel, Method, LBracLoc, SelectorLocs,
2606 /// \brief Build a new Objective-C instance message.
2607 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
2609 ArrayRef<SourceLocation> SelectorLocs,
2610 ObjCMethodDecl *Method,
2611 SourceLocation LBracLoc,
2613 SourceLocation RBracLoc) {
2614 return SemaRef.BuildInstanceMessage(Receiver,
2615 Receiver->getType(),
2616 /*SuperLoc=*/SourceLocation(),
2617 Sel, Method, LBracLoc, SelectorLocs,
2621 /// \brief Build a new Objective-C instance/class message to 'super'.
2622 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
2624 ArrayRef<SourceLocation> SelectorLocs,
2625 ObjCMethodDecl *Method,
2626 SourceLocation LBracLoc,
2628 SourceLocation RBracLoc) {
2629 ObjCInterfaceDecl *Class = Method->getClassInterface();
2630 QualType ReceiverTy = SemaRef.Context.getObjCInterfaceType(Class);
2632 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
2635 Sel, Method, LBracLoc, SelectorLocs,
2637 : SemaRef.BuildClassMessage(nullptr,
2640 Sel, Method, LBracLoc, SelectorLocs,
2646 /// \brief Build a new Objective-C ivar reference expression.
2648 /// By default, performs semantic analysis to build the new expression.
2649 /// Subclasses may override this routine to provide different behavior.
2650 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
2651 SourceLocation IvarLoc,
2652 bool IsArrow, bool IsFreeIvar) {
2653 // FIXME: We lose track of the IsFreeIvar bit.
2655 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
2656 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2657 /*FIXME:*/IvarLoc, IsArrow,
2658 SS, SourceLocation(),
2659 /*FirstQualifierInScope=*/nullptr,
2661 /*TemplateArgs=*/nullptr);
2664 /// \brief Build a new Objective-C property reference expression.
2666 /// By default, performs semantic analysis to build the new expression.
2667 /// Subclasses may override this routine to provide different behavior.
2668 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
2669 ObjCPropertyDecl *Property,
2670 SourceLocation PropertyLoc) {
2672 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
2673 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2674 /*FIXME:*/PropertyLoc,
2676 SS, SourceLocation(),
2677 /*FirstQualifierInScope=*/nullptr,
2679 /*TemplateArgs=*/nullptr);
2682 /// \brief Build a new Objective-C property reference expression.
2684 /// By default, performs semantic analysis to build the new expression.
2685 /// Subclasses may override this routine to provide different behavior.
2686 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
2687 ObjCMethodDecl *Getter,
2688 ObjCMethodDecl *Setter,
2689 SourceLocation PropertyLoc) {
2690 // Since these expressions can only be value-dependent, we do not
2691 // need to perform semantic analysis again.
2693 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
2694 VK_LValue, OK_ObjCProperty,
2695 PropertyLoc, Base));
2698 /// \brief Build a new Objective-C "isa" expression.
2700 /// By default, performs semantic analysis to build the new expression.
2701 /// Subclasses may override this routine to provide different behavior.
2702 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
2703 SourceLocation OpLoc, bool IsArrow) {
2705 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
2706 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
2708 SS, SourceLocation(),
2709 /*FirstQualifierInScope=*/nullptr,
2711 /*TemplateArgs=*/nullptr);
2714 /// \brief Build a new shuffle vector expression.
2716 /// By default, performs semantic analysis to build the new expression.
2717 /// Subclasses may override this routine to provide different behavior.
2718 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
2719 MultiExprArg SubExprs,
2720 SourceLocation RParenLoc) {
2721 // Find the declaration for __builtin_shufflevector
2722 const IdentifierInfo &Name
2723 = SemaRef.Context.Idents.get("__builtin_shufflevector");
2724 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
2725 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
2726 assert(!Lookup.empty() && "No __builtin_shufflevector?");
2728 // Build a reference to the __builtin_shufflevector builtin
2729 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
2730 Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
2731 SemaRef.Context.BuiltinFnTy,
2732 VK_RValue, BuiltinLoc);
2733 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
2734 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
2735 CK_BuiltinFnToFnPtr).get();
2737 // Build the CallExpr
2738 ExprResult TheCall = new (SemaRef.Context) CallExpr(
2739 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
2740 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
2742 // Type-check the __builtin_shufflevector expression.
2743 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
2746 /// \brief Build a new convert vector expression.
2747 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
2748 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
2749 SourceLocation RParenLoc) {
2750 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
2751 BuiltinLoc, RParenLoc);
2754 /// \brief Build a new template argument pack expansion.
2756 /// By default, performs semantic analysis to build a new pack expansion
2757 /// for a template argument. Subclasses may override this routine to provide
2758 /// different behavior.
2759 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
2760 SourceLocation EllipsisLoc,
2761 Optional<unsigned> NumExpansions) {
2762 switch (Pattern.getArgument().getKind()) {
2763 case TemplateArgument::Expression: {
2765 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
2766 EllipsisLoc, NumExpansions);
2767 if (Result.isInvalid())
2768 return TemplateArgumentLoc();
2770 return TemplateArgumentLoc(Result.get(), Result.get());
2773 case TemplateArgument::Template:
2774 return TemplateArgumentLoc(TemplateArgument(
2775 Pattern.getArgument().getAsTemplate(),
2777 Pattern.getTemplateQualifierLoc(),
2778 Pattern.getTemplateNameLoc(),
2781 case TemplateArgument::Null:
2782 case TemplateArgument::Integral:
2783 case TemplateArgument::Declaration:
2784 case TemplateArgument::Pack:
2785 case TemplateArgument::TemplateExpansion:
2786 case TemplateArgument::NullPtr:
2787 llvm_unreachable("Pack expansion pattern has no parameter packs");
2789 case TemplateArgument::Type:
2790 if (TypeSourceInfo *Expansion
2791 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
2794 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
2799 return TemplateArgumentLoc();
2802 /// \brief Build a new expression pack expansion.
2804 /// By default, performs semantic analysis to build a new pack expansion
2805 /// for an expression. Subclasses may override this routine to provide
2806 /// different behavior.
2807 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
2808 Optional<unsigned> NumExpansions) {
2809 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
2812 /// \brief Build a new C++1z fold-expression.
2814 /// By default, performs semantic analysis in order to build a new fold
2816 ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
2817 BinaryOperatorKind Operator,
2818 SourceLocation EllipsisLoc, Expr *RHS,
2819 SourceLocation RParenLoc) {
2820 return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
2824 /// \brief Build an empty C++1z fold-expression with the given operator.
2826 /// By default, produces the fallback value for the fold-expression, or
2827 /// produce an error if there is no fallback value.
2828 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
2829 BinaryOperatorKind Operator) {
2830 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
2833 /// \brief Build a new atomic operation expression.
2835 /// By default, performs semantic analysis to build the new expression.
2836 /// Subclasses may override this routine to provide different behavior.
2837 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
2838 MultiExprArg SubExprs,
2840 AtomicExpr::AtomicOp Op,
2841 SourceLocation RParenLoc) {
2842 // Just create the expression; there is not any interesting semantic
2843 // analysis here because we can't actually build an AtomicExpr until
2844 // we are sure it is semantically sound.
2845 return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
2850 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
2851 QualType ObjectType,
2852 NamedDecl *FirstQualifierInScope,
2855 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
2856 QualType ObjectType,
2857 NamedDecl *FirstQualifierInScope,
2860 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
2861 NamedDecl *FirstQualifierInScope,
2865 template<typename Derived>
2866 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
2870 switch (S->getStmtClass()) {
2871 case Stmt::NoStmtClass: break;
2873 // Transform individual statement nodes
2874 #define STMT(Node, Parent) \
2875 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
2876 #define ABSTRACT_STMT(Node)
2877 #define EXPR(Node, Parent)
2878 #include "clang/AST/StmtNodes.inc"
2880 // Transform expressions by calling TransformExpr.
2881 #define STMT(Node, Parent)
2882 #define ABSTRACT_STMT(Stmt)
2883 #define EXPR(Node, Parent) case Stmt::Node##Class:
2884 #include "clang/AST/StmtNodes.inc"
2886 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
2890 return getSema().ActOnExprStmt(E);
2897 template<typename Derived>
2898 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
2902 switch (S->getClauseKind()) {
2904 // Transform individual clause nodes
2905 #define OPENMP_CLAUSE(Name, Class) \
2906 case OMPC_ ## Name : \
2907 return getDerived().Transform ## Class(cast<Class>(S));
2908 #include "clang/Basic/OpenMPKinds.def"
2915 template<typename Derived>
2916 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
2920 switch (E->getStmtClass()) {
2921 case Stmt::NoStmtClass: break;
2922 #define STMT(Node, Parent) case Stmt::Node##Class: break;
2923 #define ABSTRACT_STMT(Stmt)
2924 #define EXPR(Node, Parent) \
2925 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
2926 #include "clang/AST/StmtNodes.inc"
2932 template<typename Derived>
2933 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
2935 // Initializers are instantiated like expressions, except that various outer
2936 // layers are stripped.
2940 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
2941 Init = ExprTemp->getSubExpr();
2943 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
2944 Init = MTE->GetTemporaryExpr();
2946 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
2947 Init = Binder->getSubExpr();
2949 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
2950 Init = ICE->getSubExprAsWritten();
2952 if (CXXStdInitializerListExpr *ILE =
2953 dyn_cast<CXXStdInitializerListExpr>(Init))
2954 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
2956 // If this is copy-initialization, we only need to reconstruct
2957 // InitListExprs. Other forms of copy-initialization will be a no-op if
2958 // the initializer is already the right type.
2959 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
2960 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
2961 return getDerived().TransformExpr(Init);
2963 // Revert value-initialization back to empty parens.
2964 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
2965 SourceRange Parens = VIE->getSourceRange();
2966 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
2970 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
2971 if (isa<ImplicitValueInitExpr>(Init))
2972 return getDerived().RebuildParenListExpr(SourceLocation(), None,
2975 // Revert initialization by constructor back to a parenthesized or braced list
2976 // of expressions. Any other form of initializer can just be reused directly.
2977 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
2978 return getDerived().TransformExpr(Init);
2980 // If the initialization implicitly converted an initializer list to a
2981 // std::initializer_list object, unwrap the std::initializer_list too.
2982 if (Construct && Construct->isStdInitListInitialization())
2983 return TransformInitializer(Construct->getArg(0), NotCopyInit);
2985 SmallVector<Expr*, 8> NewArgs;
2986 bool ArgChanged = false;
2987 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
2988 /*IsCall*/true, NewArgs, &ArgChanged))
2991 // If this was list initialization, revert to list form.
2992 if (Construct->isListInitialization())
2993 return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
2994 Construct->getLocEnd(),
2995 Construct->getType());
2997 // Build a ParenListExpr to represent anything else.
2998 SourceRange Parens = Construct->getParenOrBraceRange();
2999 if (Parens.isInvalid()) {
3000 // This was a variable declaration's initialization for which no initializer
3002 assert(NewArgs.empty() &&
3003 "no parens or braces but have direct init with arguments?");
3006 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3010 template<typename Derived>
3011 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
3014 SmallVectorImpl<Expr *> &Outputs,
3016 for (unsigned I = 0; I != NumInputs; ++I) {
3017 // If requested, drop call arguments that need to be dropped.
3018 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3025 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3026 Expr *Pattern = Expansion->getPattern();
3028 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3029 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3030 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3032 // Determine whether the set of unexpanded parameter packs can and should
3035 bool RetainExpansion = false;
3036 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3037 Optional<unsigned> NumExpansions = OrigNumExpansions;
3038 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3039 Pattern->getSourceRange(),
3041 Expand, RetainExpansion,
3046 // The transform has determined that we should perform a simple
3047 // transformation on the pack expansion, producing another pack
3049 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3050 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3051 if (OutPattern.isInvalid())
3054 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3055 Expansion->getEllipsisLoc(),
3057 if (Out.isInvalid())
3062 Outputs.push_back(Out.get());
3066 // Record right away that the argument was changed. This needs
3067 // to happen even if the array expands to nothing.
3068 if (ArgChanged) *ArgChanged = true;
3070 // The transform has determined that we should perform an elementwise
3071 // expansion of the pattern. Do so.
3072 for (unsigned I = 0; I != *NumExpansions; ++I) {
3073 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3074 ExprResult Out = getDerived().TransformExpr(Pattern);
3075 if (Out.isInvalid())
3078 // FIXME: Can this happen? We should not try to expand the pack
3080 if (Out.get()->containsUnexpandedParameterPack()) {
3081 Out = getDerived().RebuildPackExpansion(
3082 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3083 if (Out.isInvalid())
3087 Outputs.push_back(Out.get());
3090 // If we're supposed to retain a pack expansion, do so by temporarily
3091 // forgetting the partially-substituted parameter pack.
3092 if (RetainExpansion) {
3093 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3095 ExprResult Out = getDerived().TransformExpr(Pattern);
3096 if (Out.isInvalid())
3099 Out = getDerived().RebuildPackExpansion(
3100 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3101 if (Out.isInvalid())
3104 Outputs.push_back(Out.get());
3111 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3112 : getDerived().TransformExpr(Inputs[I]);
3113 if (Result.isInvalid())
3116 if (Result.get() != Inputs[I] && ArgChanged)
3119 Outputs.push_back(Result.get());
3125 template<typename Derived>
3126 NestedNameSpecifierLoc
3127 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3128 NestedNameSpecifierLoc NNS,
3129 QualType ObjectType,
3130 NamedDecl *FirstQualifierInScope) {
3131 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3132 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3133 Qualifier = Qualifier.getPrefix())
3134 Qualifiers.push_back(Qualifier);
3137 while (!Qualifiers.empty()) {
3138 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3139 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3141 switch (QNNS->getKind()) {
3142 case NestedNameSpecifier::Identifier:
3143 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr,
3144 *QNNS->getAsIdentifier(),
3145 Q.getLocalBeginLoc(),
3147 ObjectType, false, SS,
3148 FirstQualifierInScope, false))
3149 return NestedNameSpecifierLoc();
3153 case NestedNameSpecifier::Namespace: {
3155 = cast_or_null<NamespaceDecl>(
3156 getDerived().TransformDecl(
3157 Q.getLocalBeginLoc(),
3158 QNNS->getAsNamespace()));
3159 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3163 case NestedNameSpecifier::NamespaceAlias: {
3164 NamespaceAliasDecl *Alias
3165 = cast_or_null<NamespaceAliasDecl>(
3166 getDerived().TransformDecl(Q.getLocalBeginLoc(),
3167 QNNS->getAsNamespaceAlias()));
3168 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3169 Q.getLocalEndLoc());
3173 case NestedNameSpecifier::Global:
3174 // There is no meaningful transformation that one could perform on the
3176 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3179 case NestedNameSpecifier::Super: {
3181 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3182 SourceLocation(), QNNS->getAsRecordDecl()));
3183 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3187 case NestedNameSpecifier::TypeSpecWithTemplate:
3188 case NestedNameSpecifier::TypeSpec: {
3189 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3190 FirstQualifierInScope, SS);
3193 return NestedNameSpecifierLoc();
3195 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3196 (SemaRef.getLangOpts().CPlusPlus11 &&
3197 TL.getType()->isEnumeralType())) {
3198 assert(!TL.getType().hasLocalQualifiers() &&
3199 "Can't get cv-qualifiers here");
3200 if (TL.getType()->isEnumeralType())
3201 SemaRef.Diag(TL.getBeginLoc(),
3202 diag::warn_cxx98_compat_enum_nested_name_spec);
3203 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3204 Q.getLocalEndLoc());
3207 // If the nested-name-specifier is an invalid type def, don't emit an
3208 // error because a previous error should have already been emitted.
3209 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3210 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3211 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3212 << TL.getType() << SS.getRange();
3214 return NestedNameSpecifierLoc();
3218 // The qualifier-in-scope and object type only apply to the leftmost entity.
3219 FirstQualifierInScope = nullptr;
3220 ObjectType = QualType();
3223 // Don't rebuild the nested-name-specifier if we don't have to.
3224 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3225 !getDerived().AlwaysRebuild())
3228 // If we can re-use the source-location data from the original
3229 // nested-name-specifier, do so.
3230 if (SS.location_size() == NNS.getDataLength() &&
3231 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3232 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3234 // Allocate new nested-name-specifier location information.
3235 return SS.getWithLocInContext(SemaRef.Context);
3238 template<typename Derived>
3240 TreeTransform<Derived>
3241 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3242 DeclarationName Name = NameInfo.getName();
3244 return DeclarationNameInfo();
3246 switch (Name.getNameKind()) {
3247 case DeclarationName::Identifier:
3248 case DeclarationName::ObjCZeroArgSelector:
3249 case DeclarationName::ObjCOneArgSelector:
3250 case DeclarationName::ObjCMultiArgSelector:
3251 case DeclarationName::CXXOperatorName:
3252 case DeclarationName::CXXLiteralOperatorName:
3253 case DeclarationName::CXXUsingDirective:
3256 case DeclarationName::CXXConstructorName:
3257 case DeclarationName::CXXDestructorName:
3258 case DeclarationName::CXXConversionFunctionName: {
3259 TypeSourceInfo *NewTInfo;
3260 CanQualType NewCanTy;
3261 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3262 NewTInfo = getDerived().TransformType(OldTInfo);
3264 return DeclarationNameInfo();
3265 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3269 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3270 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3272 return DeclarationNameInfo();
3273 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3276 DeclarationName NewName
3277 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3279 DeclarationNameInfo NewNameInfo(NameInfo);
3280 NewNameInfo.setName(NewName);
3281 NewNameInfo.setNamedTypeInfo(NewTInfo);
3286 llvm_unreachable("Unknown name kind.");
3289 template<typename Derived>
3291 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3293 SourceLocation NameLoc,
3294 QualType ObjectType,
3295 NamedDecl *FirstQualifierInScope) {
3296 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3297 TemplateDecl *Template = QTN->getTemplateDecl();
3298 assert(Template && "qualified template name must refer to a template");
3300 TemplateDecl *TransTemplate
3301 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3304 return TemplateName();
3306 if (!getDerived().AlwaysRebuild() &&
3307 SS.getScopeRep() == QTN->getQualifier() &&
3308 TransTemplate == Template)
3311 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3315 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3316 if (SS.getScopeRep()) {
3317 // These apply to the scope specifier, not the template.
3318 ObjectType = QualType();
3319 FirstQualifierInScope = nullptr;
3322 if (!getDerived().AlwaysRebuild() &&
3323 SS.getScopeRep() == DTN->getQualifier() &&
3324 ObjectType.isNull())
3327 if (DTN->isIdentifier()) {
3328 return getDerived().RebuildTemplateName(SS,
3329 *DTN->getIdentifier(),
3332 FirstQualifierInScope);
3335 return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
3339 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3340 TemplateDecl *TransTemplate
3341 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3344 return TemplateName();
3346 if (!getDerived().AlwaysRebuild() &&
3347 TransTemplate == Template)
3350 return TemplateName(TransTemplate);
3353 if (SubstTemplateTemplateParmPackStorage *SubstPack
3354 = Name.getAsSubstTemplateTemplateParmPack()) {
3355 TemplateTemplateParmDecl *TransParam
3356 = cast_or_null<TemplateTemplateParmDecl>(
3357 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3359 return TemplateName();
3361 if (!getDerived().AlwaysRebuild() &&
3362 TransParam == SubstPack->getParameterPack())
3365 return getDerived().RebuildTemplateName(TransParam,
3366 SubstPack->getArgumentPack());
3369 // These should be getting filtered out before they reach the AST.
3370 llvm_unreachable("overloaded function decl survived to here");
3373 template<typename Derived>
3374 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3375 const TemplateArgument &Arg,
3376 TemplateArgumentLoc &Output) {
3377 SourceLocation Loc = getDerived().getBaseLocation();
3378 switch (Arg.getKind()) {
3379 case TemplateArgument::Null:
3380 llvm_unreachable("null template argument in TreeTransform");
3383 case TemplateArgument::Type:
3384 Output = TemplateArgumentLoc(Arg,
3385 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3389 case TemplateArgument::Template:
3390 case TemplateArgument::TemplateExpansion: {
3391 NestedNameSpecifierLocBuilder Builder;
3392 TemplateName Template = Arg.getAsTemplate();
3393 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3394 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3395 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3396 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3398 if (Arg.getKind() == TemplateArgument::Template)
3399 Output = TemplateArgumentLoc(Arg,
3400 Builder.getWithLocInContext(SemaRef.Context),
3403 Output = TemplateArgumentLoc(Arg,
3404 Builder.getWithLocInContext(SemaRef.Context),
3410 case TemplateArgument::Expression:
3411 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3414 case TemplateArgument::Declaration:
3415 case TemplateArgument::Integral:
3416 case TemplateArgument::Pack:
3417 case TemplateArgument::NullPtr:
3418 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3423 template<typename Derived>
3424 bool TreeTransform<Derived>::TransformTemplateArgument(
3425 const TemplateArgumentLoc &Input,
3426 TemplateArgumentLoc &Output) {
3427 const TemplateArgument &Arg = Input.getArgument();
3428 switch (Arg.getKind()) {
3429 case TemplateArgument::Null:
3430 case TemplateArgument::Integral:
3431 case TemplateArgument::Pack:
3432 case TemplateArgument::Declaration:
3433 case TemplateArgument::NullPtr:
3434 llvm_unreachable("Unexpected TemplateArgument");
3436 case TemplateArgument::Type: {
3437 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3439 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3441 DI = getDerived().TransformType(DI);
3442 if (!DI) return true;
3444 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3448 case TemplateArgument::Template: {
3449 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3451 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3457 SS.Adopt(QualifierLoc);
3458 TemplateName Template
3459 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3460 Input.getTemplateNameLoc());
3461 if (Template.isNull())
3464 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3465 Input.getTemplateNameLoc());
3469 case TemplateArgument::TemplateExpansion:
3470 llvm_unreachable("Caller should expand pack expansions");
3472 case TemplateArgument::Expression: {
3473 // Template argument expressions are constant expressions.
3474 EnterExpressionEvaluationContext Unevaluated(getSema(),
3475 Sema::ConstantEvaluated);
3477 Expr *InputExpr = Input.getSourceExpression();
3478 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
3480 ExprResult E = getDerived().TransformExpr(InputExpr);
3481 E = SemaRef.ActOnConstantExpression(E);
3482 if (E.isInvalid()) return true;
3483 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
3488 // Work around bogus GCC warning
3492 /// \brief Iterator adaptor that invents template argument location information
3493 /// for each of the template arguments in its underlying iterator.
3494 template<typename Derived, typename InputIterator>
3495 class TemplateArgumentLocInventIterator {
3496 TreeTransform<Derived> &Self;
3500 typedef TemplateArgumentLoc value_type;
3501 typedef TemplateArgumentLoc reference;
3502 typedef typename std::iterator_traits<InputIterator>::difference_type
3504 typedef std::input_iterator_tag iterator_category;
3507 TemplateArgumentLoc Arg;
3510 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
3512 const TemplateArgumentLoc *operator->() const { return &Arg; }
3515 TemplateArgumentLocInventIterator() { }
3517 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
3519 : Self(Self), Iter(Iter) { }
3521 TemplateArgumentLocInventIterator &operator++() {
3526 TemplateArgumentLocInventIterator operator++(int) {
3527 TemplateArgumentLocInventIterator Old(*this);
3532 reference operator*() const {
3533 TemplateArgumentLoc Result;
3534 Self.InventTemplateArgumentLoc(*Iter, Result);
3538 pointer operator->() const { return pointer(**this); }
3540 friend bool operator==(const TemplateArgumentLocInventIterator &X,
3541 const TemplateArgumentLocInventIterator &Y) {
3542 return X.Iter == Y.Iter;
3545 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
3546 const TemplateArgumentLocInventIterator &Y) {
3547 return X.Iter != Y.Iter;
3551 template<typename Derived>
3552 template<typename InputIterator>
3553 bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
3555 TemplateArgumentListInfo &Outputs) {
3556 for (; First != Last; ++First) {
3557 TemplateArgumentLoc Out;
3558 TemplateArgumentLoc In = *First;
3560 if (In.getArgument().getKind() == TemplateArgument::Pack) {
3561 // Unpack argument packs, which we translate them into separate
3563 // FIXME: We could do much better if we could guarantee that the
3564 // TemplateArgumentLocInfo for the pack expansion would be usable for
3565 // all of the template arguments in the argument pack.
3566 typedef TemplateArgumentLocInventIterator<Derived,
3567 TemplateArgument::pack_iterator>
3569 if (TransformTemplateArguments(PackLocIterator(*this,
3570 In.getArgument().pack_begin()),
3571 PackLocIterator(*this,
3572 In.getArgument().pack_end()),
3579 if (In.getArgument().isPackExpansion()) {
3580 // We have a pack expansion, for which we will be substituting into
3582 SourceLocation Ellipsis;
3583 Optional<unsigned> OrigNumExpansions;
3584 TemplateArgumentLoc Pattern
3585 = getSema().getTemplateArgumentPackExpansionPattern(
3586 In, Ellipsis, OrigNumExpansions);
3588 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3589 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3590 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3592 // Determine whether the set of unexpanded parameter packs can and should
3595 bool RetainExpansion = false;
3596 Optional<unsigned> NumExpansions = OrigNumExpansions;
3597 if (getDerived().TryExpandParameterPacks(Ellipsis,
3598 Pattern.getSourceRange(),
3606 // The transform has determined that we should perform a simple
3607 // transformation on the pack expansion, producing another pack
3609 TemplateArgumentLoc OutPattern;
3610 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3611 if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
3614 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
3616 if (Out.getArgument().isNull())
3619 Outputs.addArgument(Out);
3623 // The transform has determined that we should perform an elementwise
3624 // expansion of the pattern. Do so.
3625 for (unsigned I = 0; I != *NumExpansions; ++I) {
3626 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3628 if (getDerived().TransformTemplateArgument(Pattern, Out))
3631 if (Out.getArgument().containsUnexpandedParameterPack()) {
3632 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3634 if (Out.getArgument().isNull())
3638 Outputs.addArgument(Out);
3641 // If we're supposed to retain a pack expansion, do so by temporarily
3642 // forgetting the partially-substituted parameter pack.
3643 if (RetainExpansion) {
3644 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3646 if (getDerived().TransformTemplateArgument(Pattern, Out))
3649 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3651 if (Out.getArgument().isNull())
3654 Outputs.addArgument(Out);
3661 if (getDerived().TransformTemplateArgument(In, Out))
3664 Outputs.addArgument(Out);
3671 //===----------------------------------------------------------------------===//
3672 // Type transformation
3673 //===----------------------------------------------------------------------===//
3675 template<typename Derived>
3676 QualType TreeTransform<Derived>::TransformType(QualType T) {
3677 if (getDerived().AlreadyTransformed(T))
3680 // Temporary workaround. All of these transformations should
3681 // eventually turn into transformations on TypeLocs.
3682 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
3683 getDerived().getBaseLocation());
3685 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
3690 return NewDI->getType();
3693 template<typename Derived>
3694 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
3695 // Refine the base location to the type's location.
3696 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
3697 getDerived().getBaseEntity());
3698 if (getDerived().AlreadyTransformed(DI->getType()))
3703 TypeLoc TL = DI->getTypeLoc();
3704 TLB.reserve(TL.getFullDataSize());
3706 QualType Result = getDerived().TransformType(TLB, TL);
3707 if (Result.isNull())
3710 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3713 template<typename Derived>
3715 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
3716 switch (T.getTypeLocClass()) {
3717 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3718 #define TYPELOC(CLASS, PARENT) \
3719 case TypeLoc::CLASS: \
3720 return getDerived().Transform##CLASS##Type(TLB, \
3721 T.castAs<CLASS##TypeLoc>());
3722 #include "clang/AST/TypeLocNodes.def"
3725 llvm_unreachable("unhandled type loc!");
3728 /// FIXME: By default, this routine adds type qualifiers only to types
3729 /// that can have qualifiers, and silently suppresses those qualifiers
3730 /// that are not permitted (e.g., qualifiers on reference or function
3731 /// types). This is the right thing for template instantiation, but
3732 /// probably not for other clients.
3733 template<typename Derived>
3735 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
3736 QualifiedTypeLoc T) {
3737 Qualifiers Quals = T.getType().getLocalQualifiers();
3739 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
3740 if (Result.isNull())
3743 // Silently suppress qualifiers if the result type can't be qualified.
3744 // FIXME: this is the right thing for template instantiation, but
3745 // probably not for other clients.
3746 if (Result->isFunctionType() || Result->isReferenceType())
3749 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
3751 if (Quals.hasObjCLifetime()) {
3752 if (!Result->isObjCLifetimeType() && !Result->isDependentType())
3753 Quals.removeObjCLifetime();
3754 else if (Result.getObjCLifetime()) {
3756 // A lifetime qualifier applied to a substituted template parameter
3757 // overrides the lifetime qualifier from the template argument.
3758 const AutoType *AutoTy;
3759 if (const SubstTemplateTypeParmType *SubstTypeParam
3760 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
3761 QualType Replacement = SubstTypeParam->getReplacementType();
3762 Qualifiers Qs = Replacement.getQualifiers();
3763 Qs.removeObjCLifetime();
3765 = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
3767 Result = SemaRef.Context.getSubstTemplateTypeParmType(
3768 SubstTypeParam->getReplacedParameter(),
3770 TLB.TypeWasModifiedSafely(Result);
3771 } else if ((AutoTy = dyn_cast<AutoType>(Result)) && AutoTy->isDeduced()) {
3772 // 'auto' types behave the same way as template parameters.
3773 QualType Deduced = AutoTy->getDeducedType();
3774 Qualifiers Qs = Deduced.getQualifiers();
3775 Qs.removeObjCLifetime();
3776 Deduced = SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(),
3778 Result = SemaRef.Context.getAutoType(Deduced, AutoTy->isDecltypeAuto(),
3779 AutoTy->isDependentType());
3780 TLB.TypeWasModifiedSafely(Result);
3782 // Otherwise, complain about the addition of a qualifier to an
3783 // already-qualified type.
3784 SourceRange R = T.getUnqualifiedLoc().getSourceRange();
3785 SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
3788 Quals.removeObjCLifetime();
3792 if (!Quals.empty()) {
3793 Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
3794 // BuildQualifiedType might not add qualifiers if they are invalid.
3795 if (Result.hasLocalQualifiers())
3796 TLB.push<QualifiedTypeLoc>(Result);
3797 // No location information to preserve.
3803 template<typename Derived>
3805 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
3806 QualType ObjectType,
3807 NamedDecl *UnqualLookup,
3809 if (getDerived().AlreadyTransformed(TL.getType()))
3812 TypeSourceInfo *TSI =
3813 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
3815 return TSI->getTypeLoc();
3819 template<typename Derived>
3821 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3822 QualType ObjectType,
3823 NamedDecl *UnqualLookup,
3825 if (getDerived().AlreadyTransformed(TSInfo->getType()))
3828 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
3832 template <typename Derived>
3833 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
3834 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
3836 QualType T = TL.getType();
3837 assert(!getDerived().AlreadyTransformed(T));
3842 if (isa<TemplateSpecializationType>(T)) {
3843 TemplateSpecializationTypeLoc SpecTL =
3844 TL.castAs<TemplateSpecializationTypeLoc>();
3846 TemplateName Template
3847 = getDerived().TransformTemplateName(SS,
3848 SpecTL.getTypePtr()->getTemplateName(),
3849 SpecTL.getTemplateNameLoc(),
3850 ObjectType, UnqualLookup);
3851 if (Template.isNull())
3854 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
3856 } else if (isa<DependentTemplateSpecializationType>(T)) {
3857 DependentTemplateSpecializationTypeLoc SpecTL =
3858 TL.castAs<DependentTemplateSpecializationTypeLoc>();
3860 TemplateName Template
3861 = getDerived().RebuildTemplateName(SS,
3862 *SpecTL.getTypePtr()->getIdentifier(),
3863 SpecTL.getTemplateNameLoc(),
3864 ObjectType, UnqualLookup);
3865 if (Template.isNull())
3868 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
3873 // Nothing special needs to be done for these.
3874 Result = getDerived().TransformType(TLB, TL);
3877 if (Result.isNull())
3880 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3883 template <class TyLoc> static inline
3884 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
3885 TyLoc NewT = TLB.push<TyLoc>(T.getType());
3886 NewT.setNameLoc(T.getNameLoc());
3890 template<typename Derived>
3891 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
3893 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
3894 NewT.setBuiltinLoc(T.getBuiltinLoc());
3895 if (T.needsExtraLocalData())
3896 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
3900 template<typename Derived>
3901 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
3904 return TransformTypeSpecType(TLB, T);
3907 template <typename Derived>
3908 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
3909 AdjustedTypeLoc TL) {
3910 // Adjustments applied during transformation are handled elsewhere.
3911 return getDerived().TransformType(TLB, TL.getOriginalLoc());
3914 template<typename Derived>
3915 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
3916 DecayedTypeLoc TL) {
3917 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
3918 if (OriginalType.isNull())
3921 QualType Result = TL.getType();
3922 if (getDerived().AlwaysRebuild() ||
3923 OriginalType != TL.getOriginalLoc().getType())
3924 Result = SemaRef.Context.getDecayedType(OriginalType);
3925 TLB.push<DecayedTypeLoc>(Result);
3926 // Nothing to set for DecayedTypeLoc.
3930 template<typename Derived>
3931 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
3932 PointerTypeLoc TL) {
3933 QualType PointeeType
3934 = getDerived().TransformType(TLB, TL.getPointeeLoc());
3935 if (PointeeType.isNull())
3938 QualType Result = TL.getType();
3939 if (PointeeType->getAs<ObjCObjectType>()) {
3940 // A dependent pointer type 'T *' has is being transformed such
3941 // that an Objective-C class type is being replaced for 'T'. The
3942 // resulting pointer type is an ObjCObjectPointerType, not a
3944 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
3946 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
3947 NewT.setStarLoc(TL.getStarLoc());
3951 if (getDerived().AlwaysRebuild() ||
3952 PointeeType != TL.getPointeeLoc().getType()) {
3953 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
3954 if (Result.isNull())
3958 // Objective-C ARC can add lifetime qualifiers to the type that we're
3960 TLB.TypeWasModifiedSafely(Result->getPointeeType());
3962 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
3963 NewT.setSigilLoc(TL.getSigilLoc());
3967 template<typename Derived>
3969 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
3970 BlockPointerTypeLoc TL) {
3971 QualType PointeeType
3972 = getDerived().TransformType(TLB, TL.getPointeeLoc());
3973 if (PointeeType.isNull())
3976 QualType Result = TL.getType();
3977 if (getDerived().AlwaysRebuild() ||
3978 PointeeType != TL.getPointeeLoc().getType()) {
3979 Result = getDerived().RebuildBlockPointerType(PointeeType,
3981 if (Result.isNull())
3985 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
3986 NewT.setSigilLoc(TL.getSigilLoc());
3990 /// Transforms a reference type. Note that somewhat paradoxically we
3991 /// don't care whether the type itself is an l-value type or an r-value
3992 /// type; we only care if the type was *written* as an l-value type
3993 /// or an r-value type.
3994 template<typename Derived>
3996 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
3997 ReferenceTypeLoc TL) {
3998 const ReferenceType *T = TL.getTypePtr();
4000 // Note that this works with the pointee-as-written.
4001 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4002 if (PointeeType.isNull())
4005 QualType Result = TL.getType();
4006 if (getDerived().AlwaysRebuild() ||
4007 PointeeType != T->getPointeeTypeAsWritten()) {
4008 Result = getDerived().RebuildReferenceType(PointeeType,
4009 T->isSpelledAsLValue(),
4011 if (Result.isNull())
4015 // Objective-C ARC can add lifetime qualifiers to the type that we're
4017 TLB.TypeWasModifiedSafely(
4018 Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4020 // r-value references can be rebuilt as l-value references.
4021 ReferenceTypeLoc NewTL;
4022 if (isa<LValueReferenceType>(Result))
4023 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4025 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4026 NewTL.setSigilLoc(TL.getSigilLoc());
4031 template<typename Derived>
4033 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4034 LValueReferenceTypeLoc TL) {
4035 return TransformReferenceType(TLB, TL);
4038 template<typename Derived>
4040 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4041 RValueReferenceTypeLoc TL) {
4042 return TransformReferenceType(TLB, TL);
4045 template<typename Derived>
4047 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4048 MemberPointerTypeLoc TL) {
4049 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4050 if (PointeeType.isNull())
4053 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4054 TypeSourceInfo *NewClsTInfo = nullptr;
4056 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4061 const MemberPointerType *T = TL.getTypePtr();
4062 QualType OldClsType = QualType(T->getClass(), 0);
4063 QualType NewClsType;
4065 NewClsType = NewClsTInfo->getType();
4067 NewClsType = getDerived().TransformType(OldClsType);
4068 if (NewClsType.isNull())
4072 QualType Result = TL.getType();
4073 if (getDerived().AlwaysRebuild() ||
4074 PointeeType != T->getPointeeType() ||
4075 NewClsType != OldClsType) {
4076 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4078 if (Result.isNull())
4082 // If we had to adjust the pointee type when building a member pointer, make
4083 // sure to push TypeLoc info for it.
4084 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4085 if (MPT && PointeeType != MPT->getPointeeType()) {
4086 assert(isa<AdjustedType>(MPT->getPointeeType()));
4087 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4090 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4091 NewTL.setSigilLoc(TL.getSigilLoc());
4092 NewTL.setClassTInfo(NewClsTInfo);
4097 template<typename Derived>
4099 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4100 ConstantArrayTypeLoc TL) {
4101 const ConstantArrayType *T = TL.getTypePtr();
4102 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4103 if (ElementType.isNull())
4106 QualType Result = TL.getType();
4107 if (getDerived().AlwaysRebuild() ||
4108 ElementType != T->getElementType()) {
4109 Result = getDerived().RebuildConstantArrayType(ElementType,
4110 T->getSizeModifier(),
4112 T->getIndexTypeCVRQualifiers(),
4113 TL.getBracketsRange());
4114 if (Result.isNull())
4118 // We might have either a ConstantArrayType or a VariableArrayType now:
4119 // a ConstantArrayType is allowed to have an element type which is a
4120 // VariableArrayType if the type is dependent. Fortunately, all array
4121 // types have the same location layout.
4122 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4123 NewTL.setLBracketLoc(TL.getLBracketLoc());
4124 NewTL.setRBracketLoc(TL.getRBracketLoc());
4126 Expr *Size = TL.getSizeExpr();
4128 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4129 Sema::ConstantEvaluated);
4130 Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4131 Size = SemaRef.ActOnConstantExpression(Size).get();
4133 NewTL.setSizeExpr(Size);
4138 template<typename Derived>
4139 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4140 TypeLocBuilder &TLB,
4141 IncompleteArrayTypeLoc TL) {
4142 const IncompleteArrayType *T = TL.getTypePtr();
4143 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4144 if (ElementType.isNull())
4147 QualType Result = TL.getType();
4148 if (getDerived().AlwaysRebuild() ||
4149 ElementType != T->getElementType()) {
4150 Result = getDerived().RebuildIncompleteArrayType(ElementType,
4151 T->getSizeModifier(),
4152 T->getIndexTypeCVRQualifiers(),
4153 TL.getBracketsRange());
4154 if (Result.isNull())
4158 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4159 NewTL.setLBracketLoc(TL.getLBracketLoc());
4160 NewTL.setRBracketLoc(TL.getRBracketLoc());
4161 NewTL.setSizeExpr(nullptr);
4166 template<typename Derived>
4168 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4169 VariableArrayTypeLoc TL) {
4170 const VariableArrayType *T = TL.getTypePtr();
4171 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4172 if (ElementType.isNull())
4175 ExprResult SizeResult
4176 = getDerived().TransformExpr(T->getSizeExpr());
4177 if (SizeResult.isInvalid())
4180 Expr *Size = SizeResult.get();
4182 QualType Result = TL.getType();
4183 if (getDerived().AlwaysRebuild() ||
4184 ElementType != T->getElementType() ||
4185 Size != T->getSizeExpr()) {
4186 Result = getDerived().RebuildVariableArrayType(ElementType,
4187 T->getSizeModifier(),
4189 T->getIndexTypeCVRQualifiers(),
4190 TL.getBracketsRange());
4191 if (Result.isNull())
4195 // We might have constant size array now, but fortunately it has the same
4197 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4198 NewTL.setLBracketLoc(TL.getLBracketLoc());
4199 NewTL.setRBracketLoc(TL.getRBracketLoc());
4200 NewTL.setSizeExpr(Size);
4205 template<typename Derived>
4207 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4208 DependentSizedArrayTypeLoc TL) {
4209 const DependentSizedArrayType *T = TL.getTypePtr();
4210 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4211 if (ElementType.isNull())
4214 // Array bounds are constant expressions.
4215 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4216 Sema::ConstantEvaluated);
4218 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4219 Expr *origSize = TL.getSizeExpr();
4220 if (!origSize) origSize = T->getSizeExpr();
4222 ExprResult sizeResult
4223 = getDerived().TransformExpr(origSize);
4224 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4225 if (sizeResult.isInvalid())
4228 Expr *size = sizeResult.get();
4230 QualType Result = TL.getType();
4231 if (getDerived().AlwaysRebuild() ||
4232 ElementType != T->getElementType() ||
4234 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4235 T->getSizeModifier(),
4237 T->getIndexTypeCVRQualifiers(),
4238 TL.getBracketsRange());
4239 if (Result.isNull())
4243 // We might have any sort of array type now, but fortunately they
4244 // all have the same location layout.
4245 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4246 NewTL.setLBracketLoc(TL.getLBracketLoc());
4247 NewTL.setRBracketLoc(TL.getRBracketLoc());
4248 NewTL.setSizeExpr(size);
4253 template<typename Derived>
4254 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4255 TypeLocBuilder &TLB,
4256 DependentSizedExtVectorTypeLoc TL) {
4257 const DependentSizedExtVectorType *T = TL.getTypePtr();
4259 // FIXME: ext vector locs should be nested
4260 QualType ElementType = getDerived().TransformType(T->getElementType());
4261 if (ElementType.isNull())
4264 // Vector sizes are constant expressions.
4265 EnterExpressionEvaluationContext Unevaluated(SemaRef,
4266 Sema::ConstantEvaluated);
4268 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4269 Size = SemaRef.ActOnConstantExpression(Size);
4270 if (Size.isInvalid())
4273 QualType Result = TL.getType();
4274 if (getDerived().AlwaysRebuild() ||
4275 ElementType != T->getElementType() ||
4276 Size.get() != T->getSizeExpr()) {
4277 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4279 T->getAttributeLoc());
4280 if (Result.isNull())
4284 // Result might be dependent or not.
4285 if (isa<DependentSizedExtVectorType>(Result)) {
4286 DependentSizedExtVectorTypeLoc NewTL
4287 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4288 NewTL.setNameLoc(TL.getNameLoc());
4290 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4291 NewTL.setNameLoc(TL.getNameLoc());
4297 template<typename Derived>
4298 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
4300 const VectorType *T = TL.getTypePtr();
4301 QualType ElementType = getDerived().TransformType(T->getElementType());
4302 if (ElementType.isNull())
4305 QualType Result = TL.getType();
4306 if (getDerived().AlwaysRebuild() ||
4307 ElementType != T->getElementType()) {
4308 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
4309 T->getVectorKind());
4310 if (Result.isNull())
4314 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4315 NewTL.setNameLoc(TL.getNameLoc());
4320 template<typename Derived>
4321 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
4322 ExtVectorTypeLoc TL) {
4323 const VectorType *T = TL.getTypePtr();
4324 QualType ElementType = getDerived().TransformType(T->getElementType());
4325 if (ElementType.isNull())
4328 QualType Result = TL.getType();
4329 if (getDerived().AlwaysRebuild() ||
4330 ElementType != T->getElementType()) {
4331 Result = getDerived().RebuildExtVectorType(ElementType,
4332 T->getNumElements(),
4333 /*FIXME*/ SourceLocation());
4334 if (Result.isNull())
4338 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4339 NewTL.setNameLoc(TL.getNameLoc());
4344 template <typename Derived>
4345 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
4346 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
4347 bool ExpectParameterPack) {
4348 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
4349 TypeSourceInfo *NewDI = nullptr;
4351 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
4352 // If we're substituting into a pack expansion type and we know the
4353 // length we want to expand to, just substitute for the pattern.
4354 TypeLoc OldTL = OldDI->getTypeLoc();
4355 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
4358 TypeLoc NewTL = OldDI->getTypeLoc();
4359 TLB.reserve(NewTL.getFullDataSize());
4361 QualType Result = getDerived().TransformType(TLB,
4362 OldExpansionTL.getPatternLoc());
4363 if (Result.isNull())
4366 Result = RebuildPackExpansionType(Result,
4367 OldExpansionTL.getPatternLoc().getSourceRange(),
4368 OldExpansionTL.getEllipsisLoc(),
4370 if (Result.isNull())
4373 PackExpansionTypeLoc NewExpansionTL
4374 = TLB.push<PackExpansionTypeLoc>(Result);
4375 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
4376 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
4378 NewDI = getDerived().TransformType(OldDI);
4382 if (NewDI == OldDI && indexAdjustment == 0)
4385 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
4386 OldParm->getDeclContext(),
4387 OldParm->getInnerLocStart(),
4388 OldParm->getLocation(),
4389 OldParm->getIdentifier(),
4392 OldParm->getStorageClass(),
4393 /* DefArg */ nullptr);
4394 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
4395 OldParm->getFunctionScopeIndex() + indexAdjustment);
4399 template<typename Derived>
4400 bool TreeTransform<Derived>::
4401 TransformFunctionTypeParams(SourceLocation Loc,
4402 ParmVarDecl **Params, unsigned NumParams,
4403 const QualType *ParamTypes,
4404 SmallVectorImpl<QualType> &OutParamTypes,
4405 SmallVectorImpl<ParmVarDecl*> *PVars) {
4406 int indexAdjustment = 0;
4408 for (unsigned i = 0; i != NumParams; ++i) {
4409 if (ParmVarDecl *OldParm = Params[i]) {
4410 assert(OldParm->getFunctionScopeIndex() == i);
4412 Optional<unsigned> NumExpansions;
4413 ParmVarDecl *NewParm = nullptr;
4414 if (OldParm->isParameterPack()) {
4415 // We have a function parameter pack that may need to be expanded.
4416 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4418 // Find the parameter packs that could be expanded.
4419 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
4420 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
4421 TypeLoc Pattern = ExpansionTL.getPatternLoc();
4422 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
4423 assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
4425 // Determine whether we should expand the parameter packs.
4426 bool ShouldExpand = false;
4427 bool RetainExpansion = false;
4428 Optional<unsigned> OrigNumExpansions =
4429 ExpansionTL.getTypePtr()->getNumExpansions();
4430 NumExpansions = OrigNumExpansions;
4431 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
4432 Pattern.getSourceRange(),
4441 // Expand the function parameter pack into multiple, separate
4443 getDerived().ExpandingFunctionParameterPack(OldParm);
4444 for (unsigned I = 0; I != *NumExpansions; ++I) {
4445 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4446 ParmVarDecl *NewParm
4447 = getDerived().TransformFunctionTypeParam(OldParm,
4450 /*ExpectParameterPack=*/false);
4454 OutParamTypes.push_back(NewParm->getType());
4456 PVars->push_back(NewParm);
4459 // If we're supposed to retain a pack expansion, do so by temporarily
4460 // forgetting the partially-substituted parameter pack.
4461 if (RetainExpansion) {
4462 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4463 ParmVarDecl *NewParm
4464 = getDerived().TransformFunctionTypeParam(OldParm,
4467 /*ExpectParameterPack=*/false);
4471 OutParamTypes.push_back(NewParm->getType());
4473 PVars->push_back(NewParm);
4476 // The next parameter should have the same adjustment as the
4477 // last thing we pushed, but we post-incremented indexAdjustment
4478 // on every push. Also, if we push nothing, the adjustment should
4482 // We're done with the pack expansion.
4486 // We'll substitute the parameter now without expanding the pack
4488 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4489 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
4492 /*ExpectParameterPack=*/true);
4494 NewParm = getDerived().TransformFunctionTypeParam(
4495 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
4501 OutParamTypes.push_back(NewParm->getType());
4503 PVars->push_back(NewParm);
4507 // Deal with the possibility that we don't have a parameter
4508 // declaration for this parameter.
4509 QualType OldType = ParamTypes[i];
4510 bool IsPackExpansion = false;
4511 Optional<unsigned> NumExpansions;
4513 if (const PackExpansionType *Expansion
4514 = dyn_cast<PackExpansionType>(OldType)) {
4515 // We have a function parameter pack that may need to be expanded.
4516 QualType Pattern = Expansion->getPattern();
4517 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4518 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4520 // Determine whether we should expand the parameter packs.
4521 bool ShouldExpand = false;
4522 bool RetainExpansion = false;
4523 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
4532 // Expand the function parameter pack into multiple, separate
4534 for (unsigned I = 0; I != *NumExpansions; ++I) {
4535 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4536 QualType NewType = getDerived().TransformType(Pattern);
4537 if (NewType.isNull())
4540 OutParamTypes.push_back(NewType);
4542 PVars->push_back(nullptr);
4545 // We're done with the pack expansion.
4549 // If we're supposed to retain a pack expansion, do so by temporarily
4550 // forgetting the partially-substituted parameter pack.
4551 if (RetainExpansion) {
4552 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4553 QualType NewType = getDerived().TransformType(Pattern);
4554 if (NewType.isNull())
4557 OutParamTypes.push_back(NewType);
4559 PVars->push_back(nullptr);
4562 // We'll substitute the parameter now without expanding the pack
4564 OldType = Expansion->getPattern();
4565 IsPackExpansion = true;
4566 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4567 NewType = getDerived().TransformType(OldType);
4569 NewType = getDerived().TransformType(OldType);
4572 if (NewType.isNull())
4575 if (IsPackExpansion)
4576 NewType = getSema().Context.getPackExpansionType(NewType,
4579 OutParamTypes.push_back(NewType);
4581 PVars->push_back(nullptr);
4586 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
4587 if (ParmVarDecl *parm = (*PVars)[i])
4588 assert(parm->getFunctionScopeIndex() == i);
4595 template<typename Derived>
4597 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
4598 FunctionProtoTypeLoc TL) {
4599 SmallVector<QualType, 4> ExceptionStorage;
4600 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
4601 return getDerived().TransformFunctionProtoType(
4602 TLB, TL, nullptr, 0,
4603 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
4604 return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
4605 ExceptionStorage, Changed);
4609 template<typename Derived> template<typename Fn>
4610 QualType TreeTransform<Derived>::TransformFunctionProtoType(
4611 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
4612 unsigned ThisTypeQuals, Fn TransformExceptionSpec) {
4613 // Transform the parameters and return type.
4615 // We are required to instantiate the params and return type in source order.
4616 // When the function has a trailing return type, we instantiate the
4617 // parameters before the return type, since the return type can then refer
4618 // to the parameters themselves (via decltype, sizeof, etc.).
4620 SmallVector<QualType, 4> ParamTypes;
4621 SmallVector<ParmVarDecl*, 4> ParamDecls;
4622 const FunctionProtoType *T = TL.getTypePtr();
4624 QualType ResultType;
4626 if (T->hasTrailingReturn()) {
4627 if (getDerived().TransformFunctionTypeParams(
4628 TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
4629 TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
4633 // C++11 [expr.prim.general]p3:
4634 // If a declaration declares a member function or member function
4635 // template of a class X, the expression this is a prvalue of type
4636 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4637 // and the end of the function-definition, member-declarator, or
4639 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
4641 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4642 if (ResultType.isNull())
4647 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4648 if (ResultType.isNull())
4651 if (getDerived().TransformFunctionTypeParams(
4652 TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
4653 TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
4657 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
4659 bool EPIChanged = false;
4660 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
4663 // FIXME: Need to transform ConsumedParameters for variadic template
4666 QualType Result = TL.getType();
4667 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
4668 T->getNumParams() != ParamTypes.size() ||
4669 !std::equal(T->param_type_begin(), T->param_type_end(),
4670 ParamTypes.begin()) || EPIChanged) {
4671 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
4672 if (Result.isNull())
4676 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
4677 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4678 NewTL.setLParenLoc(TL.getLParenLoc());
4679 NewTL.setRParenLoc(TL.getRParenLoc());
4680 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4681 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
4682 NewTL.setParam(i, ParamDecls[i]);
4687 template<typename Derived>
4688 bool TreeTransform<Derived>::TransformExceptionSpec(
4689 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
4690 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
4691 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
4693 // Instantiate a dynamic noexcept expression, if any.
4694 if (ESI.Type == EST_ComputedNoexcept) {
4695 EnterExpressionEvaluationContext Unevaluated(getSema(),
4696 Sema::ConstantEvaluated);
4697 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
4698 if (NoexceptExpr.isInvalid())
4701 NoexceptExpr = getSema().CheckBooleanCondition(
4702 NoexceptExpr.get(), NoexceptExpr.get()->getLocStart());
4703 if (NoexceptExpr.isInvalid())
4706 if (!NoexceptExpr.get()->isValueDependent()) {
4707 NoexceptExpr = getSema().VerifyIntegerConstantExpression(
4708 NoexceptExpr.get(), nullptr,
4709 diag::err_noexcept_needs_constant_expression,
4710 /*AllowFold*/false);
4711 if (NoexceptExpr.isInvalid())
4715 if (ESI.NoexceptExpr != NoexceptExpr.get())
4717 ESI.NoexceptExpr = NoexceptExpr.get();
4720 if (ESI.Type != EST_Dynamic)
4723 // Instantiate a dynamic exception specification's type.
4724 for (QualType T : ESI.Exceptions) {
4725 if (const PackExpansionType *PackExpansion =
4726 T->getAs<PackExpansionType>()) {
4729 // We have a pack expansion. Instantiate it.
4730 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4731 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
4733 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4735 // Determine whether the set of unexpanded parameter packs can and
4738 bool Expand = false;
4739 bool RetainExpansion = false;
4740 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
4741 // FIXME: Track the location of the ellipsis (and track source location
4742 // information for the types in the exception specification in general).
4743 if (getDerived().TryExpandParameterPacks(
4744 Loc, SourceRange(), Unexpanded, Expand,
4745 RetainExpansion, NumExpansions))
4749 // We can't expand this pack expansion into separate arguments yet;
4750 // just substitute into the pattern and create a new pack expansion
4752 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4753 QualType U = getDerived().TransformType(PackExpansion->getPattern());
4757 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
4758 Exceptions.push_back(U);
4762 // Substitute into the pack expansion pattern for each slice of the
4764 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
4765 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
4767 QualType U = getDerived().TransformType(PackExpansion->getPattern());
4768 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
4771 Exceptions.push_back(U);
4774 QualType U = getDerived().TransformType(T);
4775 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
4780 Exceptions.push_back(U);
4784 ESI.Exceptions = Exceptions;
4788 template<typename Derived>
4789 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
4790 TypeLocBuilder &TLB,
4791 FunctionNoProtoTypeLoc TL) {
4792 const FunctionNoProtoType *T = TL.getTypePtr();
4793 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
4794 if (ResultType.isNull())
4797 QualType Result = TL.getType();
4798 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
4799 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
4801 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
4802 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4803 NewTL.setLParenLoc(TL.getLParenLoc());
4804 NewTL.setRParenLoc(TL.getRParenLoc());
4805 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4810 template<typename Derived> QualType
4811 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
4812 UnresolvedUsingTypeLoc TL) {
4813 const UnresolvedUsingType *T = TL.getTypePtr();
4814 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
4818 QualType Result = TL.getType();
4819 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
4820 Result = getDerived().RebuildUnresolvedUsingType(D);
4821 if (Result.isNull())
4825 // We might get an arbitrary type spec type back. We should at
4826 // least always get a type spec type, though.
4827 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
4828 NewTL.setNameLoc(TL.getNameLoc());
4833 template<typename Derived>
4834 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
4835 TypedefTypeLoc TL) {
4836 const TypedefType *T = TL.getTypePtr();
4837 TypedefNameDecl *Typedef
4838 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4843 QualType Result = TL.getType();
4844 if (getDerived().AlwaysRebuild() ||
4845 Typedef != T->getDecl()) {
4846 Result = getDerived().RebuildTypedefType(Typedef);
4847 if (Result.isNull())
4851 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
4852 NewTL.setNameLoc(TL.getNameLoc());
4857 template<typename Derived>
4858 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
4859 TypeOfExprTypeLoc TL) {
4860 // typeof expressions are not potentially evaluated contexts
4861 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4862 Sema::ReuseLambdaContextDecl);
4864 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
4868 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
4872 QualType Result = TL.getType();
4873 if (getDerived().AlwaysRebuild() ||
4874 E.get() != TL.getUnderlyingExpr()) {
4875 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
4876 if (Result.isNull())
4881 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
4882 NewTL.setTypeofLoc(TL.getTypeofLoc());
4883 NewTL.setLParenLoc(TL.getLParenLoc());
4884 NewTL.setRParenLoc(TL.getRParenLoc());
4889 template<typename Derived>
4890 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
4892 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
4893 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
4897 QualType Result = TL.getType();
4898 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
4899 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
4900 if (Result.isNull())
4904 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
4905 NewTL.setTypeofLoc(TL.getTypeofLoc());
4906 NewTL.setLParenLoc(TL.getLParenLoc());
4907 NewTL.setRParenLoc(TL.getRParenLoc());
4908 NewTL.setUnderlyingTInfo(New_Under_TI);
4913 template<typename Derived>
4914 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
4915 DecltypeTypeLoc TL) {
4916 const DecltypeType *T = TL.getTypePtr();
4918 // decltype expressions are not potentially evaluated contexts
4919 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4920 nullptr, /*IsDecltype=*/ true);
4922 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
4926 E = getSema().ActOnDecltypeExpression(E.get());
4930 QualType Result = TL.getType();
4931 if (getDerived().AlwaysRebuild() ||
4932 E.get() != T->getUnderlyingExpr()) {
4933 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
4934 if (Result.isNull())
4939 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
4940 NewTL.setNameLoc(TL.getNameLoc());
4945 template<typename Derived>
4946 QualType TreeTransform<Derived>::TransformUnaryTransformType(
4947 TypeLocBuilder &TLB,
4948 UnaryTransformTypeLoc TL) {
4949 QualType Result = TL.getType();
4950 if (Result->isDependentType()) {
4951 const UnaryTransformType *T = TL.getTypePtr();
4953 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
4954 Result = getDerived().RebuildUnaryTransformType(NewBase,
4957 if (Result.isNull())
4961 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
4962 NewTL.setKWLoc(TL.getKWLoc());
4963 NewTL.setParensRange(TL.getParensRange());
4964 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
4968 template<typename Derived>
4969 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
4971 const AutoType *T = TL.getTypePtr();
4972 QualType OldDeduced = T->getDeducedType();
4973 QualType NewDeduced;
4974 if (!OldDeduced.isNull()) {
4975 NewDeduced = getDerived().TransformType(OldDeduced);
4976 if (NewDeduced.isNull())
4980 QualType Result = TL.getType();
4981 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
4982 T->isDependentType()) {
4983 Result = getDerived().RebuildAutoType(NewDeduced, T->isDecltypeAuto());
4984 if (Result.isNull())
4988 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4989 NewTL.setNameLoc(TL.getNameLoc());
4994 template<typename Derived>
4995 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
4997 const RecordType *T = TL.getTypePtr();
4999 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5004 QualType Result = TL.getType();
5005 if (getDerived().AlwaysRebuild() ||
5006 Record != T->getDecl()) {
5007 Result = getDerived().RebuildRecordType(Record);
5008 if (Result.isNull())
5012 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5013 NewTL.setNameLoc(TL.getNameLoc());
5018 template<typename Derived>
5019 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5021 const EnumType *T = TL.getTypePtr();
5023 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5028 QualType Result = TL.getType();
5029 if (getDerived().AlwaysRebuild() ||
5030 Enum != T->getDecl()) {
5031 Result = getDerived().RebuildEnumType(Enum);
5032 if (Result.isNull())
5036 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5037 NewTL.setNameLoc(TL.getNameLoc());
5042 template<typename Derived>
5043 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5044 TypeLocBuilder &TLB,
5045 InjectedClassNameTypeLoc TL) {
5046 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5047 TL.getTypePtr()->getDecl());
5048 if (!D) return QualType();
5050 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5051 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5055 template<typename Derived>
5056 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5057 TypeLocBuilder &TLB,
5058 TemplateTypeParmTypeLoc TL) {
5059 return TransformTypeSpecType(TLB, TL);
5062 template<typename Derived>
5063 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5064 TypeLocBuilder &TLB,
5065 SubstTemplateTypeParmTypeLoc TL) {
5066 const SubstTemplateTypeParmType *T = TL.getTypePtr();
5068 // Substitute into the replacement type, which itself might involve something
5069 // that needs to be transformed. This only tends to occur with default
5070 // template arguments of template template parameters.
5071 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5072 QualType Replacement = getDerived().TransformType(T->getReplacementType());
5073 if (Replacement.isNull())
5076 // Always canonicalize the replacement type.
5077 Replacement = SemaRef.Context.getCanonicalType(Replacement);
5079 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5082 // Propagate type-source information.
5083 SubstTemplateTypeParmTypeLoc NewTL
5084 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5085 NewTL.setNameLoc(TL.getNameLoc());
5090 template<typename Derived>
5091 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5092 TypeLocBuilder &TLB,
5093 SubstTemplateTypeParmPackTypeLoc TL) {
5094 return TransformTypeSpecType(TLB, TL);
5097 template<typename Derived>
5098 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5099 TypeLocBuilder &TLB,
5100 TemplateSpecializationTypeLoc TL) {
5101 const TemplateSpecializationType *T = TL.getTypePtr();
5103 // The nested-name-specifier never matters in a TemplateSpecializationType,
5104 // because we can't have a dependent nested-name-specifier anyway.
5106 TemplateName Template
5107 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5108 TL.getTemplateNameLoc());
5109 if (Template.isNull())
5112 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5115 template<typename Derived>
5116 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5118 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5119 if (ValueType.isNull())
5122 QualType Result = TL.getType();
5123 if (getDerived().AlwaysRebuild() ||
5124 ValueType != TL.getValueLoc().getType()) {
5125 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5126 if (Result.isNull())
5130 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5131 NewTL.setKWLoc(TL.getKWLoc());
5132 NewTL.setLParenLoc(TL.getLParenLoc());
5133 NewTL.setRParenLoc(TL.getRParenLoc());
5138 /// \brief Simple iterator that traverses the template arguments in a
5139 /// container that provides a \c getArgLoc() member function.
5141 /// This iterator is intended to be used with the iterator form of
5142 /// \c TreeTransform<Derived>::TransformTemplateArguments().
5143 template<typename ArgLocContainer>
5144 class TemplateArgumentLocContainerIterator {
5145 ArgLocContainer *Container;
5149 typedef TemplateArgumentLoc value_type;
5150 typedef TemplateArgumentLoc reference;
5151 typedef int difference_type;
5152 typedef std::input_iterator_tag iterator_category;
5155 TemplateArgumentLoc Arg;
5158 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5160 const TemplateArgumentLoc *operator->() const {
5166 TemplateArgumentLocContainerIterator() {}
5168 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5170 : Container(&Container), Index(Index) { }
5172 TemplateArgumentLocContainerIterator &operator++() {
5177 TemplateArgumentLocContainerIterator operator++(int) {
5178 TemplateArgumentLocContainerIterator Old(*this);
5183 TemplateArgumentLoc operator*() const {
5184 return Container->getArgLoc(Index);
5187 pointer operator->() const {
5188 return pointer(Container->getArgLoc(Index));
5191 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5192 const TemplateArgumentLocContainerIterator &Y) {
5193 return X.Container == Y.Container && X.Index == Y.Index;
5196 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
5197 const TemplateArgumentLocContainerIterator &Y) {
5203 template <typename Derived>
5204 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5205 TypeLocBuilder &TLB,
5206 TemplateSpecializationTypeLoc TL,
5207 TemplateName Template) {
5208 TemplateArgumentListInfo NewTemplateArgs;
5209 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5210 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5211 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
5213 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5214 ArgIterator(TL, TL.getNumArgs()),
5218 // FIXME: maybe don't rebuild if all the template arguments are the same.
5221 getDerived().RebuildTemplateSpecializationType(Template,
5222 TL.getTemplateNameLoc(),
5225 if (!Result.isNull()) {
5226 // Specializations of template template parameters are represented as
5227 // TemplateSpecializationTypes, and substitution of type alias templates
5228 // within a dependent context can transform them into
5229 // DependentTemplateSpecializationTypes.
5230 if (isa<DependentTemplateSpecializationType>(Result)) {
5231 DependentTemplateSpecializationTypeLoc NewTL
5232 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5233 NewTL.setElaboratedKeywordLoc(SourceLocation());
5234 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
5235 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5236 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5237 NewTL.setLAngleLoc(TL.getLAngleLoc());
5238 NewTL.setRAngleLoc(TL.getRAngleLoc());
5239 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5240 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5244 TemplateSpecializationTypeLoc NewTL
5245 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5246 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5247 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5248 NewTL.setLAngleLoc(TL.getLAngleLoc());
5249 NewTL.setRAngleLoc(TL.getRAngleLoc());
5250 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5251 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5257 template <typename Derived>
5258 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
5259 TypeLocBuilder &TLB,
5260 DependentTemplateSpecializationTypeLoc TL,
5261 TemplateName Template,
5263 TemplateArgumentListInfo NewTemplateArgs;
5264 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5265 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5266 typedef TemplateArgumentLocContainerIterator<
5267 DependentTemplateSpecializationTypeLoc> ArgIterator;
5268 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5269 ArgIterator(TL, TL.getNumArgs()),
5273 // FIXME: maybe don't rebuild if all the template arguments are the same.
5275 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
5277 = getSema().Context.getDependentTemplateSpecializationType(
5278 TL.getTypePtr()->getKeyword(),
5279 DTN->getQualifier(),
5280 DTN->getIdentifier(),
5283 DependentTemplateSpecializationTypeLoc NewTL
5284 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5285 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5286 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
5287 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5288 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5289 NewTL.setLAngleLoc(TL.getLAngleLoc());
5290 NewTL.setRAngleLoc(TL.getRAngleLoc());
5291 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5292 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5297 = getDerived().RebuildTemplateSpecializationType(Template,
5298 TL.getTemplateNameLoc(),
5301 if (!Result.isNull()) {
5302 /// FIXME: Wrap this in an elaborated-type-specifier?
5303 TemplateSpecializationTypeLoc NewTL
5304 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5305 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5306 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5307 NewTL.setLAngleLoc(TL.getLAngleLoc());
5308 NewTL.setRAngleLoc(TL.getRAngleLoc());
5309 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5310 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5316 template<typename Derived>
5318 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
5319 ElaboratedTypeLoc TL) {
5320 const ElaboratedType *T = TL.getTypePtr();
5322 NestedNameSpecifierLoc QualifierLoc;
5323 // NOTE: the qualifier in an ElaboratedType is optional.
5324 if (TL.getQualifierLoc()) {
5326 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5331 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
5332 if (NamedT.isNull())
5335 // C++0x [dcl.type.elab]p2:
5336 // If the identifier resolves to a typedef-name or the simple-template-id
5337 // resolves to an alias template specialization, the
5338 // elaborated-type-specifier is ill-formed.
5339 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
5340 if (const TemplateSpecializationType *TST =
5341 NamedT->getAs<TemplateSpecializationType>()) {
5342 TemplateName Template = TST->getTemplateName();
5343 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
5344 Template.getAsTemplateDecl())) {
5345 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
5346 diag::err_tag_reference_non_tag) << 4;
5347 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
5352 QualType Result = TL.getType();
5353 if (getDerived().AlwaysRebuild() ||
5354 QualifierLoc != TL.getQualifierLoc() ||
5355 NamedT != T->getNamedType()) {
5356 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
5358 QualifierLoc, NamedT);
5359 if (Result.isNull())
5363 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5364 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5365 NewTL.setQualifierLoc(QualifierLoc);
5369 template<typename Derived>
5370 QualType TreeTransform<Derived>::TransformAttributedType(
5371 TypeLocBuilder &TLB,
5372 AttributedTypeLoc TL) {
5373 const AttributedType *oldType = TL.getTypePtr();
5374 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
5375 if (modifiedType.isNull())
5378 QualType result = TL.getType();
5380 // FIXME: dependent operand expressions?
5381 if (getDerived().AlwaysRebuild() ||
5382 modifiedType != oldType->getModifiedType()) {
5383 // TODO: this is really lame; we should really be rebuilding the
5384 // equivalent type from first principles.
5385 QualType equivalentType
5386 = getDerived().TransformType(oldType->getEquivalentType());
5387 if (equivalentType.isNull())
5390 // Check whether we can add nullability; it is only represented as
5391 // type sugar, and therefore cannot be diagnosed in any other way.
5392 if (auto nullability = oldType->getImmediateNullability()) {
5393 if (!modifiedType->canHaveNullability()) {
5394 SemaRef.Diag(TL.getAttrNameLoc(), diag::err_nullability_nonpointer)
5395 << static_cast<unsigned>(*nullability) << false << modifiedType;
5400 result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
5405 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
5406 newTL.setAttrNameLoc(TL.getAttrNameLoc());
5407 if (TL.hasAttrOperand())
5408 newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5409 if (TL.hasAttrExprOperand())
5410 newTL.setAttrExprOperand(TL.getAttrExprOperand());
5411 else if (TL.hasAttrEnumOperand())
5412 newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
5417 template<typename Derived>
5419 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
5421 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
5425 QualType Result = TL.getType();
5426 if (getDerived().AlwaysRebuild() ||
5427 Inner != TL.getInnerLoc().getType()) {
5428 Result = getDerived().RebuildParenType(Inner);
5429 if (Result.isNull())
5433 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
5434 NewTL.setLParenLoc(TL.getLParenLoc());
5435 NewTL.setRParenLoc(TL.getRParenLoc());
5439 template<typename Derived>
5440 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
5441 DependentNameTypeLoc TL) {
5442 const DependentNameType *T = TL.getTypePtr();
5444 NestedNameSpecifierLoc QualifierLoc
5445 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5450 = getDerived().RebuildDependentNameType(T->getKeyword(),
5451 TL.getElaboratedKeywordLoc(),
5455 if (Result.isNull())
5458 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5459 QualType NamedT = ElabT->getNamedType();
5460 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5462 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5463 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5464 NewTL.setQualifierLoc(QualifierLoc);
5466 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5467 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5468 NewTL.setQualifierLoc(QualifierLoc);
5469 NewTL.setNameLoc(TL.getNameLoc());
5474 template<typename Derived>
5475 QualType TreeTransform<Derived>::
5476 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5477 DependentTemplateSpecializationTypeLoc TL) {
5478 NestedNameSpecifierLoc QualifierLoc;
5479 if (TL.getQualifierLoc()) {
5481 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5487 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
5490 template<typename Derived>
5491 QualType TreeTransform<Derived>::
5492 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5493 DependentTemplateSpecializationTypeLoc TL,
5494 NestedNameSpecifierLoc QualifierLoc) {
5495 const DependentTemplateSpecializationType *T = TL.getTypePtr();
5497 TemplateArgumentListInfo NewTemplateArgs;
5498 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5499 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5501 typedef TemplateArgumentLocContainerIterator<
5502 DependentTemplateSpecializationTypeLoc> ArgIterator;
5503 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5504 ArgIterator(TL, TL.getNumArgs()),
5509 = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
5512 TL.getTemplateNameLoc(),
5514 if (Result.isNull())
5517 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
5518 QualType NamedT = ElabT->getNamedType();
5520 // Copy information relevant to the template specialization.
5521 TemplateSpecializationTypeLoc NamedTL
5522 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5523 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5524 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5525 NamedTL.setLAngleLoc(TL.getLAngleLoc());
5526 NamedTL.setRAngleLoc(TL.getRAngleLoc());
5527 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5528 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5530 // Copy information relevant to the elaborated type.
5531 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5532 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5533 NewTL.setQualifierLoc(QualifierLoc);
5534 } else if (isa<DependentTemplateSpecializationType>(Result)) {
5535 DependentTemplateSpecializationTypeLoc SpecTL
5536 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5537 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5538 SpecTL.setQualifierLoc(QualifierLoc);
5539 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5540 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5541 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5542 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5543 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5544 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5546 TemplateSpecializationTypeLoc SpecTL
5547 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5548 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5549 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5550 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5551 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5552 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5553 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5558 template<typename Derived>
5559 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
5560 PackExpansionTypeLoc TL) {
5562 = getDerived().TransformType(TLB, TL.getPatternLoc());
5563 if (Pattern.isNull())
5566 QualType Result = TL.getType();
5567 if (getDerived().AlwaysRebuild() ||
5568 Pattern != TL.getPatternLoc().getType()) {
5569 Result = getDerived().RebuildPackExpansionType(Pattern,
5570 TL.getPatternLoc().getSourceRange(),
5571 TL.getEllipsisLoc(),
5572 TL.getTypePtr()->getNumExpansions());
5573 if (Result.isNull())
5577 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
5578 NewT.setEllipsisLoc(TL.getEllipsisLoc());
5582 template<typename Derived>
5584 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
5585 ObjCInterfaceTypeLoc TL) {
5586 // ObjCInterfaceType is never dependent.
5587 TLB.pushFullCopy(TL);
5588 return TL.getType();
5591 template<typename Derived>
5593 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
5594 ObjCObjectTypeLoc TL) {
5595 // ObjCObjectType is never dependent.
5596 TLB.pushFullCopy(TL);
5597 return TL.getType();
5600 template<typename Derived>
5602 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
5603 ObjCObjectPointerTypeLoc TL) {
5604 // ObjCObjectPointerType is never dependent.
5605 TLB.pushFullCopy(TL);
5606 return TL.getType();
5609 //===----------------------------------------------------------------------===//
5610 // Statement transformation
5611 //===----------------------------------------------------------------------===//
5612 template<typename Derived>
5614 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
5618 template<typename Derived>
5620 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
5621 return getDerived().TransformCompoundStmt(S, false);
5624 template<typename Derived>
5626 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
5628 Sema::CompoundScopeRAII CompoundScope(getSema());
5630 bool SubStmtInvalid = false;
5631 bool SubStmtChanged = false;
5632 SmallVector<Stmt*, 8> Statements;
5633 for (auto *B : S->body()) {
5634 StmtResult Result = getDerived().TransformStmt(B);
5635 if (Result.isInvalid()) {
5636 // Immediately fail if this was a DeclStmt, since it's very
5637 // likely that this will cause problems for future statements.
5638 if (isa<DeclStmt>(B))
5641 // Otherwise, just keep processing substatements and fail later.
5642 SubStmtInvalid = true;
5646 SubStmtChanged = SubStmtChanged || Result.get() != B;
5647 Statements.push_back(Result.getAs<Stmt>());
5653 if (!getDerived().AlwaysRebuild() &&
5657 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
5663 template<typename Derived>
5665 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
5666 ExprResult LHS, RHS;
5668 EnterExpressionEvaluationContext Unevaluated(SemaRef,
5669 Sema::ConstantEvaluated);
5671 // Transform the left-hand case value.
5672 LHS = getDerived().TransformExpr(S->getLHS());
5673 LHS = SemaRef.ActOnConstantExpression(LHS);
5674 if (LHS.isInvalid())
5677 // Transform the right-hand case value (for the GNU case-range extension).
5678 RHS = getDerived().TransformExpr(S->getRHS());
5679 RHS = SemaRef.ActOnConstantExpression(RHS);
5680 if (RHS.isInvalid())
5684 // Build the case statement.
5685 // Case statements are always rebuilt so that they will attached to their
5686 // transformed switch statement.
5687 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
5689 S->getEllipsisLoc(),
5692 if (Case.isInvalid())
5695 // Transform the statement following the case
5696 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5697 if (SubStmt.isInvalid())
5700 // Attach the body to the case statement
5701 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
5704 template<typename Derived>
5706 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
5707 // Transform the statement following the default case
5708 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5709 if (SubStmt.isInvalid())
5712 // Default statements are always rebuilt
5713 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
5717 template<typename Derived>
5719 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
5720 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5721 if (SubStmt.isInvalid())
5724 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
5730 // FIXME: Pass the real colon location in.
5731 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
5732 cast<LabelDecl>(LD), SourceLocation(),
5736 template <typename Derived>
5737 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
5741 switch (R->getKind()) {
5742 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
5744 #define PRAGMA_SPELLING_ATTR(X) \
5746 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
5747 #include "clang/Basic/AttrList.inc"
5753 template <typename Derived>
5754 StmtResult TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
5755 bool AttrsChanged = false;
5756 SmallVector<const Attr *, 1> Attrs;
5758 // Visit attributes and keep track if any are transformed.
5759 for (const auto *I : S->getAttrs()) {
5760 const Attr *R = getDerived().TransformAttr(I);
5761 AttrsChanged |= (I != R);
5765 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5766 if (SubStmt.isInvalid())
5769 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
5772 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
5776 template<typename Derived>
5778 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
5779 // Transform the condition
5781 VarDecl *ConditionVar = nullptr;
5782 if (S->getConditionVariable()) {
5784 = cast_or_null<VarDecl>(
5785 getDerived().TransformDefinition(
5786 S->getConditionVariable()->getLocation(),
5787 S->getConditionVariable()));
5791 Cond = getDerived().TransformExpr(S->getCond());
5793 if (Cond.isInvalid())
5796 // Convert the condition to a boolean value.
5798 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr, S->getIfLoc(),
5800 if (CondE.isInvalid())
5807 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5808 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5811 // Transform the "then" branch.
5812 StmtResult Then = getDerived().TransformStmt(S->getThen());
5813 if (Then.isInvalid())
5816 // Transform the "else" branch.
5817 StmtResult Else = getDerived().TransformStmt(S->getElse());
5818 if (Else.isInvalid())
5821 if (!getDerived().AlwaysRebuild() &&
5822 FullCond.get() == S->getCond() &&
5823 ConditionVar == S->getConditionVariable() &&
5824 Then.get() == S->getThen() &&
5825 Else.get() == S->getElse())
5828 return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
5830 S->getElseLoc(), Else.get());
5833 template<typename Derived>
5835 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
5836 // Transform the condition.
5838 VarDecl *ConditionVar = nullptr;
5839 if (S->getConditionVariable()) {
5841 = cast_or_null<VarDecl>(
5842 getDerived().TransformDefinition(
5843 S->getConditionVariable()->getLocation(),
5844 S->getConditionVariable()));
5848 Cond = getDerived().TransformExpr(S->getCond());
5850 if (Cond.isInvalid())
5854 // Rebuild the switch statement.
5856 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
5858 if (Switch.isInvalid())
5861 // Transform the body of the switch statement.
5862 StmtResult Body = getDerived().TransformStmt(S->getBody());
5863 if (Body.isInvalid())
5866 // Complete the switch statement.
5867 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
5871 template<typename Derived>
5873 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
5874 // Transform the condition
5876 VarDecl *ConditionVar = nullptr;
5877 if (S->getConditionVariable()) {
5879 = cast_or_null<VarDecl>(
5880 getDerived().TransformDefinition(
5881 S->getConditionVariable()->getLocation(),
5882 S->getConditionVariable()));
5886 Cond = getDerived().TransformExpr(S->getCond());
5888 if (Cond.isInvalid())
5892 // Convert the condition to a boolean value.
5893 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
5896 if (CondE.isInvalid())
5902 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5903 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5906 // Transform the body
5907 StmtResult Body = getDerived().TransformStmt(S->getBody());
5908 if (Body.isInvalid())
5911 if (!getDerived().AlwaysRebuild() &&
5912 FullCond.get() == S->getCond() &&
5913 ConditionVar == S->getConditionVariable() &&
5914 Body.get() == S->getBody())
5917 return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
5918 ConditionVar, Body.get());
5921 template<typename Derived>
5923 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
5924 // Transform the body
5925 StmtResult Body = getDerived().TransformStmt(S->getBody());
5926 if (Body.isInvalid())
5929 // Transform the condition
5930 ExprResult Cond = getDerived().TransformExpr(S->getCond());
5931 if (Cond.isInvalid())
5934 if (!getDerived().AlwaysRebuild() &&
5935 Cond.get() == S->getCond() &&
5936 Body.get() == S->getBody())
5939 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
5940 /*FIXME:*/S->getWhileLoc(), Cond.get(),
5944 template<typename Derived>
5946 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
5947 // Transform the initialization statement
5948 StmtResult Init = getDerived().TransformStmt(S->getInit());
5949 if (Init.isInvalid())
5952 // Transform the condition
5954 VarDecl *ConditionVar = nullptr;
5955 if (S->getConditionVariable()) {
5957 = cast_or_null<VarDecl>(
5958 getDerived().TransformDefinition(
5959 S->getConditionVariable()->getLocation(),
5960 S->getConditionVariable()));
5964 Cond = getDerived().TransformExpr(S->getCond());
5966 if (Cond.isInvalid())
5970 // Convert the condition to a boolean value.
5971 ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
5974 if (CondE.isInvalid())
5981 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
5982 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5985 // Transform the increment
5986 ExprResult Inc = getDerived().TransformExpr(S->getInc());
5987 if (Inc.isInvalid())
5990 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
5991 if (S->getInc() && !FullInc.get())
5994 // Transform the body
5995 StmtResult Body = getDerived().TransformStmt(S->getBody());
5996 if (Body.isInvalid())
5999 if (!getDerived().AlwaysRebuild() &&
6000 Init.get() == S->getInit() &&
6001 FullCond.get() == S->getCond() &&
6002 Inc.get() == S->getInc() &&
6003 Body.get() == S->getBody())
6006 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6007 Init.get(), FullCond, ConditionVar,
6008 FullInc, S->getRParenLoc(), Body.get());
6011 template<typename Derived>
6013 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6014 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6019 // Goto statements must always be rebuilt, to resolve the label.
6020 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
6021 cast<LabelDecl>(LD));
6024 template<typename Derived>
6026 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
6027 ExprResult Target = getDerived().TransformExpr(S->getTarget());
6028 if (Target.isInvalid())
6030 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6032 if (!getDerived().AlwaysRebuild() &&
6033 Target.get() == S->getTarget())
6036 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6040 template<typename Derived>
6042 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6046 template<typename Derived>
6048 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6052 template<typename Derived>
6054 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
6055 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
6056 /*NotCopyInit*/false);
6057 if (Result.isInvalid())
6060 // FIXME: We always rebuild the return statement because there is no way
6061 // to tell whether the return type of the function has changed.
6062 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
6065 template<typename Derived>
6067 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
6068 bool DeclChanged = false;
6069 SmallVector<Decl *, 4> Decls;
6070 for (auto *D : S->decls()) {
6071 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
6075 if (Transformed != D)
6078 Decls.push_back(Transformed);
6081 if (!getDerived().AlwaysRebuild() && !DeclChanged)
6084 return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
6087 template<typename Derived>
6089 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
6091 SmallVector<Expr*, 8> Constraints;
6092 SmallVector<Expr*, 8> Exprs;
6093 SmallVector<IdentifierInfo *, 4> Names;
6095 ExprResult AsmString;
6096 SmallVector<Expr*, 8> Clobbers;
6098 bool ExprsChanged = false;
6100 // Go through the outputs.
6101 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
6102 Names.push_back(S->getOutputIdentifier(I));
6104 // No need to transform the constraint literal.
6105 Constraints.push_back(S->getOutputConstraintLiteral(I));
6107 // Transform the output expr.
6108 Expr *OutputExpr = S->getOutputExpr(I);
6109 ExprResult Result = getDerived().TransformExpr(OutputExpr);
6110 if (Result.isInvalid())
6113 ExprsChanged |= Result.get() != OutputExpr;
6115 Exprs.push_back(Result.get());
6118 // Go through the inputs.
6119 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
6120 Names.push_back(S->getInputIdentifier(I));
6122 // No need to transform the constraint literal.
6123 Constraints.push_back(S->getInputConstraintLiteral(I));
6125 // Transform the input expr.
6126 Expr *InputExpr = S->getInputExpr(I);
6127 ExprResult Result = getDerived().TransformExpr(InputExpr);
6128 if (Result.isInvalid())
6131 ExprsChanged |= Result.get() != InputExpr;
6133 Exprs.push_back(Result.get());
6136 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
6139 // Go through the clobbers.
6140 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
6141 Clobbers.push_back(S->getClobberStringLiteral(I));
6143 // No need to transform the asm string literal.
6144 AsmString = S->getAsmString();
6145 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
6146 S->isVolatile(), S->getNumOutputs(),
6147 S->getNumInputs(), Names.data(),
6148 Constraints, Exprs, AsmString.get(),
6149 Clobbers, S->getRParenLoc());
6152 template<typename Derived>
6154 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
6155 ArrayRef<Token> AsmToks =
6156 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
6158 bool HadError = false, HadChange = false;
6160 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
6161 SmallVector<Expr*, 8> TransformedExprs;
6162 TransformedExprs.reserve(SrcExprs.size());
6163 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
6164 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
6165 if (!Result.isUsable()) {
6168 HadChange |= (Result.get() != SrcExprs[i]);
6169 TransformedExprs.push_back(Result.get());
6173 if (HadError) return StmtError();
6174 if (!HadChange && !getDerived().AlwaysRebuild())
6177 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
6178 AsmToks, S->getAsmString(),
6179 S->getNumOutputs(), S->getNumInputs(),
6180 S->getAllConstraints(), S->getClobbers(),
6181 TransformedExprs, S->getEndLoc());
6184 template<typename Derived>
6186 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
6187 // Transform the body of the @try.
6188 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
6189 if (TryBody.isInvalid())
6192 // Transform the @catch statements (if present).
6193 bool AnyCatchChanged = false;
6194 SmallVector<Stmt*, 8> CatchStmts;
6195 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
6196 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
6197 if (Catch.isInvalid())
6199 if (Catch.get() != S->getCatchStmt(I))
6200 AnyCatchChanged = true;
6201 CatchStmts.push_back(Catch.get());
6204 // Transform the @finally statement (if present).
6206 if (S->getFinallyStmt()) {
6207 Finally = getDerived().TransformStmt(S->getFinallyStmt());
6208 if (Finally.isInvalid())
6212 // If nothing changed, just retain this statement.
6213 if (!getDerived().AlwaysRebuild() &&
6214 TryBody.get() == S->getTryBody() &&
6216 Finally.get() == S->getFinallyStmt())
6219 // Build a new statement.
6220 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
6221 CatchStmts, Finally.get());
6224 template<typename Derived>
6226 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
6227 // Transform the @catch parameter, if there is one.
6228 VarDecl *Var = nullptr;
6229 if (VarDecl *FromVar = S->getCatchParamDecl()) {
6230 TypeSourceInfo *TSInfo = nullptr;
6231 if (FromVar->getTypeSourceInfo()) {
6232 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
6239 T = TSInfo->getType();
6241 T = getDerived().TransformType(FromVar->getType());
6246 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
6251 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
6252 if (Body.isInvalid())
6255 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
6260 template<typename Derived>
6262 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
6263 // Transform the body.
6264 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
6265 if (Body.isInvalid())
6268 // If nothing changed, just retain this statement.
6269 if (!getDerived().AlwaysRebuild() &&
6270 Body.get() == S->getFinallyBody())
6273 // Build a new statement.
6274 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
6278 template<typename Derived>
6280 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
6282 if (S->getThrowExpr()) {
6283 Operand = getDerived().TransformExpr(S->getThrowExpr());
6284 if (Operand.isInvalid())
6288 if (!getDerived().AlwaysRebuild() &&
6289 Operand.get() == S->getThrowExpr())
6292 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
6295 template<typename Derived>
6297 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
6298 ObjCAtSynchronizedStmt *S) {
6299 // Transform the object we are locking.
6300 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
6301 if (Object.isInvalid())
6304 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
6306 if (Object.isInvalid())
6309 // Transform the body.
6310 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
6311 if (Body.isInvalid())
6314 // If nothing change, just retain the current statement.
6315 if (!getDerived().AlwaysRebuild() &&
6316 Object.get() == S->getSynchExpr() &&
6317 Body.get() == S->getSynchBody())
6320 // Build a new statement.
6321 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
6322 Object.get(), Body.get());
6325 template<typename Derived>
6327 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
6328 ObjCAutoreleasePoolStmt *S) {
6329 // Transform the body.
6330 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
6331 if (Body.isInvalid())
6334 // If nothing changed, just retain this statement.
6335 if (!getDerived().AlwaysRebuild() &&
6336 Body.get() == S->getSubStmt())
6339 // Build a new statement.
6340 return getDerived().RebuildObjCAutoreleasePoolStmt(
6341 S->getAtLoc(), Body.get());
6344 template<typename Derived>
6346 TreeTransform<Derived>::TransformObjCForCollectionStmt(
6347 ObjCForCollectionStmt *S) {
6348 // Transform the element statement.
6349 StmtResult Element = getDerived().TransformStmt(S->getElement());
6350 if (Element.isInvalid())
6353 // Transform the collection expression.
6354 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
6355 if (Collection.isInvalid())
6358 // Transform the body.
6359 StmtResult Body = getDerived().TransformStmt(S->getBody());
6360 if (Body.isInvalid())
6363 // If nothing changed, just retain this statement.
6364 if (!getDerived().AlwaysRebuild() &&
6365 Element.get() == S->getElement() &&
6366 Collection.get() == S->getCollection() &&
6367 Body.get() == S->getBody())
6370 // Build a new statement.
6371 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
6378 template <typename Derived>
6379 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
6380 // Transform the exception declaration, if any.
6381 VarDecl *Var = nullptr;
6382 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
6384 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
6388 Var = getDerived().RebuildExceptionDecl(
6389 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
6390 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
6391 if (!Var || Var->isInvalidDecl())
6395 // Transform the actual exception handler.
6396 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
6397 if (Handler.isInvalid())
6400 if (!getDerived().AlwaysRebuild() && !Var &&
6401 Handler.get() == S->getHandlerBlock())
6404 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
6407 template <typename Derived>
6408 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
6409 // Transform the try block itself.
6410 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
6411 if (TryBlock.isInvalid())
6414 // Transform the handlers.
6415 bool HandlerChanged = false;
6416 SmallVector<Stmt *, 8> Handlers;
6417 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
6418 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
6419 if (Handler.isInvalid())
6422 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
6423 Handlers.push_back(Handler.getAs<Stmt>());
6426 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
6430 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
6434 template<typename Derived>
6436 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
6437 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
6438 if (Range.isInvalid())
6441 StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
6442 if (BeginEnd.isInvalid())
6445 ExprResult Cond = getDerived().TransformExpr(S->getCond());
6446 if (Cond.isInvalid())
6449 Cond = SemaRef.CheckBooleanCondition(Cond.get(), S->getColonLoc());
6450 if (Cond.isInvalid())
6453 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
6455 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6456 if (Inc.isInvalid())
6459 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
6461 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
6462 if (LoopVar.isInvalid())
6465 StmtResult NewStmt = S;
6466 if (getDerived().AlwaysRebuild() ||
6467 Range.get() != S->getRangeStmt() ||
6468 BeginEnd.get() != S->getBeginEndStmt() ||
6469 Cond.get() != S->getCond() ||
6470 Inc.get() != S->getInc() ||
6471 LoopVar.get() != S->getLoopVarStmt()) {
6472 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6473 S->getColonLoc(), Range.get(),
6474 BeginEnd.get(), Cond.get(),
6475 Inc.get(), LoopVar.get(),
6477 if (NewStmt.isInvalid())
6481 StmtResult Body = getDerived().TransformStmt(S->getBody());
6482 if (Body.isInvalid())
6485 // Body has changed but we didn't rebuild the for-range statement. Rebuild
6486 // it now so we have a new statement to attach the body to.
6487 if (Body.get() != S->getBody() && NewStmt.get() == S) {
6488 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6489 S->getColonLoc(), Range.get(),
6490 BeginEnd.get(), Cond.get(),
6491 Inc.get(), LoopVar.get(),
6493 if (NewStmt.isInvalid())
6497 if (NewStmt.get() == S)
6500 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
6503 template<typename Derived>
6505 TreeTransform<Derived>::TransformMSDependentExistsStmt(
6506 MSDependentExistsStmt *S) {
6507 // Transform the nested-name-specifier, if any.
6508 NestedNameSpecifierLoc QualifierLoc;
6509 if (S->getQualifierLoc()) {
6511 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
6516 // Transform the declaration name.
6517 DeclarationNameInfo NameInfo = S->getNameInfo();
6518 if (NameInfo.getName()) {
6519 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
6520 if (!NameInfo.getName())
6524 // Check whether anything changed.
6525 if (!getDerived().AlwaysRebuild() &&
6526 QualifierLoc == S->getQualifierLoc() &&
6527 NameInfo.getName() == S->getNameInfo().getName())
6530 // Determine whether this name exists, if we can.
6532 SS.Adopt(QualifierLoc);
6533 bool Dependent = false;
6534 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
6535 case Sema::IER_Exists:
6536 if (S->isIfExists())
6539 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6541 case Sema::IER_DoesNotExist:
6542 if (S->isIfNotExists())
6545 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6547 case Sema::IER_Dependent:
6551 case Sema::IER_Error:
6555 // We need to continue with the instantiation, so do so now.
6556 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
6557 if (SubStmt.isInvalid())
6560 // If we have resolved the name, just transform to the substatement.
6564 // The name is still dependent, so build a dependent expression again.
6565 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
6572 template<typename Derived>
6574 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
6575 NestedNameSpecifierLoc QualifierLoc;
6576 if (E->getQualifierLoc()) {
6578 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6583 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
6584 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
6588 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
6589 if (Base.isInvalid())
6592 return new (SemaRef.getASTContext())
6593 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
6594 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
6595 QualifierLoc, E->getMemberLoc());
6598 template <typename Derived>
6599 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
6600 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
6601 if (TryBlock.isInvalid())
6604 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
6605 if (Handler.isInvalid())
6608 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
6609 Handler.get() == S->getHandler())
6612 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
6613 TryBlock.get(), Handler.get());
6616 template <typename Derived>
6617 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
6618 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
6619 if (Block.isInvalid())
6622 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
6625 template <typename Derived>
6626 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
6627 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
6628 if (FilterExpr.isInvalid())
6631 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
6632 if (Block.isInvalid())
6635 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
6639 template <typename Derived>
6640 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
6641 if (isa<SEHFinallyStmt>(Handler))
6642 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
6644 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
6647 template<typename Derived>
6649 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
6653 //===----------------------------------------------------------------------===//
6654 // OpenMP directive transformation
6655 //===----------------------------------------------------------------------===//
6656 template <typename Derived>
6657 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
6658 OMPExecutableDirective *D) {
6660 // Transform the clauses
6661 llvm::SmallVector<OMPClause *, 16> TClauses;
6662 ArrayRef<OMPClause *> Clauses = D->clauses();
6663 TClauses.reserve(Clauses.size());
6664 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
6667 OMPClause *Clause = getDerived().TransformOMPClause(*I);
6669 TClauses.push_back(Clause);
6671 TClauses.push_back(nullptr);
6674 StmtResult AssociatedStmt;
6675 if (D->hasAssociatedStmt()) {
6676 if (!D->getAssociatedStmt()) {
6679 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
6680 /*CurScope=*/nullptr);
6683 Sema::CompoundScopeRAII CompoundScope(getSema());
6684 Body = getDerived().TransformStmt(
6685 cast<CapturedStmt>(D->getAssociatedStmt())->getCapturedStmt());
6688 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
6689 if (AssociatedStmt.isInvalid()) {
6693 if (TClauses.size() != Clauses.size()) {
6697 // Transform directive name for 'omp critical' directive.
6698 DeclarationNameInfo DirName;
6699 if (D->getDirectiveKind() == OMPD_critical) {
6700 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
6701 DirName = getDerived().TransformDeclarationNameInfo(DirName);
6704 return getDerived().RebuildOMPExecutableDirective(
6705 D->getDirectiveKind(), DirName, TClauses, AssociatedStmt.get(),
6706 D->getLocStart(), D->getLocEnd());
6709 template <typename Derived>
6711 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
6712 DeclarationNameInfo DirName;
6713 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
6715 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6716 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6720 template <typename Derived>
6722 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
6723 DeclarationNameInfo DirName;
6724 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
6726 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6727 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6731 template <typename Derived>
6733 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
6734 DeclarationNameInfo DirName;
6735 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
6737 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6738 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6742 template <typename Derived>
6744 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
6745 DeclarationNameInfo DirName;
6746 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
6748 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6749 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6753 template <typename Derived>
6755 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
6756 DeclarationNameInfo DirName;
6757 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
6759 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6760 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6764 template <typename Derived>
6766 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
6767 DeclarationNameInfo DirName;
6768 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
6770 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6771 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6775 template <typename Derived>
6777 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
6778 DeclarationNameInfo DirName;
6779 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
6781 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6782 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6786 template <typename Derived>
6788 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
6789 DeclarationNameInfo DirName;
6790 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
6792 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6793 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6797 template <typename Derived>
6799 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
6800 getDerived().getSema().StartOpenMPDSABlock(
6801 OMPD_critical, D->getDirectiveName(), nullptr, D->getLocStart());
6802 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6803 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6807 template <typename Derived>
6808 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
6809 OMPParallelForDirective *D) {
6810 DeclarationNameInfo DirName;
6811 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
6812 nullptr, D->getLocStart());
6813 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6814 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6818 template <typename Derived>
6819 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
6820 OMPParallelForSimdDirective *D) {
6821 DeclarationNameInfo DirName;
6822 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
6823 nullptr, D->getLocStart());
6824 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6825 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6829 template <typename Derived>
6830 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
6831 OMPParallelSectionsDirective *D) {
6832 DeclarationNameInfo DirName;
6833 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
6834 nullptr, D->getLocStart());
6835 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6836 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6840 template <typename Derived>
6842 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
6843 DeclarationNameInfo DirName;
6844 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
6846 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6847 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6851 template <typename Derived>
6852 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
6853 OMPTaskyieldDirective *D) {
6854 DeclarationNameInfo DirName;
6855 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
6857 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6858 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6862 template <typename Derived>
6864 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
6865 DeclarationNameInfo DirName;
6866 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
6868 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6869 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6873 template <typename Derived>
6875 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
6876 DeclarationNameInfo DirName;
6877 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
6879 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6880 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6884 template <typename Derived>
6885 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
6886 OMPTaskgroupDirective *D) {
6887 DeclarationNameInfo DirName;
6888 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
6890 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6891 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6895 template <typename Derived>
6897 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
6898 DeclarationNameInfo DirName;
6899 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
6901 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6902 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6906 template <typename Derived>
6908 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
6909 DeclarationNameInfo DirName;
6910 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
6912 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6913 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6917 template <typename Derived>
6919 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
6920 DeclarationNameInfo DirName;
6921 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
6923 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6924 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6928 template <typename Derived>
6930 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
6931 DeclarationNameInfo DirName;
6932 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
6934 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6935 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6939 template <typename Derived>
6941 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
6942 DeclarationNameInfo DirName;
6943 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
6945 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
6946 getDerived().getSema().EndOpenMPDSABlock(Res.get());
6950 //===----------------------------------------------------------------------===//
6951 // OpenMP clause transformation
6952 //===----------------------------------------------------------------------===//
6953 template <typename Derived>
6954 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
6955 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
6956 if (Cond.isInvalid())
6958 return getDerived().RebuildOMPIfClause(Cond.get(), C->getLocStart(),
6959 C->getLParenLoc(), C->getLocEnd());
6962 template <typename Derived>
6963 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
6964 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
6965 if (Cond.isInvalid())
6967 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getLocStart(),
6968 C->getLParenLoc(), C->getLocEnd());
6971 template <typename Derived>
6973 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
6974 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
6975 if (NumThreads.isInvalid())
6977 return getDerived().RebuildOMPNumThreadsClause(
6978 NumThreads.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
6981 template <typename Derived>
6983 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
6984 ExprResult E = getDerived().TransformExpr(C->getSafelen());
6987 return getDerived().RebuildOMPSafelenClause(
6988 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
6991 template <typename Derived>
6993 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
6994 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
6997 return getDerived().RebuildOMPCollapseClause(
6998 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7001 template <typename Derived>
7003 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
7004 return getDerived().RebuildOMPDefaultClause(
7005 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getLocStart(),
7006 C->getLParenLoc(), C->getLocEnd());
7009 template <typename Derived>
7011 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
7012 return getDerived().RebuildOMPProcBindClause(
7013 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getLocStart(),
7014 C->getLParenLoc(), C->getLocEnd());
7017 template <typename Derived>
7019 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
7020 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
7023 return getDerived().RebuildOMPScheduleClause(
7024 C->getScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
7025 C->getScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
7028 template <typename Derived>
7030 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
7031 // No need to rebuild this clause, no template-dependent parameters.
7035 template <typename Derived>
7037 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
7038 // No need to rebuild this clause, no template-dependent parameters.
7042 template <typename Derived>
7044 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
7045 // No need to rebuild this clause, no template-dependent parameters.
7049 template <typename Derived>
7051 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
7052 // No need to rebuild this clause, no template-dependent parameters.
7056 template <typename Derived>
7057 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
7058 // No need to rebuild this clause, no template-dependent parameters.
7062 template <typename Derived>
7063 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
7064 // No need to rebuild this clause, no template-dependent parameters.
7068 template <typename Derived>
7070 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
7071 // No need to rebuild this clause, no template-dependent parameters.
7075 template <typename Derived>
7077 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
7078 // No need to rebuild this clause, no template-dependent parameters.
7082 template <typename Derived>
7084 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
7085 // No need to rebuild this clause, no template-dependent parameters.
7089 template <typename Derived>
7091 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
7092 llvm::SmallVector<Expr *, 16> Vars;
7093 Vars.reserve(C->varlist_size());
7094 for (auto *VE : C->varlists()) {
7095 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7096 if (EVar.isInvalid())
7098 Vars.push_back(EVar.get());
7100 return getDerived().RebuildOMPPrivateClause(
7101 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7104 template <typename Derived>
7105 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
7106 OMPFirstprivateClause *C) {
7107 llvm::SmallVector<Expr *, 16> Vars;
7108 Vars.reserve(C->varlist_size());
7109 for (auto *VE : C->varlists()) {
7110 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7111 if (EVar.isInvalid())
7113 Vars.push_back(EVar.get());
7115 return getDerived().RebuildOMPFirstprivateClause(
7116 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7119 template <typename Derived>
7121 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
7122 llvm::SmallVector<Expr *, 16> Vars;
7123 Vars.reserve(C->varlist_size());
7124 for (auto *VE : C->varlists()) {
7125 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7126 if (EVar.isInvalid())
7128 Vars.push_back(EVar.get());
7130 return getDerived().RebuildOMPLastprivateClause(
7131 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7134 template <typename Derived>
7136 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
7137 llvm::SmallVector<Expr *, 16> Vars;
7138 Vars.reserve(C->varlist_size());
7139 for (auto *VE : C->varlists()) {
7140 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7141 if (EVar.isInvalid())
7143 Vars.push_back(EVar.get());
7145 return getDerived().RebuildOMPSharedClause(Vars, C->getLocStart(),
7146 C->getLParenLoc(), C->getLocEnd());
7149 template <typename Derived>
7151 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
7152 llvm::SmallVector<Expr *, 16> Vars;
7153 Vars.reserve(C->varlist_size());
7154 for (auto *VE : C->varlists()) {
7155 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7156 if (EVar.isInvalid())
7158 Vars.push_back(EVar.get());
7160 CXXScopeSpec ReductionIdScopeSpec;
7161 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
7163 DeclarationNameInfo NameInfo = C->getNameInfo();
7164 if (NameInfo.getName()) {
7165 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7166 if (!NameInfo.getName())
7169 return getDerived().RebuildOMPReductionClause(
7170 Vars, C->getLocStart(), C->getLParenLoc(), C->getColonLoc(),
7171 C->getLocEnd(), ReductionIdScopeSpec, NameInfo);
7174 template <typename Derived>
7176 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
7177 llvm::SmallVector<Expr *, 16> Vars;
7178 Vars.reserve(C->varlist_size());
7179 for (auto *VE : C->varlists()) {
7180 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7181 if (EVar.isInvalid())
7183 Vars.push_back(EVar.get());
7185 ExprResult Step = getDerived().TransformExpr(C->getStep());
7186 if (Step.isInvalid())
7188 return getDerived().RebuildOMPLinearClause(Vars, Step.get(), C->getLocStart(),
7190 C->getColonLoc(), C->getLocEnd());
7193 template <typename Derived>
7195 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
7196 llvm::SmallVector<Expr *, 16> Vars;
7197 Vars.reserve(C->varlist_size());
7198 for (auto *VE : C->varlists()) {
7199 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7200 if (EVar.isInvalid())
7202 Vars.push_back(EVar.get());
7204 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
7205 if (Alignment.isInvalid())
7207 return getDerived().RebuildOMPAlignedClause(
7208 Vars, Alignment.get(), C->getLocStart(), C->getLParenLoc(),
7209 C->getColonLoc(), C->getLocEnd());
7212 template <typename Derived>
7214 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
7215 llvm::SmallVector<Expr *, 16> Vars;
7216 Vars.reserve(C->varlist_size());
7217 for (auto *VE : C->varlists()) {
7218 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7219 if (EVar.isInvalid())
7221 Vars.push_back(EVar.get());
7223 return getDerived().RebuildOMPCopyinClause(Vars, C->getLocStart(),
7224 C->getLParenLoc(), C->getLocEnd());
7227 template <typename Derived>
7229 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
7230 llvm::SmallVector<Expr *, 16> Vars;
7231 Vars.reserve(C->varlist_size());
7232 for (auto *VE : C->varlists()) {
7233 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7234 if (EVar.isInvalid())
7236 Vars.push_back(EVar.get());
7238 return getDerived().RebuildOMPCopyprivateClause(
7239 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
7242 template <typename Derived>
7243 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
7244 llvm::SmallVector<Expr *, 16> Vars;
7245 Vars.reserve(C->varlist_size());
7246 for (auto *VE : C->varlists()) {
7247 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
7248 if (EVar.isInvalid())
7250 Vars.push_back(EVar.get());
7252 return getDerived().RebuildOMPFlushClause(Vars, C->getLocStart(),
7253 C->getLParenLoc(), C->getLocEnd());
7256 //===----------------------------------------------------------------------===//
7257 // Expression transformation
7258 //===----------------------------------------------------------------------===//
7259 template<typename Derived>
7261 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
7262 if (!E->isTypeDependent())
7265 return getDerived().RebuildPredefinedExpr(E->getLocation(),
7269 template<typename Derived>
7271 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
7272 NestedNameSpecifierLoc QualifierLoc;
7273 if (E->getQualifierLoc()) {
7275 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7281 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
7286 DeclarationNameInfo NameInfo = E->getNameInfo();
7287 if (NameInfo.getName()) {
7288 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7289 if (!NameInfo.getName())
7293 if (!getDerived().AlwaysRebuild() &&
7294 QualifierLoc == E->getQualifierLoc() &&
7295 ND == E->getDecl() &&
7296 NameInfo.getName() == E->getDecl()->getDeclName() &&
7297 !E->hasExplicitTemplateArgs()) {
7299 // Mark it referenced in the new context regardless.
7300 // FIXME: this is a bit instantiation-specific.
7301 SemaRef.MarkDeclRefReferenced(E);
7306 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
7307 if (E->hasExplicitTemplateArgs()) {
7308 TemplateArgs = &TransArgs;
7309 TransArgs.setLAngleLoc(E->getLAngleLoc());
7310 TransArgs.setRAngleLoc(E->getRAngleLoc());
7311 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7312 E->getNumTemplateArgs(),
7317 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
7321 template<typename Derived>
7323 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
7327 template<typename Derived>
7329 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
7333 template<typename Derived>
7335 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
7339 template<typename Derived>
7341 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
7345 template<typename Derived>
7347 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
7351 template<typename Derived>
7353 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
7354 if (FunctionDecl *FD = E->getDirectCallee())
7355 SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
7356 return SemaRef.MaybeBindToTemporary(E);
7359 template<typename Derived>
7361 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
7362 ExprResult ControllingExpr =
7363 getDerived().TransformExpr(E->getControllingExpr());
7364 if (ControllingExpr.isInvalid())
7367 SmallVector<Expr *, 4> AssocExprs;
7368 SmallVector<TypeSourceInfo *, 4> AssocTypes;
7369 for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
7370 TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
7372 TypeSourceInfo *AssocType = getDerived().TransformType(TS);
7375 AssocTypes.push_back(AssocType);
7377 AssocTypes.push_back(nullptr);
7380 ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
7381 if (AssocExpr.isInvalid())
7383 AssocExprs.push_back(AssocExpr.get());
7386 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
7389 ControllingExpr.get(),
7394 template<typename Derived>
7396 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
7397 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
7398 if (SubExpr.isInvalid())
7401 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
7404 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
7408 /// \brief The operand of a unary address-of operator has special rules: it's
7409 /// allowed to refer to a non-static member of a class even if there's no 'this'
7410 /// object available.
7411 template<typename Derived>
7413 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
7414 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
7415 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
7417 return getDerived().TransformExpr(E);
7420 template<typename Derived>
7422 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
7424 if (E->getOpcode() == UO_AddrOf)
7425 SubExpr = TransformAddressOfOperand(E->getSubExpr());
7427 SubExpr = TransformExpr(E->getSubExpr());
7428 if (SubExpr.isInvalid())
7431 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
7434 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
7439 template<typename Derived>
7441 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
7442 // Transform the type.
7443 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
7447 // Transform all of the components into components similar to what the
7449 // FIXME: It would be slightly more efficient in the non-dependent case to
7450 // just map FieldDecls, rather than requiring the rebuilder to look for
7451 // the fields again. However, __builtin_offsetof is rare enough in
7452 // template code that we don't care.
7453 bool ExprChanged = false;
7454 typedef Sema::OffsetOfComponent Component;
7455 typedef OffsetOfExpr::OffsetOfNode Node;
7456 SmallVector<Component, 4> Components;
7457 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
7458 const Node &ON = E->getComponent(I);
7460 Comp.isBrackets = true;
7461 Comp.LocStart = ON.getSourceRange().getBegin();
7462 Comp.LocEnd = ON.getSourceRange().getEnd();
7463 switch (ON.getKind()) {
7465 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
7466 ExprResult Index = getDerived().TransformExpr(FromIndex);
7467 if (Index.isInvalid())
7470 ExprChanged = ExprChanged || Index.get() != FromIndex;
7471 Comp.isBrackets = true;
7472 Comp.U.E = Index.get();
7477 case Node::Identifier:
7478 Comp.isBrackets = false;
7479 Comp.U.IdentInfo = ON.getFieldName();
7480 if (!Comp.U.IdentInfo)
7486 // Will be recomputed during the rebuild.
7490 Components.push_back(Comp);
7493 // If nothing changed, retain the existing expression.
7494 if (!getDerived().AlwaysRebuild() &&
7495 Type == E->getTypeSourceInfo() &&
7499 // Build a new offsetof expression.
7500 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
7501 Components.data(), Components.size(),
7505 template<typename Derived>
7507 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
7508 assert(getDerived().AlreadyTransformed(E->getType()) &&
7509 "opaque value expression requires transformation");
7513 template<typename Derived>
7515 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
7519 template<typename Derived>
7521 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
7522 // Rebuild the syntactic form. The original syntactic form has
7523 // opaque-value expressions in it, so strip those away and rebuild
7524 // the result. This is a really awful way of doing this, but the
7525 // better solution (rebuilding the semantic expressions and
7526 // rebinding OVEs as necessary) doesn't work; we'd need
7527 // TreeTransform to not strip away implicit conversions.
7528 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
7529 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
7530 if (result.isInvalid()) return ExprError();
7532 // If that gives us a pseudo-object result back, the pseudo-object
7533 // expression must have been an lvalue-to-rvalue conversion which we
7535 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
7536 result = SemaRef.checkPseudoObjectRValue(result.get());
7541 template<typename Derived>
7543 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
7544 UnaryExprOrTypeTraitExpr *E) {
7545 if (E->isArgumentType()) {
7546 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
7548 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
7552 if (!getDerived().AlwaysRebuild() && OldT == NewT)
7555 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
7557 E->getSourceRange());
7560 // C++0x [expr.sizeof]p1:
7561 // The operand is either an expression, which is an unevaluated operand
7563 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
7564 Sema::ReuseLambdaContextDecl);
7566 // Try to recover if we have something like sizeof(T::X) where X is a type.
7567 // Notably, there must be *exactly* one set of parens if X is a type.
7568 TypeSourceInfo *RecoveryTSI = nullptr;
7570 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
7572 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
7573 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
7574 PE, DRE, false, &RecoveryTSI);
7576 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
7579 return getDerived().RebuildUnaryExprOrTypeTrait(
7580 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
7581 } else if (SubExpr.isInvalid())
7584 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
7587 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
7588 E->getOperatorLoc(),
7590 E->getSourceRange());
7593 template<typename Derived>
7595 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
7596 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7597 if (LHS.isInvalid())
7600 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7601 if (RHS.isInvalid())
7605 if (!getDerived().AlwaysRebuild() &&
7606 LHS.get() == E->getLHS() &&
7607 RHS.get() == E->getRHS())
7610 return getDerived().RebuildArraySubscriptExpr(LHS.get(),
7611 /*FIXME:*/E->getLHS()->getLocStart(),
7613 E->getRBracketLoc());
7616 template<typename Derived>
7618 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
7619 // Transform the callee.
7620 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
7621 if (Callee.isInvalid())
7624 // Transform arguments.
7625 bool ArgChanged = false;
7626 SmallVector<Expr*, 8> Args;
7627 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
7631 if (!getDerived().AlwaysRebuild() &&
7632 Callee.get() == E->getCallee() &&
7634 return SemaRef.MaybeBindToTemporary(E);
7636 // FIXME: Wrong source location information for the '('.
7637 SourceLocation FakeLParenLoc
7638 = ((Expr *)Callee.get())->getSourceRange().getBegin();
7639 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
7644 template<typename Derived>
7646 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
7647 ExprResult Base = getDerived().TransformExpr(E->getBase());
7648 if (Base.isInvalid())
7651 NestedNameSpecifierLoc QualifierLoc;
7652 if (E->hasQualifier()) {
7654 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7659 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
7662 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
7663 E->getMemberDecl()));
7667 NamedDecl *FoundDecl = E->getFoundDecl();
7668 if (FoundDecl == E->getMemberDecl()) {
7671 FoundDecl = cast_or_null<NamedDecl>(
7672 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
7677 if (!getDerived().AlwaysRebuild() &&
7678 Base.get() == E->getBase() &&
7679 QualifierLoc == E->getQualifierLoc() &&
7680 Member == E->getMemberDecl() &&
7681 FoundDecl == E->getFoundDecl() &&
7682 !E->hasExplicitTemplateArgs()) {
7684 // Mark it referenced in the new context regardless.
7685 // FIXME: this is a bit instantiation-specific.
7686 SemaRef.MarkMemberReferenced(E);
7691 TemplateArgumentListInfo TransArgs;
7692 if (E->hasExplicitTemplateArgs()) {
7693 TransArgs.setLAngleLoc(E->getLAngleLoc());
7694 TransArgs.setRAngleLoc(E->getRAngleLoc());
7695 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7696 E->getNumTemplateArgs(),
7701 // FIXME: Bogus source location for the operator
7702 SourceLocation FakeOperatorLoc =
7703 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
7705 // FIXME: to do this check properly, we will need to preserve the
7706 // first-qualifier-in-scope here, just in case we had a dependent
7707 // base (and therefore couldn't do the check) and a
7708 // nested-name-qualifier (and therefore could do the lookup).
7709 NamedDecl *FirstQualifierInScope = nullptr;
7711 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
7715 E->getMemberNameInfo(),
7718 (E->hasExplicitTemplateArgs()
7719 ? &TransArgs : nullptr),
7720 FirstQualifierInScope);
7723 template<typename Derived>
7725 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
7726 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7727 if (LHS.isInvalid())
7730 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7731 if (RHS.isInvalid())
7734 if (!getDerived().AlwaysRebuild() &&
7735 LHS.get() == E->getLHS() &&
7736 RHS.get() == E->getRHS())
7739 Sema::FPContractStateRAII FPContractState(getSema());
7740 getSema().FPFeatures.fp_contract = E->isFPContractable();
7742 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
7743 LHS.get(), RHS.get());
7746 template<typename Derived>
7748 TreeTransform<Derived>::TransformCompoundAssignOperator(
7749 CompoundAssignOperator *E) {
7750 return getDerived().TransformBinaryOperator(E);
7753 template<typename Derived>
7754 ExprResult TreeTransform<Derived>::
7755 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
7756 // Just rebuild the common and RHS expressions and see whether we
7759 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
7760 if (commonExpr.isInvalid())
7763 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
7764 if (rhs.isInvalid())
7767 if (!getDerived().AlwaysRebuild() &&
7768 commonExpr.get() == e->getCommon() &&
7769 rhs.get() == e->getFalseExpr())
7772 return getDerived().RebuildConditionalOperator(commonExpr.get(),
7773 e->getQuestionLoc(),
7779 template<typename Derived>
7781 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
7782 ExprResult Cond = getDerived().TransformExpr(E->getCond());
7783 if (Cond.isInvalid())
7786 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
7787 if (LHS.isInvalid())
7790 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
7791 if (RHS.isInvalid())
7794 if (!getDerived().AlwaysRebuild() &&
7795 Cond.get() == E->getCond() &&
7796 LHS.get() == E->getLHS() &&
7797 RHS.get() == E->getRHS())
7800 return getDerived().RebuildConditionalOperator(Cond.get(),
7801 E->getQuestionLoc(),
7807 template<typename Derived>
7809 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
7810 // Implicit casts are eliminated during transformation, since they
7811 // will be recomputed by semantic analysis after transformation.
7812 return getDerived().TransformExpr(E->getSubExprAsWritten());
7815 template<typename Derived>
7817 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
7818 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
7823 = getDerived().TransformExpr(E->getSubExprAsWritten());
7824 if (SubExpr.isInvalid())
7827 if (!getDerived().AlwaysRebuild() &&
7828 Type == E->getTypeInfoAsWritten() &&
7829 SubExpr.get() == E->getSubExpr())
7832 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
7838 template<typename Derived>
7840 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
7841 TypeSourceInfo *OldT = E->getTypeSourceInfo();
7842 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
7846 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
7847 if (Init.isInvalid())
7850 if (!getDerived().AlwaysRebuild() &&
7852 Init.get() == E->getInitializer())
7853 return SemaRef.MaybeBindToTemporary(E);
7855 // Note: the expression type doesn't necessarily match the
7856 // type-as-written, but that's okay, because it should always be
7857 // derivable from the initializer.
7859 return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
7860 /*FIXME:*/E->getInitializer()->getLocEnd(),
7864 template<typename Derived>
7866 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
7867 ExprResult Base = getDerived().TransformExpr(E->getBase());
7868 if (Base.isInvalid())
7871 if (!getDerived().AlwaysRebuild() &&
7872 Base.get() == E->getBase())
7875 // FIXME: Bad source location
7876 SourceLocation FakeOperatorLoc =
7877 SemaRef.getLocForEndOfToken(E->getBase()->getLocEnd());
7878 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
7879 E->getAccessorLoc(),
7883 template<typename Derived>
7885 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
7886 if (InitListExpr *Syntactic = E->getSyntacticForm())
7889 bool InitChanged = false;
7891 SmallVector<Expr*, 4> Inits;
7892 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
7893 Inits, &InitChanged))
7896 if (!getDerived().AlwaysRebuild() && !InitChanged) {
7897 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
7898 // in some cases. We can't reuse it in general, because the syntactic and
7899 // semantic forms are linked, and we can't know that semantic form will
7900 // match even if the syntactic form does.
7903 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
7904 E->getRBraceLoc(), E->getType());
7907 template<typename Derived>
7909 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
7912 // transform the initializer value
7913 ExprResult Init = getDerived().TransformExpr(E->getInit());
7914 if (Init.isInvalid())
7917 // transform the designators.
7918 SmallVector<Expr*, 4> ArrayExprs;
7919 bool ExprChanged = false;
7920 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
7921 DEnd = E->designators_end();
7923 if (D->isFieldDesignator()) {
7924 Desig.AddDesignator(Designator::getField(D->getFieldName(),
7930 if (D->isArrayDesignator()) {
7931 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
7932 if (Index.isInvalid())
7935 Desig.AddDesignator(Designator::getArray(Index.get(),
7936 D->getLBracketLoc()));
7938 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
7939 ArrayExprs.push_back(Index.get());
7943 assert(D->isArrayRangeDesignator() && "New kind of designator?");
7945 = getDerived().TransformExpr(E->getArrayRangeStart(*D));
7946 if (Start.isInvalid())
7949 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
7950 if (End.isInvalid())
7953 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
7955 D->getLBracketLoc(),
7956 D->getEllipsisLoc()));
7958 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
7959 End.get() != E->getArrayRangeEnd(*D);
7961 ArrayExprs.push_back(Start.get());
7962 ArrayExprs.push_back(End.get());
7965 if (!getDerived().AlwaysRebuild() &&
7966 Init.get() == E->getInit() &&
7970 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
7971 E->getEqualOrColonLoc(),
7972 E->usesGNUSyntax(), Init.get());
7975 // Seems that if TransformInitListExpr() only works on the syntactic form of an
7976 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
7977 template<typename Derived>
7979 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
7980 DesignatedInitUpdateExpr *E) {
7981 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
7986 template<typename Derived>
7988 TreeTransform<Derived>::TransformNoInitExpr(
7990 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
7994 template<typename Derived>
7996 TreeTransform<Derived>::TransformImplicitValueInitExpr(
7997 ImplicitValueInitExpr *E) {
7998 TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
8000 // FIXME: Will we ever have proper type location here? Will we actually
8001 // need to transform the type?
8002 QualType T = getDerived().TransformType(E->getType());
8006 if (!getDerived().AlwaysRebuild() &&
8010 return getDerived().RebuildImplicitValueInitExpr(T);
8013 template<typename Derived>
8015 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
8016 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
8020 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8021 if (SubExpr.isInvalid())
8024 if (!getDerived().AlwaysRebuild() &&
8025 TInfo == E->getWrittenTypeInfo() &&
8026 SubExpr.get() == E->getSubExpr())
8029 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
8030 TInfo, E->getRParenLoc());
8033 template<typename Derived>
8035 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
8036 bool ArgumentChanged = false;
8037 SmallVector<Expr*, 4> Inits;
8038 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
8042 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
8047 /// \brief Transform an address-of-label expression.
8049 /// By default, the transformation of an address-of-label expression always
8050 /// rebuilds the expression, so that the label identifier can be resolved to
8051 /// the corresponding label statement by semantic analysis.
8052 template<typename Derived>
8054 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
8055 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
8060 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
8061 cast<LabelDecl>(LD));
8064 template<typename Derived>
8066 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
8067 SemaRef.ActOnStartStmtExpr();
8069 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
8070 if (SubStmt.isInvalid()) {
8071 SemaRef.ActOnStmtExprError();
8075 if (!getDerived().AlwaysRebuild() &&
8076 SubStmt.get() == E->getSubStmt()) {
8077 // Calling this an 'error' is unintuitive, but it does the right thing.
8078 SemaRef.ActOnStmtExprError();
8079 return SemaRef.MaybeBindToTemporary(E);
8082 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
8087 template<typename Derived>
8089 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
8090 ExprResult Cond = getDerived().TransformExpr(E->getCond());
8091 if (Cond.isInvalid())
8094 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
8095 if (LHS.isInvalid())
8098 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
8099 if (RHS.isInvalid())
8102 if (!getDerived().AlwaysRebuild() &&
8103 Cond.get() == E->getCond() &&
8104 LHS.get() == E->getLHS() &&
8105 RHS.get() == E->getRHS())
8108 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
8109 Cond.get(), LHS.get(), RHS.get(),
8113 template<typename Derived>
8115 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
8119 template<typename Derived>
8121 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8122 switch (E->getOperator()) {
8126 case OO_Array_Delete:
8127 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
8130 // This is a call to an object's operator().
8131 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
8133 // Transform the object itself.
8134 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
8135 if (Object.isInvalid())
8138 // FIXME: Poor location information
8139 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
8140 static_cast<Expr *>(Object.get())->getLocEnd());
8142 // Transform the call arguments.
8143 SmallVector<Expr*, 8> Args;
8144 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
8148 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
8153 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8155 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
8156 #include "clang/Basic/OperatorKinds.def"
8161 case OO_Conditional:
8162 llvm_unreachable("conditional operator is not actually overloadable");
8165 case NUM_OVERLOADED_OPERATORS:
8166 llvm_unreachable("not an overloaded operator?");
8169 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
8170 if (Callee.isInvalid())
8174 if (E->getOperator() == OO_Amp)
8175 First = getDerived().TransformAddressOfOperand(E->getArg(0));
8177 First = getDerived().TransformExpr(E->getArg(0));
8178 if (First.isInvalid())
8182 if (E->getNumArgs() == 2) {
8183 Second = getDerived().TransformExpr(E->getArg(1));
8184 if (Second.isInvalid())
8188 if (!getDerived().AlwaysRebuild() &&
8189 Callee.get() == E->getCallee() &&
8190 First.get() == E->getArg(0) &&
8191 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
8192 return SemaRef.MaybeBindToTemporary(E);
8194 Sema::FPContractStateRAII FPContractState(getSema());
8195 getSema().FPFeatures.fp_contract = E->isFPContractable();
8197 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
8198 E->getOperatorLoc(),
8204 template<typename Derived>
8206 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
8207 return getDerived().TransformCallExpr(E);
8210 template<typename Derived>
8212 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
8213 // Transform the callee.
8214 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
8215 if (Callee.isInvalid())
8218 // Transform exec config.
8219 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
8223 // Transform arguments.
8224 bool ArgChanged = false;
8225 SmallVector<Expr*, 8> Args;
8226 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
8230 if (!getDerived().AlwaysRebuild() &&
8231 Callee.get() == E->getCallee() &&
8233 return SemaRef.MaybeBindToTemporary(E);
8235 // FIXME: Wrong source location information for the '('.
8236 SourceLocation FakeLParenLoc
8237 = ((Expr *)Callee.get())->getSourceRange().getBegin();
8238 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
8240 E->getRParenLoc(), EC.get());
8243 template<typename Derived>
8245 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
8246 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
8251 = getDerived().TransformExpr(E->getSubExprAsWritten());
8252 if (SubExpr.isInvalid())
8255 if (!getDerived().AlwaysRebuild() &&
8256 Type == E->getTypeInfoAsWritten() &&
8257 SubExpr.get() == E->getSubExpr())
8259 return getDerived().RebuildCXXNamedCastExpr(
8260 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
8261 Type, E->getAngleBrackets().getEnd(),
8262 // FIXME. this should be '(' location
8263 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
8266 template<typename Derived>
8268 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
8269 return getDerived().TransformCXXNamedCastExpr(E);
8272 template<typename Derived>
8274 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
8275 return getDerived().TransformCXXNamedCastExpr(E);
8278 template<typename Derived>
8280 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
8281 CXXReinterpretCastExpr *E) {
8282 return getDerived().TransformCXXNamedCastExpr(E);
8285 template<typename Derived>
8287 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
8288 return getDerived().TransformCXXNamedCastExpr(E);
8291 template<typename Derived>
8293 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
8294 CXXFunctionalCastExpr *E) {
8295 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
8300 = getDerived().TransformExpr(E->getSubExprAsWritten());
8301 if (SubExpr.isInvalid())
8304 if (!getDerived().AlwaysRebuild() &&
8305 Type == E->getTypeInfoAsWritten() &&
8306 SubExpr.get() == E->getSubExpr())
8309 return getDerived().RebuildCXXFunctionalCastExpr(Type,
8315 template<typename Derived>
8317 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
8318 if (E->isTypeOperand()) {
8319 TypeSourceInfo *TInfo
8320 = getDerived().TransformType(E->getTypeOperandSourceInfo());
8324 if (!getDerived().AlwaysRebuild() &&
8325 TInfo == E->getTypeOperandSourceInfo())
8328 return getDerived().RebuildCXXTypeidExpr(E->getType(),
8334 // We don't know whether the subexpression is potentially evaluated until
8335 // after we perform semantic analysis. We speculatively assume it is
8336 // unevaluated; it will get fixed later if the subexpression is in fact
8337 // potentially evaluated.
8338 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
8339 Sema::ReuseLambdaContextDecl);
8341 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
8342 if (SubExpr.isInvalid())
8345 if (!getDerived().AlwaysRebuild() &&
8346 SubExpr.get() == E->getExprOperand())
8349 return getDerived().RebuildCXXTypeidExpr(E->getType(),
8355 template<typename Derived>
8357 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
8358 if (E->isTypeOperand()) {
8359 TypeSourceInfo *TInfo
8360 = getDerived().TransformType(E->getTypeOperandSourceInfo());
8364 if (!getDerived().AlwaysRebuild() &&
8365 TInfo == E->getTypeOperandSourceInfo())
8368 return getDerived().RebuildCXXUuidofExpr(E->getType(),
8374 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8376 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
8377 if (SubExpr.isInvalid())
8380 if (!getDerived().AlwaysRebuild() &&
8381 SubExpr.get() == E->getExprOperand())
8384 return getDerived().RebuildCXXUuidofExpr(E->getType(),
8390 template<typename Derived>
8392 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
8396 template<typename Derived>
8398 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
8399 CXXNullPtrLiteralExpr *E) {
8403 template<typename Derived>
8405 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
8406 QualType T = getSema().getCurrentThisType();
8408 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
8409 // Make sure that we capture 'this'.
8410 getSema().CheckCXXThisCapture(E->getLocStart());
8414 return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
8417 template<typename Derived>
8419 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
8420 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8421 if (SubExpr.isInvalid())
8424 if (!getDerived().AlwaysRebuild() &&
8425 SubExpr.get() == E->getSubExpr())
8428 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
8429 E->isThrownVariableInScope());
8432 template<typename Derived>
8434 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
8436 = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
8441 if (!getDerived().AlwaysRebuild() &&
8442 Param == E->getParam())
8445 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
8448 template<typename Derived>
8450 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
8452 = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
8457 if (!getDerived().AlwaysRebuild() && Field == E->getField())
8460 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
8463 template<typename Derived>
8465 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
8466 CXXScalarValueInitExpr *E) {
8467 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
8471 if (!getDerived().AlwaysRebuild() &&
8472 T == E->getTypeSourceInfo())
8475 return getDerived().RebuildCXXScalarValueInitExpr(T,
8476 /*FIXME:*/T->getTypeLoc().getEndLoc(),
8480 template<typename Derived>
8482 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
8483 // Transform the type that we're allocating
8484 TypeSourceInfo *AllocTypeInfo
8485 = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
8489 // Transform the size of the array we're allocating (if any).
8490 ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
8491 if (ArraySize.isInvalid())
8494 // Transform the placement arguments (if any).
8495 bool ArgumentChanged = false;
8496 SmallVector<Expr*, 8> PlacementArgs;
8497 if (getDerived().TransformExprs(E->getPlacementArgs(),
8498 E->getNumPlacementArgs(), true,
8499 PlacementArgs, &ArgumentChanged))
8502 // Transform the initializer (if any).
8503 Expr *OldInit = E->getInitializer();
8506 NewInit = getDerived().TransformInitializer(OldInit, true);
8507 if (NewInit.isInvalid())
8510 // Transform new operator and delete operator.
8511 FunctionDecl *OperatorNew = nullptr;
8512 if (E->getOperatorNew()) {
8513 OperatorNew = cast_or_null<FunctionDecl>(
8514 getDerived().TransformDecl(E->getLocStart(),
8515 E->getOperatorNew()));
8520 FunctionDecl *OperatorDelete = nullptr;
8521 if (E->getOperatorDelete()) {
8522 OperatorDelete = cast_or_null<FunctionDecl>(
8523 getDerived().TransformDecl(E->getLocStart(),
8524 E->getOperatorDelete()));
8525 if (!OperatorDelete)
8529 if (!getDerived().AlwaysRebuild() &&
8530 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
8531 ArraySize.get() == E->getArraySize() &&
8532 NewInit.get() == OldInit &&
8533 OperatorNew == E->getOperatorNew() &&
8534 OperatorDelete == E->getOperatorDelete() &&
8536 // Mark any declarations we need as referenced.
8537 // FIXME: instantiation-specific.
8539 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
8541 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
8543 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
8544 QualType ElementType
8545 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
8546 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
8547 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
8548 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
8549 SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
8557 QualType AllocType = AllocTypeInfo->getType();
8558 if (!ArraySize.get()) {
8559 // If no array size was specified, but the new expression was
8560 // instantiated with an array type (e.g., "new T" where T is
8561 // instantiated with "int[4]"), extract the outer bound from the
8562 // array type as our array size. We do this with constant and
8563 // dependently-sized array types.
8564 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
8567 } else if (const ConstantArrayType *ConsArrayT
8568 = dyn_cast<ConstantArrayType>(ArrayT)) {
8569 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
8570 SemaRef.Context.getSizeType(),
8571 /*FIXME:*/ E->getLocStart());
8572 AllocType = ConsArrayT->getElementType();
8573 } else if (const DependentSizedArrayType *DepArrayT
8574 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
8575 if (DepArrayT->getSizeExpr()) {
8576 ArraySize = DepArrayT->getSizeExpr();
8577 AllocType = DepArrayT->getElementType();
8582 return getDerived().RebuildCXXNewExpr(E->getLocStart(),
8584 /*FIXME:*/E->getLocStart(),
8586 /*FIXME:*/E->getLocStart(),
8587 E->getTypeIdParens(),
8591 E->getDirectInitRange(),
8595 template<typename Derived>
8597 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
8598 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
8599 if (Operand.isInvalid())
8602 // Transform the delete operator, if known.
8603 FunctionDecl *OperatorDelete = nullptr;
8604 if (E->getOperatorDelete()) {
8605 OperatorDelete = cast_or_null<FunctionDecl>(
8606 getDerived().TransformDecl(E->getLocStart(),
8607 E->getOperatorDelete()));
8608 if (!OperatorDelete)
8612 if (!getDerived().AlwaysRebuild() &&
8613 Operand.get() == E->getArgument() &&
8614 OperatorDelete == E->getOperatorDelete()) {
8615 // Mark any declarations we need as referenced.
8616 // FIXME: instantiation-specific.
8618 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
8620 if (!E->getArgument()->isTypeDependent()) {
8621 QualType Destroyed = SemaRef.Context.getBaseElementType(
8622 E->getDestroyedType());
8623 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
8624 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
8625 SemaRef.MarkFunctionReferenced(E->getLocStart(),
8626 SemaRef.LookupDestructor(Record));
8633 return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
8634 E->isGlobalDelete(),
8639 template<typename Derived>
8641 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
8642 CXXPseudoDestructorExpr *E) {
8643 ExprResult Base = getDerived().TransformExpr(E->getBase());
8644 if (Base.isInvalid())
8647 ParsedType ObjectTypePtr;
8648 bool MayBePseudoDestructor = false;
8649 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
8650 E->getOperatorLoc(),
8651 E->isArrow()? tok::arrow : tok::period,
8653 MayBePseudoDestructor);
8654 if (Base.isInvalid())
8657 QualType ObjectType = ObjectTypePtr.get();
8658 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
8661 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
8666 SS.Adopt(QualifierLoc);
8668 PseudoDestructorTypeStorage Destroyed;
8669 if (E->getDestroyedTypeInfo()) {
8670 TypeSourceInfo *DestroyedTypeInfo
8671 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
8672 ObjectType, nullptr, SS);
8673 if (!DestroyedTypeInfo)
8675 Destroyed = DestroyedTypeInfo;
8676 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
8677 // We aren't likely to be able to resolve the identifier down to a type
8678 // now anyway, so just retain the identifier.
8679 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
8680 E->getDestroyedTypeLoc());
8682 // Look for a destructor known with the given name.
8683 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
8684 *E->getDestroyedTypeIdentifier(),
8685 E->getDestroyedTypeLoc(),
8693 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
8694 E->getDestroyedTypeLoc());
8697 TypeSourceInfo *ScopeTypeInfo = nullptr;
8698 if (E->getScopeTypeInfo()) {
8699 CXXScopeSpec EmptySS;
8700 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
8701 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
8706 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
8707 E->getOperatorLoc(),
8711 E->getColonColonLoc(),
8716 template<typename Derived>
8718 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
8719 UnresolvedLookupExpr *Old) {
8720 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
8721 Sema::LookupOrdinaryName);
8723 // Transform all the decls.
8724 for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
8725 E = Old->decls_end(); I != E; ++I) {
8726 NamedDecl *InstD = static_cast<NamedDecl*>(
8727 getDerived().TransformDecl(Old->getNameLoc(),
8730 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
8731 // This can happen because of dependent hiding.
8732 if (isa<UsingShadowDecl>(*I))
8740 // Expand using declarations.
8741 if (isa<UsingDecl>(InstD)) {
8742 UsingDecl *UD = cast<UsingDecl>(InstD);
8743 for (auto *I : UD->shadows())
8751 // Resolve a kind, but don't do any further analysis. If it's
8752 // ambiguous, the callee needs to deal with it.
8755 // Rebuild the nested-name qualifier, if present.
8757 if (Old->getQualifierLoc()) {
8758 NestedNameSpecifierLoc QualifierLoc
8759 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
8763 SS.Adopt(QualifierLoc);
8766 if (Old->getNamingClass()) {
8767 CXXRecordDecl *NamingClass
8768 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
8770 Old->getNamingClass()));
8776 R.setNamingClass(NamingClass);
8779 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
8781 // If we have neither explicit template arguments, nor the template keyword,
8782 // it's a normal declaration name.
8783 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid())
8784 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
8786 // If we have template arguments, rebuild them, then rebuild the
8787 // templateid expression.
8788 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
8789 if (Old->hasExplicitTemplateArgs() &&
8790 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
8791 Old->getNumTemplateArgs(),
8797 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
8798 Old->requiresADL(), &TransArgs);
8801 template<typename Derived>
8803 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
8804 bool ArgChanged = false;
8805 SmallVector<TypeSourceInfo *, 4> Args;
8806 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
8807 TypeSourceInfo *From = E->getArg(I);
8808 TypeLoc FromTL = From->getTypeLoc();
8809 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
8811 TLB.reserve(FromTL.getFullDataSize());
8812 QualType To = getDerived().TransformType(TLB, FromTL);
8816 if (To == From->getType())
8817 Args.push_back(From);
8819 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8827 // We have a pack expansion. Instantiate it.
8828 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
8829 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
8830 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
8831 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
8833 // Determine whether the set of unexpanded parameter packs can and should
8836 bool RetainExpansion = false;
8837 Optional<unsigned> OrigNumExpansions =
8838 ExpansionTL.getTypePtr()->getNumExpansions();
8839 Optional<unsigned> NumExpansions = OrigNumExpansions;
8840 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
8841 PatternTL.getSourceRange(),
8843 Expand, RetainExpansion,
8848 // The transform has determined that we should perform a simple
8849 // transformation on the pack expansion, producing another pack
8851 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
8854 TLB.reserve(From->getTypeLoc().getFullDataSize());
8856 QualType To = getDerived().TransformType(TLB, PatternTL);
8860 To = getDerived().RebuildPackExpansionType(To,
8861 PatternTL.getSourceRange(),
8862 ExpansionTL.getEllipsisLoc(),
8867 PackExpansionTypeLoc ToExpansionTL
8868 = TLB.push<PackExpansionTypeLoc>(To);
8869 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
8870 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8874 // Expand the pack expansion by substituting for each argument in the
8876 for (unsigned I = 0; I != *NumExpansions; ++I) {
8877 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
8879 TLB.reserve(PatternTL.getFullDataSize());
8880 QualType To = getDerived().TransformType(TLB, PatternTL);
8884 if (To->containsUnexpandedParameterPack()) {
8885 To = getDerived().RebuildPackExpansionType(To,
8886 PatternTL.getSourceRange(),
8887 ExpansionTL.getEllipsisLoc(),
8892 PackExpansionTypeLoc ToExpansionTL
8893 = TLB.push<PackExpansionTypeLoc>(To);
8894 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
8897 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8900 if (!RetainExpansion)
8903 // If we're supposed to retain a pack expansion, do so by temporarily
8904 // forgetting the partially-substituted parameter pack.
8905 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
8908 TLB.reserve(From->getTypeLoc().getFullDataSize());
8910 QualType To = getDerived().TransformType(TLB, PatternTL);
8914 To = getDerived().RebuildPackExpansionType(To,
8915 PatternTL.getSourceRange(),
8916 ExpansionTL.getEllipsisLoc(),
8921 PackExpansionTypeLoc ToExpansionTL
8922 = TLB.push<PackExpansionTypeLoc>(To);
8923 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
8924 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
8927 if (!getDerived().AlwaysRebuild() && !ArgChanged)
8930 return getDerived().RebuildTypeTrait(E->getTrait(),
8936 template<typename Derived>
8938 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
8939 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
8943 if (!getDerived().AlwaysRebuild() &&
8944 T == E->getQueriedTypeSourceInfo())
8949 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8950 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
8951 if (SubExpr.isInvalid())
8954 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
8958 return getDerived().RebuildArrayTypeTrait(E->getTrait(),
8965 template<typename Derived>
8967 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
8970 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8971 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
8972 if (SubExpr.isInvalid())
8975 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
8979 return getDerived().RebuildExpressionTrait(
8980 E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
8983 template <typename Derived>
8984 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
8985 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
8986 TypeSourceInfo **RecoveryTSI) {
8987 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
8988 DRE, AddrTaken, RecoveryTSI);
8990 // Propagate both errors and recovered types, which return ExprEmpty.
8991 if (!NewDRE.isUsable())
8994 // We got an expr, wrap it up in parens.
8995 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
8997 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
9001 template <typename Derived>
9002 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
9003 DependentScopeDeclRefExpr *E) {
9004 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
9008 template<typename Derived>
9010 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
9011 DependentScopeDeclRefExpr *E,
9012 bool IsAddressOfOperand,
9013 TypeSourceInfo **RecoveryTSI) {
9014 assert(E->getQualifierLoc());
9015 NestedNameSpecifierLoc QualifierLoc
9016 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9019 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9021 // TODO: If this is a conversion-function-id, verify that the
9022 // destination type name (if present) resolves the same way after
9023 // instantiation as it did in the local scope.
9025 DeclarationNameInfo NameInfo
9026 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
9027 if (!NameInfo.getName())
9030 if (!E->hasExplicitTemplateArgs()) {
9031 if (!getDerived().AlwaysRebuild() &&
9032 QualifierLoc == E->getQualifierLoc() &&
9033 // Note: it is sufficient to compare the Name component of NameInfo:
9034 // if name has not changed, DNLoc has not changed either.
9035 NameInfo.getName() == E->getDeclName())
9038 return getDerived().RebuildDependentScopeDeclRefExpr(
9039 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
9040 IsAddressOfOperand, RecoveryTSI);
9043 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
9044 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9045 E->getNumTemplateArgs(),
9049 return getDerived().RebuildDependentScopeDeclRefExpr(
9050 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
9054 template<typename Derived>
9056 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
9057 // CXXConstructExprs other than for list-initialization and
9058 // CXXTemporaryObjectExpr are always implicit, so when we have
9059 // a 1-argument construction we just transform that argument.
9060 if ((E->getNumArgs() == 1 ||
9061 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
9062 (!getDerived().DropCallArgument(E->getArg(0))) &&
9063 !E->isListInitialization())
9064 return getDerived().TransformExpr(E->getArg(0));
9066 TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
9068 QualType T = getDerived().TransformType(E->getType());
9072 CXXConstructorDecl *Constructor
9073 = cast_or_null<CXXConstructorDecl>(
9074 getDerived().TransformDecl(E->getLocStart(),
9075 E->getConstructor()));
9079 bool ArgumentChanged = false;
9080 SmallVector<Expr*, 8> Args;
9081 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9085 if (!getDerived().AlwaysRebuild() &&
9086 T == E->getType() &&
9087 Constructor == E->getConstructor() &&
9089 // Mark the constructor as referenced.
9090 // FIXME: Instantiation-specific
9091 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
9095 return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
9096 Constructor, E->isElidable(),
9098 E->hadMultipleCandidates(),
9099 E->isListInitialization(),
9100 E->isStdInitListInitialization(),
9101 E->requiresZeroInitialization(),
9102 E->getConstructionKind(),
9103 E->getParenOrBraceRange());
9106 /// \brief Transform a C++ temporary-binding expression.
9108 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
9109 /// transform the subexpression and return that.
9110 template<typename Derived>
9112 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
9113 return getDerived().TransformExpr(E->getSubExpr());
9116 /// \brief Transform a C++ expression that contains cleanups that should
9117 /// be run after the expression is evaluated.
9119 /// Since ExprWithCleanups nodes are implicitly generated, we
9120 /// just transform the subexpression and return that.
9121 template<typename Derived>
9123 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
9124 return getDerived().TransformExpr(E->getSubExpr());
9127 template<typename Derived>
9129 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
9130 CXXTemporaryObjectExpr *E) {
9131 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9135 CXXConstructorDecl *Constructor
9136 = cast_or_null<CXXConstructorDecl>(
9137 getDerived().TransformDecl(E->getLocStart(),
9138 E->getConstructor()));
9142 bool ArgumentChanged = false;
9143 SmallVector<Expr*, 8> Args;
9144 Args.reserve(E->getNumArgs());
9145 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9149 if (!getDerived().AlwaysRebuild() &&
9150 T == E->getTypeSourceInfo() &&
9151 Constructor == E->getConstructor() &&
9153 // FIXME: Instantiation-specific
9154 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
9155 return SemaRef.MaybeBindToTemporary(E);
9158 // FIXME: Pass in E->isListInitialization().
9159 return getDerived().RebuildCXXTemporaryObjectExpr(T,
9160 /*FIXME:*/T->getTypeLoc().getEndLoc(),
9165 template<typename Derived>
9167 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
9168 // Transform any init-capture expressions before entering the scope of the
9169 // lambda body, because they are not semantically within that scope.
9170 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
9171 SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
9172 InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
9173 E->explicit_capture_begin());
9174 for (LambdaExpr::capture_iterator C = E->capture_begin(),
9175 CEnd = E->capture_end();
9177 if (!E->isInitCapture(C))
9179 EnterExpressionEvaluationContext EEEC(getSema(),
9180 Sema::PotentiallyEvaluated);
9181 ExprResult NewExprInitResult = getDerived().TransformInitializer(
9182 C->getCapturedVar()->getInit(),
9183 C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
9185 if (NewExprInitResult.isInvalid())
9187 Expr *NewExprInit = NewExprInitResult.get();
9189 VarDecl *OldVD = C->getCapturedVar();
9190 QualType NewInitCaptureType =
9191 getSema().performLambdaInitCaptureInitialization(C->getLocation(),
9192 OldVD->getType()->isReferenceType(), OldVD->getIdentifier(),
9194 NewExprInitResult = NewExprInit;
9195 InitCaptureExprsAndTypes[C - E->capture_begin()] =
9196 std::make_pair(NewExprInitResult, NewInitCaptureType);
9199 // Transform the template parameters, and add them to the current
9200 // instantiation scope. The null case is handled correctly.
9201 auto TPL = getDerived().TransformTemplateParameterList(
9202 E->getTemplateParameterList());
9204 // Transform the type of the original lambda's call operator.
9205 // The transformation MUST be done in the CurrentInstantiationScope since
9206 // it introduces a mapping of the original to the newly created
9207 // transformed parameters.
9208 TypeSourceInfo *NewCallOpTSI = nullptr;
9210 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
9211 FunctionProtoTypeLoc OldCallOpFPTL =
9212 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
9214 TypeLocBuilder NewCallOpTLBuilder;
9215 SmallVector<QualType, 4> ExceptionStorage;
9216 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
9217 QualType NewCallOpType = TransformFunctionProtoType(
9218 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, 0,
9219 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
9220 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
9221 ExceptionStorage, Changed);
9223 if (NewCallOpType.isNull())
9225 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
9229 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
9230 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
9231 LSI->GLTemplateParameterList = TPL;
9233 // Create the local class that will describe the lambda.
9234 CXXRecordDecl *Class
9235 = getSema().createLambdaClosureType(E->getIntroducerRange(),
9237 /*KnownDependent=*/false,
9238 E->getCaptureDefault());
9239 getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
9241 // Build the call operator.
9242 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
9243 Class, E->getIntroducerRange(), NewCallOpTSI,
9244 E->getCallOperator()->getLocEnd(),
9245 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams());
9246 LSI->CallOperator = NewCallOperator;
9248 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
9249 getDerived().transformedLocalDecl(E->getCallOperator(), NewCallOperator);
9251 // Introduce the context of the call operator.
9252 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
9253 /*NewThisContext*/false);
9255 // Enter the scope of the lambda.
9256 getSema().buildLambdaScope(LSI, NewCallOperator,
9257 E->getIntroducerRange(),
9258 E->getCaptureDefault(),
9259 E->getCaptureDefaultLoc(),
9260 E->hasExplicitParameters(),
9261 E->hasExplicitResultType(),
9264 bool Invalid = false;
9266 // Transform captures.
9267 bool FinishedExplicitCaptures = false;
9268 for (LambdaExpr::capture_iterator C = E->capture_begin(),
9269 CEnd = E->capture_end();
9271 // When we hit the first implicit capture, tell Sema that we've finished
9272 // the list of explicit captures.
9273 if (!FinishedExplicitCaptures && C->isImplicit()) {
9274 getSema().finishLambdaExplicitCaptures(LSI);
9275 FinishedExplicitCaptures = true;
9278 // Capturing 'this' is trivial.
9279 if (C->capturesThis()) {
9280 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
9283 // Captured expression will be recaptured during captured variables
9285 if (C->capturesVLAType())
9288 // Rebuild init-captures, including the implied field declaration.
9289 if (E->isInitCapture(C)) {
9290 InitCaptureInfoTy InitExprTypePair =
9291 InitCaptureExprsAndTypes[C - E->capture_begin()];
9292 ExprResult Init = InitExprTypePair.first;
9293 QualType InitQualType = InitExprTypePair.second;
9294 if (Init.isInvalid() || InitQualType.isNull()) {
9298 VarDecl *OldVD = C->getCapturedVar();
9299 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
9300 OldVD->getLocation(), InitExprTypePair.second,
9301 OldVD->getIdentifier(), Init.get());
9305 getDerived().transformedLocalDecl(OldVD, NewVD);
9307 getSema().buildInitCaptureField(LSI, NewVD);
9311 assert(C->capturesVariable() && "unexpected kind of lambda capture");
9313 // Determine the capture kind for Sema.
9314 Sema::TryCaptureKind Kind
9315 = C->isImplicit()? Sema::TryCapture_Implicit
9316 : C->getCaptureKind() == LCK_ByCopy
9317 ? Sema::TryCapture_ExplicitByVal
9318 : Sema::TryCapture_ExplicitByRef;
9319 SourceLocation EllipsisLoc;
9320 if (C->isPackExpansion()) {
9321 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
9322 bool ShouldExpand = false;
9323 bool RetainExpansion = false;
9324 Optional<unsigned> NumExpansions;
9325 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
9328 ShouldExpand, RetainExpansion,
9335 // The transform has determined that we should perform an expansion;
9336 // transform and capture each of the arguments.
9337 // expansion of the pattern. Do so.
9338 VarDecl *Pack = C->getCapturedVar();
9339 for (unsigned I = 0; I != *NumExpansions; ++I) {
9340 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
9341 VarDecl *CapturedVar
9342 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
9349 // Capture the transformed variable.
9350 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
9353 // FIXME: Retain a pack expansion if RetainExpansion is true.
9358 EllipsisLoc = C->getEllipsisLoc();
9361 // Transform the captured variable.
9362 VarDecl *CapturedVar
9363 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
9364 C->getCapturedVar()));
9365 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
9370 // Capture the transformed variable.
9371 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
9373 if (!FinishedExplicitCaptures)
9374 getSema().finishLambdaExplicitCaptures(LSI);
9376 // Enter a new evaluation context to insulate the lambda from any
9377 // cleanups from the enclosing full-expression.
9378 getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
9380 // Instantiate the body of the lambda expression.
9382 Invalid ? StmtError() : getDerived().TransformStmt(E->getBody());
9384 // ActOnLambda* will pop the function scope for us.
9385 FuncScopeCleanup.disable();
9387 if (Body.isInvalid()) {
9389 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
9390 /*IsInstantiation=*/true);
9394 // Copy the LSI before ActOnFinishFunctionBody removes it.
9395 // FIXME: This is dumb. Store the lambda information somewhere that outlives
9396 // the call operator.
9397 auto LSICopy = *LSI;
9398 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
9399 /*IsInstantiation*/ true);
9402 return getSema().BuildLambdaExpr(E->getLocStart(), Body.get()->getLocEnd(),
9406 template<typename Derived>
9408 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
9409 CXXUnresolvedConstructExpr *E) {
9410 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9414 bool ArgumentChanged = false;
9415 SmallVector<Expr*, 8> Args;
9416 Args.reserve(E->arg_size());
9417 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
9421 if (!getDerived().AlwaysRebuild() &&
9422 T == E->getTypeSourceInfo() &&
9426 // FIXME: we're faking the locations of the commas
9427 return getDerived().RebuildCXXUnresolvedConstructExpr(T,
9433 template<typename Derived>
9435 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
9436 CXXDependentScopeMemberExpr *E) {
9437 // Transform the base of the expression.
9438 ExprResult Base((Expr*) nullptr);
9441 QualType ObjectType;
9442 if (!E->isImplicitAccess()) {
9443 OldBase = E->getBase();
9444 Base = getDerived().TransformExpr(OldBase);
9445 if (Base.isInvalid())
9448 // Start the member reference and compute the object's type.
9449 ParsedType ObjectTy;
9450 bool MayBePseudoDestructor = false;
9451 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
9452 E->getOperatorLoc(),
9453 E->isArrow()? tok::arrow : tok::period,
9455 MayBePseudoDestructor);
9456 if (Base.isInvalid())
9459 ObjectType = ObjectTy.get();
9460 BaseType = ((Expr*) Base.get())->getType();
9463 BaseType = getDerived().TransformType(E->getBaseType());
9464 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
9467 // Transform the first part of the nested-name-specifier that qualifies
9469 NamedDecl *FirstQualifierInScope
9470 = getDerived().TransformFirstQualifierInScope(
9471 E->getFirstQualifierFoundInScope(),
9472 E->getQualifierLoc().getBeginLoc());
9474 NestedNameSpecifierLoc QualifierLoc;
9475 if (E->getQualifier()) {
9477 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
9479 FirstQualifierInScope);
9484 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9486 // TODO: If this is a conversion-function-id, verify that the
9487 // destination type name (if present) resolves the same way after
9488 // instantiation as it did in the local scope.
9490 DeclarationNameInfo NameInfo
9491 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
9492 if (!NameInfo.getName())
9495 if (!E->hasExplicitTemplateArgs()) {
9496 // This is a reference to a member without an explicitly-specified
9497 // template argument list. Optimize for this common case.
9498 if (!getDerived().AlwaysRebuild() &&
9499 Base.get() == OldBase &&
9500 BaseType == E->getBaseType() &&
9501 QualifierLoc == E->getQualifierLoc() &&
9502 NameInfo.getName() == E->getMember() &&
9503 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
9506 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
9509 E->getOperatorLoc(),
9512 FirstQualifierInScope,
9514 /*TemplateArgs*/nullptr);
9517 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
9518 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9519 E->getNumTemplateArgs(),
9523 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
9526 E->getOperatorLoc(),
9529 FirstQualifierInScope,
9534 template<typename Derived>
9536 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
9537 // Transform the base of the expression.
9538 ExprResult Base((Expr*) nullptr);
9540 if (!Old->isImplicitAccess()) {
9541 Base = getDerived().TransformExpr(Old->getBase());
9542 if (Base.isInvalid())
9544 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
9546 if (Base.isInvalid())
9548 BaseType = Base.get()->getType();
9550 BaseType = getDerived().TransformType(Old->getBaseType());
9553 NestedNameSpecifierLoc QualifierLoc;
9554 if (Old->getQualifierLoc()) {
9556 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
9561 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
9563 LookupResult R(SemaRef, Old->getMemberNameInfo(),
9564 Sema::LookupOrdinaryName);
9566 // Transform all the decls.
9567 for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
9568 E = Old->decls_end(); I != E; ++I) {
9569 NamedDecl *InstD = static_cast<NamedDecl*>(
9570 getDerived().TransformDecl(Old->getMemberLoc(),
9573 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
9574 // This can happen because of dependent hiding.
9575 if (isa<UsingShadowDecl>(*I))
9583 // Expand using declarations.
9584 if (isa<UsingDecl>(InstD)) {
9585 UsingDecl *UD = cast<UsingDecl>(InstD);
9586 for (auto *I : UD->shadows())
9596 // Determine the naming class.
9597 if (Old->getNamingClass()) {
9598 CXXRecordDecl *NamingClass
9599 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
9600 Old->getMemberLoc(),
9601 Old->getNamingClass()));
9605 R.setNamingClass(NamingClass);
9608 TemplateArgumentListInfo TransArgs;
9609 if (Old->hasExplicitTemplateArgs()) {
9610 TransArgs.setLAngleLoc(Old->getLAngleLoc());
9611 TransArgs.setRAngleLoc(Old->getRAngleLoc());
9612 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
9613 Old->getNumTemplateArgs(),
9618 // FIXME: to do this check properly, we will need to preserve the
9619 // first-qualifier-in-scope here, just in case we had a dependent
9620 // base (and therefore couldn't do the check) and a
9621 // nested-name-qualifier (and therefore could do the lookup).
9622 NamedDecl *FirstQualifierInScope = nullptr;
9624 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
9626 Old->getOperatorLoc(),
9630 FirstQualifierInScope,
9632 (Old->hasExplicitTemplateArgs()
9633 ? &TransArgs : nullptr));
9636 template<typename Derived>
9638 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
9639 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
9640 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
9641 if (SubExpr.isInvalid())
9644 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
9647 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
9650 template<typename Derived>
9652 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
9653 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
9654 if (Pattern.isInvalid())
9657 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
9660 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
9661 E->getNumExpansions());
9664 template<typename Derived>
9666 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
9667 // If E is not value-dependent, then nothing will change when we transform it.
9668 // Note: This is an instantiation-centric view.
9669 if (!E->isValueDependent())
9672 // Note: None of the implementations of TryExpandParameterPacks can ever
9673 // produce a diagnostic when given only a single unexpanded parameter pack,
9675 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
9676 bool ShouldExpand = false;
9677 bool RetainExpansion = false;
9678 Optional<unsigned> NumExpansions;
9679 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
9681 ShouldExpand, RetainExpansion,
9685 if (RetainExpansion)
9688 NamedDecl *Pack = E->getPack();
9689 if (!ShouldExpand) {
9690 Pack = cast_or_null<NamedDecl>(getDerived().TransformDecl(E->getPackLoc(),
9697 // We now know the length of the parameter pack, so build a new expression
9698 // that stores that length.
9699 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
9700 E->getPackLoc(), E->getRParenLoc(),
9704 template<typename Derived>
9706 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
9707 SubstNonTypeTemplateParmPackExpr *E) {
9708 // Default behavior is to do nothing with this transformation.
9712 template<typename Derived>
9714 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
9715 SubstNonTypeTemplateParmExpr *E) {
9716 // Default behavior is to do nothing with this transformation.
9720 template<typename Derived>
9722 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
9723 // Default behavior is to do nothing with this transformation.
9727 template<typename Derived>
9729 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
9730 MaterializeTemporaryExpr *E) {
9731 return getDerived().TransformExpr(E->GetTemporaryExpr());
9734 template<typename Derived>
9736 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
9737 Expr *Pattern = E->getPattern();
9739 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
9740 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
9741 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
9743 // Determine whether the set of unexpanded parameter packs can and should
9746 bool RetainExpansion = false;
9747 Optional<unsigned> NumExpansions;
9748 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
9749 Pattern->getSourceRange(),
9751 Expand, RetainExpansion,
9756 // Do not expand any packs here, just transform and rebuild a fold
9758 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
9761 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
9762 if (LHS.isInvalid())
9766 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
9767 if (RHS.isInvalid())
9770 if (!getDerived().AlwaysRebuild() &&
9771 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
9774 return getDerived().RebuildCXXFoldExpr(
9775 E->getLocStart(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
9776 RHS.get(), E->getLocEnd());
9779 // The transform has determined that we should perform an elementwise
9780 // expansion of the pattern. Do so.
9781 ExprResult Result = getDerived().TransformExpr(E->getInit());
9782 if (Result.isInvalid())
9784 bool LeftFold = E->isLeftFold();
9786 // If we're retaining an expansion for a right fold, it is the innermost
9787 // component and takes the init (if any).
9788 if (!LeftFold && RetainExpansion) {
9789 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
9791 ExprResult Out = getDerived().TransformExpr(Pattern);
9792 if (Out.isInvalid())
9795 Result = getDerived().RebuildCXXFoldExpr(
9796 E->getLocStart(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
9797 Result.get(), E->getLocEnd());
9798 if (Result.isInvalid())
9802 for (unsigned I = 0; I != *NumExpansions; ++I) {
9803 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
9804 getSema(), LeftFold ? I : *NumExpansions - I - 1);
9805 ExprResult Out = getDerived().TransformExpr(Pattern);
9806 if (Out.isInvalid())
9809 if (Out.get()->containsUnexpandedParameterPack()) {
9810 // We still have a pack; retain a pack expansion for this slice.
9811 Result = getDerived().RebuildCXXFoldExpr(
9813 LeftFold ? Result.get() : Out.get(),
9814 E->getOperator(), E->getEllipsisLoc(),
9815 LeftFold ? Out.get() : Result.get(),
9817 } else if (Result.isUsable()) {
9818 // We've got down to a single element; build a binary operator.
9819 Result = getDerived().RebuildBinaryOperator(
9820 E->getEllipsisLoc(), E->getOperator(),
9821 LeftFold ? Result.get() : Out.get(),
9822 LeftFold ? Out.get() : Result.get());
9826 if (Result.isInvalid())
9830 // If we're retaining an expansion for a left fold, it is the outermost
9831 // component and takes the complete expansion so far as its init (if any).
9832 if (LeftFold && RetainExpansion) {
9833 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
9835 ExprResult Out = getDerived().TransformExpr(Pattern);
9836 if (Out.isInvalid())
9839 Result = getDerived().RebuildCXXFoldExpr(
9840 E->getLocStart(), Result.get(),
9841 E->getOperator(), E->getEllipsisLoc(),
9842 Out.get(), E->getLocEnd());
9843 if (Result.isInvalid())
9847 // If we had no init and an empty pack, and we're not retaining an expansion,
9848 // then produce a fallback value or error.
9849 if (Result.isUnset())
9850 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
9856 template<typename Derived>
9858 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
9859 CXXStdInitializerListExpr *E) {
9860 return getDerived().TransformExpr(E->getSubExpr());
9863 template<typename Derived>
9865 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
9866 return SemaRef.MaybeBindToTemporary(E);
9869 template<typename Derived>
9871 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
9875 template<typename Derived>
9877 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
9878 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9879 if (SubExpr.isInvalid())
9882 if (!getDerived().AlwaysRebuild() &&
9883 SubExpr.get() == E->getSubExpr())
9886 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
9889 template<typename Derived>
9891 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
9892 // Transform each of the elements.
9893 SmallVector<Expr *, 8> Elements;
9894 bool ArgChanged = false;
9895 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
9896 /*IsCall=*/false, Elements, &ArgChanged))
9899 if (!getDerived().AlwaysRebuild() && !ArgChanged)
9900 return SemaRef.MaybeBindToTemporary(E);
9902 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
9907 template<typename Derived>
9909 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
9910 ObjCDictionaryLiteral *E) {
9911 // Transform each of the elements.
9912 SmallVector<ObjCDictionaryElement, 8> Elements;
9913 bool ArgChanged = false;
9914 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
9915 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
9917 if (OrigElement.isPackExpansion()) {
9918 // This key/value element is a pack expansion.
9919 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
9920 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
9921 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
9922 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
9924 // Determine whether the set of unexpanded parameter packs can
9925 // and should be expanded.
9927 bool RetainExpansion = false;
9928 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
9929 Optional<unsigned> NumExpansions = OrigNumExpansions;
9930 SourceRange PatternRange(OrigElement.Key->getLocStart(),
9931 OrigElement.Value->getLocEnd());
9932 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
9935 Expand, RetainExpansion,
9940 // The transform has determined that we should perform a simple
9941 // transformation on the pack expansion, producing another pack
9943 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
9944 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
9945 if (Key.isInvalid())
9948 if (Key.get() != OrigElement.Key)
9951 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
9952 if (Value.isInvalid())
9955 if (Value.get() != OrigElement.Value)
9958 ObjCDictionaryElement Expansion = {
9959 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
9961 Elements.push_back(Expansion);
9965 // Record right away that the argument was changed. This needs
9966 // to happen even if the array expands to nothing.
9969 // The transform has determined that we should perform an elementwise
9970 // expansion of the pattern. Do so.
9971 for (unsigned I = 0; I != *NumExpansions; ++I) {
9972 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
9973 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
9974 if (Key.isInvalid())
9977 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
9978 if (Value.isInvalid())
9981 ObjCDictionaryElement Element = {
9982 Key.get(), Value.get(), SourceLocation(), NumExpansions
9985 // If any unexpanded parameter packs remain, we still have a
9987 // FIXME: Can this really happen?
9988 if (Key.get()->containsUnexpandedParameterPack() ||
9989 Value.get()->containsUnexpandedParameterPack())
9990 Element.EllipsisLoc = OrigElement.EllipsisLoc;
9992 Elements.push_back(Element);
9995 // FIXME: Retain a pack expansion if RetainExpansion is true.
9997 // We've finished with this pack expansion.
10001 // Transform and check key.
10002 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
10003 if (Key.isInvalid())
10004 return ExprError();
10006 if (Key.get() != OrigElement.Key)
10009 // Transform and check value.
10011 = getDerived().TransformExpr(OrigElement.Value);
10012 if (Value.isInvalid())
10013 return ExprError();
10015 if (Value.get() != OrigElement.Value)
10018 ObjCDictionaryElement Element = {
10019 Key.get(), Value.get(), SourceLocation(), None
10021 Elements.push_back(Element);
10024 if (!getDerived().AlwaysRebuild() && !ArgChanged)
10025 return SemaRef.MaybeBindToTemporary(E);
10027 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
10032 template<typename Derived>
10034 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
10035 TypeSourceInfo *EncodedTypeInfo
10036 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
10037 if (!EncodedTypeInfo)
10038 return ExprError();
10040 if (!getDerived().AlwaysRebuild() &&
10041 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
10044 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
10046 E->getRParenLoc());
10049 template<typename Derived>
10050 ExprResult TreeTransform<Derived>::
10051 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
10052 // This is a kind of implicit conversion, and it needs to get dropped
10053 // and recomputed for the same general reasons that ImplicitCastExprs
10054 // do, as well a more specific one: this expression is only valid when
10055 // it appears *immediately* as an argument expression.
10056 return getDerived().TransformExpr(E->getSubExpr());
10059 template<typename Derived>
10060 ExprResult TreeTransform<Derived>::
10061 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
10062 TypeSourceInfo *TSInfo
10063 = getDerived().TransformType(E->getTypeInfoAsWritten());
10065 return ExprError();
10067 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
10068 if (Result.isInvalid())
10069 return ExprError();
10071 if (!getDerived().AlwaysRebuild() &&
10072 TSInfo == E->getTypeInfoAsWritten() &&
10073 Result.get() == E->getSubExpr())
10076 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
10077 E->getBridgeKeywordLoc(), TSInfo,
10081 template<typename Derived>
10083 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
10084 // Transform arguments.
10085 bool ArgChanged = false;
10086 SmallVector<Expr*, 8> Args;
10087 Args.reserve(E->getNumArgs());
10088 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
10090 return ExprError();
10092 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
10093 // Class message: transform the receiver type.
10094 TypeSourceInfo *ReceiverTypeInfo
10095 = getDerived().TransformType(E->getClassReceiverTypeInfo());
10096 if (!ReceiverTypeInfo)
10097 return ExprError();
10099 // If nothing changed, just retain the existing message send.
10100 if (!getDerived().AlwaysRebuild() &&
10101 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
10102 return SemaRef.MaybeBindToTemporary(E);
10104 // Build a new class message send.
10105 SmallVector<SourceLocation, 16> SelLocs;
10106 E->getSelectorLocs(SelLocs);
10107 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
10110 E->getMethodDecl(),
10115 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
10116 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10117 // Build a new class message send to 'super'.
10118 SmallVector<SourceLocation, 16> SelLocs;
10119 E->getSelectorLocs(SelLocs);
10120 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
10123 E->getMethodDecl(),
10129 // Instance message: transform the receiver
10130 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
10131 "Only class and instance messages may be instantiated");
10132 ExprResult Receiver
10133 = getDerived().TransformExpr(E->getInstanceReceiver());
10134 if (Receiver.isInvalid())
10135 return ExprError();
10137 // If nothing changed, just retain the existing message send.
10138 if (!getDerived().AlwaysRebuild() &&
10139 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
10140 return SemaRef.MaybeBindToTemporary(E);
10142 // Build a new instance message send.
10143 SmallVector<SourceLocation, 16> SelLocs;
10144 E->getSelectorLocs(SelLocs);
10145 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
10148 E->getMethodDecl(),
10154 template<typename Derived>
10156 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
10160 template<typename Derived>
10162 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
10166 template<typename Derived>
10168 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
10169 // Transform the base expression.
10170 ExprResult Base = getDerived().TransformExpr(E->getBase());
10171 if (Base.isInvalid())
10172 return ExprError();
10174 // We don't need to transform the ivar; it will never change.
10176 // If nothing changed, just retain the existing expression.
10177 if (!getDerived().AlwaysRebuild() &&
10178 Base.get() == E->getBase())
10181 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
10183 E->isArrow(), E->isFreeIvar());
10186 template<typename Derived>
10188 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
10189 // 'super' and types never change. Property never changes. Just
10190 // retain the existing expression.
10191 if (!E->isObjectReceiver())
10194 // Transform the base expression.
10195 ExprResult Base = getDerived().TransformExpr(E->getBase());
10196 if (Base.isInvalid())
10197 return ExprError();
10199 // We don't need to transform the property; it will never change.
10201 // If nothing changed, just retain the existing expression.
10202 if (!getDerived().AlwaysRebuild() &&
10203 Base.get() == E->getBase())
10206 if (E->isExplicitProperty())
10207 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10208 E->getExplicitProperty(),
10211 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
10212 SemaRef.Context.PseudoObjectTy,
10213 E->getImplicitPropertyGetter(),
10214 E->getImplicitPropertySetter(),
10218 template<typename Derived>
10220 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
10221 // Transform the base expression.
10222 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
10223 if (Base.isInvalid())
10224 return ExprError();
10226 // Transform the key expression.
10227 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
10228 if (Key.isInvalid())
10229 return ExprError();
10231 // If nothing changed, just retain the existing expression.
10232 if (!getDerived().AlwaysRebuild() &&
10233 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
10236 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
10237 Base.get(), Key.get(),
10238 E->getAtIndexMethodDecl(),
10239 E->setAtIndexMethodDecl());
10242 template<typename Derived>
10244 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
10245 // Transform the base expression.
10246 ExprResult Base = getDerived().TransformExpr(E->getBase());
10247 if (Base.isInvalid())
10248 return ExprError();
10250 // If nothing changed, just retain the existing expression.
10251 if (!getDerived().AlwaysRebuild() &&
10252 Base.get() == E->getBase())
10255 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
10260 template<typename Derived>
10262 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
10263 bool ArgumentChanged = false;
10264 SmallVector<Expr*, 8> SubExprs;
10265 SubExprs.reserve(E->getNumSubExprs());
10266 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10267 SubExprs, &ArgumentChanged))
10268 return ExprError();
10270 if (!getDerived().AlwaysRebuild() &&
10274 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
10276 E->getRParenLoc());
10279 template<typename Derived>
10281 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
10282 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
10283 if (SrcExpr.isInvalid())
10284 return ExprError();
10286 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10288 return ExprError();
10290 if (!getDerived().AlwaysRebuild() &&
10291 Type == E->getTypeSourceInfo() &&
10292 SrcExpr.get() == E->getSrcExpr())
10295 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
10296 SrcExpr.get(), Type,
10297 E->getRParenLoc());
10300 template<typename Derived>
10302 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
10303 BlockDecl *oldBlock = E->getBlockDecl();
10305 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
10306 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
10308 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
10309 blockScope->TheDecl->setBlockMissingReturnType(
10310 oldBlock->blockMissingReturnType());
10312 SmallVector<ParmVarDecl*, 4> params;
10313 SmallVector<QualType, 4> paramTypes;
10315 // Parameter substitution.
10316 if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
10317 oldBlock->param_begin(),
10318 oldBlock->param_size(),
10319 nullptr, paramTypes, ¶ms)) {
10320 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10321 return ExprError();
10324 const FunctionProtoType *exprFunctionType = E->getFunctionType();
10325 QualType exprResultType =
10326 getDerived().TransformType(exprFunctionType->getReturnType());
10328 QualType functionType =
10329 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes,
10330 exprFunctionType->getExtProtoInfo());
10331 blockScope->FunctionType = functionType;
10333 // Set the parameters on the block decl.
10334 if (!params.empty())
10335 blockScope->TheDecl->setParams(params);
10337 if (!oldBlock->blockMissingReturnType()) {
10338 blockScope->HasImplicitReturnType = false;
10339 blockScope->ReturnType = exprResultType;
10342 // Transform the body
10343 StmtResult body = getDerived().TransformStmt(E->getBody());
10344 if (body.isInvalid()) {
10345 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
10346 return ExprError();
10350 // In builds with assertions, make sure that we captured everything we
10351 // captured before.
10352 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
10353 for (const auto &I : oldBlock->captures()) {
10354 VarDecl *oldCapture = I.getVariable();
10356 // Ignore parameter packs.
10357 if (isa<ParmVarDecl>(oldCapture) &&
10358 cast<ParmVarDecl>(oldCapture)->isParameterPack())
10361 VarDecl *newCapture =
10362 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
10364 assert(blockScope->CaptureMap.count(newCapture));
10366 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
10370 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
10371 /*Scope=*/nullptr);
10374 template<typename Derived>
10376 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
10377 llvm_unreachable("Cannot transform asType expressions yet");
10380 template<typename Derived>
10382 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
10383 QualType RetTy = getDerived().TransformType(E->getType());
10384 bool ArgumentChanged = false;
10385 SmallVector<Expr*, 8> SubExprs;
10386 SubExprs.reserve(E->getNumSubExprs());
10387 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
10388 SubExprs, &ArgumentChanged))
10389 return ExprError();
10391 if (!getDerived().AlwaysRebuild() &&
10395 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
10396 RetTy, E->getOp(), E->getRParenLoc());
10399 //===----------------------------------------------------------------------===//
10400 // Type reconstruction
10401 //===----------------------------------------------------------------------===//
10403 template<typename Derived>
10404 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
10405 SourceLocation Star) {
10406 return SemaRef.BuildPointerType(PointeeType, Star,
10407 getDerived().getBaseEntity());
10410 template<typename Derived>
10411 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
10412 SourceLocation Star) {
10413 return SemaRef.BuildBlockPointerType(PointeeType, Star,
10414 getDerived().getBaseEntity());
10417 template<typename Derived>
10419 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
10420 bool WrittenAsLValue,
10421 SourceLocation Sigil) {
10422 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
10423 Sigil, getDerived().getBaseEntity());
10426 template<typename Derived>
10428 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
10429 QualType ClassType,
10430 SourceLocation Sigil) {
10431 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
10432 getDerived().getBaseEntity());
10435 template<typename Derived>
10437 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
10438 ArrayType::ArraySizeModifier SizeMod,
10439 const llvm::APInt *Size,
10441 unsigned IndexTypeQuals,
10442 SourceRange BracketsRange) {
10443 if (SizeExpr || !Size)
10444 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
10445 IndexTypeQuals, BracketsRange,
10446 getDerived().getBaseEntity());
10448 QualType Types[] = {
10449 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
10450 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
10451 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
10453 const unsigned NumTypes = llvm::array_lengthof(Types);
10455 for (unsigned I = 0; I != NumTypes; ++I)
10456 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
10457 SizeType = Types[I];
10461 // Note that we can return a VariableArrayType here in the case where
10462 // the element type was a dependent VariableArrayType.
10463 IntegerLiteral *ArraySize
10464 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
10465 /*FIXME*/BracketsRange.getBegin());
10466 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
10467 IndexTypeQuals, BracketsRange,
10468 getDerived().getBaseEntity());
10471 template<typename Derived>
10473 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
10474 ArrayType::ArraySizeModifier SizeMod,
10475 const llvm::APInt &Size,
10476 unsigned IndexTypeQuals,
10477 SourceRange BracketsRange) {
10478 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
10479 IndexTypeQuals, BracketsRange);
10482 template<typename Derived>
10484 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
10485 ArrayType::ArraySizeModifier SizeMod,
10486 unsigned IndexTypeQuals,
10487 SourceRange BracketsRange) {
10488 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
10489 IndexTypeQuals, BracketsRange);
10492 template<typename Derived>
10494 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
10495 ArrayType::ArraySizeModifier SizeMod,
10497 unsigned IndexTypeQuals,
10498 SourceRange BracketsRange) {
10499 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10501 IndexTypeQuals, BracketsRange);
10504 template<typename Derived>
10506 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
10507 ArrayType::ArraySizeModifier SizeMod,
10509 unsigned IndexTypeQuals,
10510 SourceRange BracketsRange) {
10511 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
10513 IndexTypeQuals, BracketsRange);
10516 template<typename Derived>
10517 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
10518 unsigned NumElements,
10519 VectorType::VectorKind VecKind) {
10520 // FIXME: semantic checking!
10521 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
10524 template<typename Derived>
10525 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
10526 unsigned NumElements,
10527 SourceLocation AttributeLoc) {
10528 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
10529 NumElements, true);
10530 IntegerLiteral *VectorSize
10531 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
10533 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
10536 template<typename Derived>
10538 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
10540 SourceLocation AttributeLoc) {
10541 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
10544 template<typename Derived>
10545 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
10547 MutableArrayRef<QualType> ParamTypes,
10548 const FunctionProtoType::ExtProtoInfo &EPI) {
10549 return SemaRef.BuildFunctionType(T, ParamTypes,
10550 getDerived().getBaseLocation(),
10551 getDerived().getBaseEntity(),
10555 template<typename Derived>
10556 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
10557 return SemaRef.Context.getFunctionNoProtoType(T);
10560 template<typename Derived>
10561 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
10562 assert(D && "no decl found");
10563 if (D->isInvalidDecl()) return QualType();
10565 // FIXME: Doesn't account for ObjCInterfaceDecl!
10567 if (isa<UsingDecl>(D)) {
10568 UsingDecl *Using = cast<UsingDecl>(D);
10569 assert(Using->hasTypename() &&
10570 "UnresolvedUsingTypenameDecl transformed to non-typename using");
10572 // A valid resolved using typename decl points to exactly one type decl.
10573 assert(++Using->shadow_begin() == Using->shadow_end());
10574 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
10577 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
10578 "UnresolvedUsingTypenameDecl transformed to non-using decl");
10579 Ty = cast<UnresolvedUsingTypenameDecl>(D);
10582 return SemaRef.Context.getTypeDeclType(Ty);
10585 template<typename Derived>
10586 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
10587 SourceLocation Loc) {
10588 return SemaRef.BuildTypeofExprType(E, Loc);
10591 template<typename Derived>
10592 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
10593 return SemaRef.Context.getTypeOfType(Underlying);
10596 template<typename Derived>
10597 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
10598 SourceLocation Loc) {
10599 return SemaRef.BuildDecltypeType(E, Loc);
10602 template<typename Derived>
10603 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
10604 UnaryTransformType::UTTKind UKind,
10605 SourceLocation Loc) {
10606 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
10609 template<typename Derived>
10610 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
10611 TemplateName Template,
10612 SourceLocation TemplateNameLoc,
10613 TemplateArgumentListInfo &TemplateArgs) {
10614 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
10617 template<typename Derived>
10618 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
10619 SourceLocation KWLoc) {
10620 return SemaRef.BuildAtomicType(ValueType, KWLoc);
10623 template<typename Derived>
10625 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10627 TemplateDecl *Template) {
10628 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
10632 template<typename Derived>
10634 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10635 const IdentifierInfo &Name,
10636 SourceLocation NameLoc,
10637 QualType ObjectType,
10638 NamedDecl *FirstQualifierInScope) {
10639 UnqualifiedId TemplateName;
10640 TemplateName.setIdentifier(&Name, NameLoc);
10641 Sema::TemplateTy Template;
10642 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10643 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10644 SS, TemplateKWLoc, TemplateName,
10645 ParsedType::make(ObjectType),
10646 /*EnteringContext=*/false,
10648 return Template.get();
10651 template<typename Derived>
10653 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
10654 OverloadedOperatorKind Operator,
10655 SourceLocation NameLoc,
10656 QualType ObjectType) {
10657 UnqualifiedId Name;
10658 // FIXME: Bogus location information.
10659 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
10660 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
10661 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10662 Sema::TemplateTy Template;
10663 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
10664 SS, TemplateKWLoc, Name,
10665 ParsedType::make(ObjectType),
10666 /*EnteringContext=*/false,
10668 return Template.get();
10671 template<typename Derived>
10673 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
10674 SourceLocation OpLoc,
10678 Expr *Callee = OrigCallee->IgnoreParenCasts();
10679 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
10681 if (First->getObjectKind() == OK_ObjCProperty) {
10682 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10683 if (BinaryOperator::isAssignmentOp(Opc))
10684 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
10686 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
10687 if (Result.isInvalid())
10688 return ExprError();
10689 First = Result.get();
10692 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
10693 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
10694 if (Result.isInvalid())
10695 return ExprError();
10696 Second = Result.get();
10699 // Determine whether this should be a builtin operation.
10700 if (Op == OO_Subscript) {
10701 if (!First->getType()->isOverloadableType() &&
10702 !Second->getType()->isOverloadableType())
10703 return getSema().CreateBuiltinArraySubscriptExpr(First,
10704 Callee->getLocStart(),
10706 } else if (Op == OO_Arrow) {
10707 // -> is never a builtin operation.
10708 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
10709 } else if (Second == nullptr || isPostIncDec) {
10710 if (!First->getType()->isOverloadableType()) {
10711 // The argument is not of overloadable type, so try to create a
10712 // built-in unary operation.
10713 UnaryOperatorKind Opc
10714 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10716 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
10719 if (!First->getType()->isOverloadableType() &&
10720 !Second->getType()->isOverloadableType()) {
10721 // Neither of the arguments is an overloadable type, so try to
10722 // create a built-in binary operation.
10723 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10725 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
10726 if (Result.isInvalid())
10727 return ExprError();
10733 // Compute the transformed set of functions (and function templates) to be
10734 // used during overload resolution.
10735 UnresolvedSet<16> Functions;
10737 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
10738 assert(ULE->requiresADL());
10739 Functions.append(ULE->decls_begin(), ULE->decls_end());
10741 // If we've resolved this to a particular non-member function, just call
10742 // that function. If we resolved it to a member function,
10743 // CreateOverloaded* will find that function for us.
10744 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
10745 if (!isa<CXXMethodDecl>(ND))
10746 Functions.addDecl(ND);
10749 // Add any functions found via argument-dependent lookup.
10750 Expr *Args[2] = { First, Second };
10751 unsigned NumArgs = 1 + (Second != nullptr);
10753 // Create the overloaded operator invocation for unary operators.
10754 if (NumArgs == 1 || isPostIncDec) {
10755 UnaryOperatorKind Opc
10756 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
10757 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
10760 if (Op == OO_Subscript) {
10761 SourceLocation LBrace;
10762 SourceLocation RBrace;
10764 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
10765 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
10766 LBrace = SourceLocation::getFromRawEncoding(
10767 NameLoc.CXXOperatorName.BeginOpNameLoc);
10768 RBrace = SourceLocation::getFromRawEncoding(
10769 NameLoc.CXXOperatorName.EndOpNameLoc);
10771 LBrace = Callee->getLocStart();
10775 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
10779 // Create the overloaded operator invocation for binary operators.
10780 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
10782 = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
10783 if (Result.isInvalid())
10784 return ExprError();
10789 template<typename Derived>
10791 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
10792 SourceLocation OperatorLoc,
10795 TypeSourceInfo *ScopeType,
10796 SourceLocation CCLoc,
10797 SourceLocation TildeLoc,
10798 PseudoDestructorTypeStorage Destroyed) {
10799 QualType BaseType = Base->getType();
10800 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
10801 (!isArrow && !BaseType->getAs<RecordType>()) ||
10802 (isArrow && BaseType->getAs<PointerType>() &&
10803 !BaseType->getAs<PointerType>()->getPointeeType()
10804 ->template getAs<RecordType>())){
10805 // This pseudo-destructor expression is still a pseudo-destructor.
10806 return SemaRef.BuildPseudoDestructorExpr(
10807 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
10808 CCLoc, TildeLoc, Destroyed);
10811 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
10812 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
10813 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
10814 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
10815 NameInfo.setNamedTypeInfo(DestroyedType);
10817 // The scope type is now known to be a valid nested name specifier
10818 // component. Tack it on to the end of the nested name specifier.
10820 if (!ScopeType->getType()->getAs<TagType>()) {
10821 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
10822 diag::err_expected_class_or_namespace)
10823 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
10824 return ExprError();
10826 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
10830 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
10831 return getSema().BuildMemberReferenceExpr(Base, BaseType,
10832 OperatorLoc, isArrow,
10834 /*FIXME: FirstQualifier*/ nullptr,
10836 /*TemplateArgs*/ nullptr);
10839 template<typename Derived>
10841 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
10842 SourceLocation Loc = S->getLocStart();
10843 CapturedDecl *CD = S->getCapturedDecl();
10844 unsigned NumParams = CD->getNumParams();
10845 unsigned ContextParamPos = CD->getContextParamPosition();
10846 SmallVector<Sema::CapturedParamNameType, 4> Params;
10847 for (unsigned I = 0; I < NumParams; ++I) {
10848 if (I != ContextParamPos) {
10851 CD->getParam(I)->getName(),
10852 getDerived().TransformType(CD->getParam(I)->getType())));
10854 Params.push_back(std::make_pair(StringRef(), QualType()));
10857 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
10858 S->getCapturedRegionKind(), Params);
10861 Sema::CompoundScopeRAII CompoundScope(getSema());
10862 Body = getDerived().TransformStmt(S->getCapturedStmt());
10865 if (Body.isInvalid()) {
10866 getSema().ActOnCapturedRegionError();
10867 return StmtError();
10870 return getSema().ActOnCapturedRegionEnd(Body.get());
10873 } // end namespace clang