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 "CoroutineStmtBuilder.h"
18 #include "TypeLocBuilder.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/AST/StmtOpenMP.h"
30 #include "clang/Sema/Designator.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Ownership.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaDiagnostic.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/Support/ErrorHandling.h"
44 /// \brief A semantic tree transformation that allows one to transform one
45 /// abstract syntax tree into another.
47 /// A new tree transformation is defined by creating a new subclass \c X of
48 /// \c TreeTransform<X> and then overriding certain operations to provide
49 /// behavior specific to that transformation. For example, template
50 /// instantiation is implemented as a tree transformation where the
51 /// transformation of TemplateTypeParmType nodes involves substituting the
52 /// template arguments for their corresponding template parameters; a similar
53 /// transformation is performed for non-type template parameters and
54 /// template template parameters.
56 /// This tree-transformation template uses static polymorphism to allow
57 /// subclasses to customize any of its operations. Thus, a subclass can
58 /// override any of the transformation or rebuild operators by providing an
59 /// operation with the same signature as the default implementation. The
60 /// overridding function should not be virtual.
62 /// Semantic tree transformations are split into two stages, either of which
63 /// can be replaced by a subclass. The "transform" step transforms an AST node
64 /// or the parts of an AST node using the various transformation functions,
65 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
66 /// node of the appropriate kind from the pieces. The default transformation
67 /// routines recursively transform the operands to composite AST nodes (e.g.,
68 /// the pointee type of a PointerType node) and, if any of those operand nodes
69 /// were changed by the transformation, invokes the rebuild operation to create
72 /// Subclasses can customize the transformation at various levels. The
73 /// most coarse-grained transformations involve replacing TransformType(),
74 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
75 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
76 /// new implementations.
78 /// For more fine-grained transformations, subclasses can replace any of the
79 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
80 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
81 /// replacing TransformTemplateTypeParmType() allows template instantiation
82 /// to substitute template arguments for their corresponding template
83 /// parameters. Additionally, subclasses can override the \c RebuildXXX
84 /// functions to control how AST nodes are rebuilt when their operands change.
85 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
86 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
87 /// be able to use more efficient rebuild steps.
89 /// There are a handful of other functions that can be overridden, allowing one
90 /// to avoid traversing nodes that don't need any transformation
91 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
92 /// operands have not changed (\c AlwaysRebuild()), and customize the
93 /// default locations and entity names used for type-checking
94 /// (\c getBaseLocation(), \c getBaseEntity()).
95 template<typename Derived>
97 /// \brief Private RAII object that helps us forget and then re-remember
98 /// the template argument corresponding to a partially-substituted parameter
100 class ForgetPartiallySubstitutedPackRAII {
102 TemplateArgument Old;
105 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
106 Old = Self.ForgetPartiallySubstitutedPack();
109 ~ForgetPartiallySubstitutedPackRAII() {
110 Self.RememberPartiallySubstitutedPack(Old);
117 /// \brief The set of local declarations that have been transformed, for
118 /// cases where we are forced to build new declarations within the transformer
119 /// rather than in the subclass (e.g., lambda closure types).
120 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
123 /// \brief Initializes a new tree transformer.
124 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
126 /// \brief Retrieves a reference to the derived class.
127 Derived &getDerived() { return static_cast<Derived&>(*this); }
129 /// \brief Retrieves a reference to the derived class.
130 const Derived &getDerived() const {
131 return static_cast<const Derived&>(*this);
134 static inline ExprResult Owned(Expr *E) { return E; }
135 static inline StmtResult Owned(Stmt *S) { return S; }
137 /// \brief Retrieves a reference to the semantic analysis object used for
138 /// this tree transform.
139 Sema &getSema() const { return SemaRef; }
141 /// \brief Whether the transformation should always rebuild AST nodes, even
142 /// if none of the children have changed.
144 /// Subclasses may override this function to specify when the transformation
145 /// should rebuild all AST nodes.
147 /// We must always rebuild all AST nodes when performing variadic template
148 /// pack expansion, in order to avoid violating the AST invariant that each
149 /// statement node appears at most once in its containing declaration.
150 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
152 /// \brief Returns the location of the entity being transformed, if that
153 /// information was not available elsewhere in the AST.
155 /// By default, returns no source-location information. Subclasses can
156 /// provide an alternative implementation that provides better location
158 SourceLocation getBaseLocation() { return SourceLocation(); }
160 /// \brief Returns the name of the entity being transformed, if that
161 /// information was not available elsewhere in the AST.
163 /// By default, returns an empty name. Subclasses can provide an alternative
164 /// implementation with a more precise name.
165 DeclarationName getBaseEntity() { return DeclarationName(); }
167 /// \brief Sets the "base" location and entity when that
168 /// information is known based on another transformation.
170 /// By default, the source location and entity are ignored. Subclasses can
171 /// override this function to provide a customized implementation.
172 void setBase(SourceLocation Loc, DeclarationName Entity) { }
174 /// \brief RAII object that temporarily sets the base location and entity
175 /// used for reporting diagnostics in types.
176 class TemporaryBase {
178 SourceLocation OldLocation;
179 DeclarationName OldEntity;
182 TemporaryBase(TreeTransform &Self, SourceLocation Location,
183 DeclarationName Entity) : Self(Self) {
184 OldLocation = Self.getDerived().getBaseLocation();
185 OldEntity = Self.getDerived().getBaseEntity();
187 if (Location.isValid())
188 Self.getDerived().setBase(Location, Entity);
192 Self.getDerived().setBase(OldLocation, OldEntity);
196 /// \brief Determine whether the given type \p T has already been
199 /// Subclasses can provide an alternative implementation of this routine
200 /// to short-circuit evaluation when it is known that a given type will
201 /// not change. For example, template instantiation need not traverse
202 /// non-dependent types.
203 bool AlreadyTransformed(QualType T) {
207 /// \brief Determine whether the given call argument should be dropped, e.g.,
208 /// because it is a default argument.
210 /// Subclasses can provide an alternative implementation of this routine to
211 /// determine which kinds of call arguments get dropped. By default,
212 /// CXXDefaultArgument nodes are dropped (prior to transformation).
213 bool DropCallArgument(Expr *E) {
214 return E->isDefaultArgument();
217 /// \brief Determine whether we should expand a pack expansion with the
218 /// given set of parameter packs into separate arguments by repeatedly
219 /// transforming the pattern.
221 /// By default, the transformer never tries to expand pack expansions.
222 /// Subclasses can override this routine to provide different behavior.
224 /// \param EllipsisLoc The location of the ellipsis that identifies the
227 /// \param PatternRange The source range that covers the entire pattern of
228 /// the pack expansion.
230 /// \param Unexpanded The set of unexpanded parameter packs within the
233 /// \param ShouldExpand Will be set to \c true if the transformer should
234 /// expand the corresponding pack expansions into separate arguments. When
235 /// set, \c NumExpansions must also be set.
237 /// \param RetainExpansion Whether the caller should add an unexpanded
238 /// pack expansion after all of the expanded arguments. This is used
239 /// when extending explicitly-specified template argument packs per
240 /// C++0x [temp.arg.explicit]p9.
242 /// \param NumExpansions The number of separate arguments that will be in
243 /// the expanded form of the corresponding pack expansion. This is both an
244 /// input and an output parameter, which can be set by the caller if the
245 /// number of expansions is known a priori (e.g., due to a prior substitution)
246 /// and will be set by the callee when the number of expansions is known.
247 /// The callee must set this value when \c ShouldExpand is \c true; it may
248 /// set this value in other cases.
250 /// \returns true if an error occurred (e.g., because the parameter packs
251 /// are to be instantiated with arguments of different lengths), false
252 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
254 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
255 SourceRange PatternRange,
256 ArrayRef<UnexpandedParameterPack> Unexpanded,
258 bool &RetainExpansion,
259 Optional<unsigned> &NumExpansions) {
260 ShouldExpand = false;
264 /// \brief "Forget" about the partially-substituted pack template argument,
265 /// when performing an instantiation that must preserve the parameter pack
268 /// This routine is meant to be overridden by the template instantiator.
269 TemplateArgument ForgetPartiallySubstitutedPack() {
270 return TemplateArgument();
273 /// \brief "Remember" the partially-substituted pack template argument
274 /// after performing an instantiation that must preserve the parameter pack
277 /// This routine is meant to be overridden by the template instantiator.
278 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
280 /// \brief Note to the derived class when a function parameter pack is
282 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
284 /// \brief Transforms the given type into another type.
286 /// By default, this routine transforms a type by creating a
287 /// TypeSourceInfo for it and delegating to the appropriate
288 /// function. This is expensive, but we don't mind, because
289 /// this method is deprecated anyway; all users should be
290 /// switched to storing TypeSourceInfos.
292 /// \returns the transformed type.
293 QualType TransformType(QualType T);
295 /// \brief Transforms the given type-with-location into a new
296 /// type-with-location.
298 /// By default, this routine transforms a type by delegating to the
299 /// appropriate TransformXXXType to build a new type. Subclasses
300 /// may override this function (to take over all type
301 /// transformations) or some set of the TransformXXXType functions
302 /// to alter the transformation.
303 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
305 /// \brief Transform the given type-with-location into a new
306 /// type, collecting location information in the given builder
309 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
311 /// \brief Transform a type that is permitted to produce a
312 /// DeducedTemplateSpecializationType.
314 /// This is used in the (relatively rare) contexts where it is acceptable
315 /// for transformation to produce a class template type with deduced
316 /// template arguments.
318 QualType TransformTypeWithDeducedTST(QualType T);
319 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
322 /// \brief Transform the given statement.
324 /// By default, this routine transforms a statement by delegating to the
325 /// appropriate TransformXXXStmt function to transform a specific kind of
326 /// statement or the TransformExpr() function to transform an expression.
327 /// Subclasses may override this function to transform statements using some
330 /// \returns the transformed statement.
331 StmtResult TransformStmt(Stmt *S);
333 /// \brief Transform the given statement.
335 /// By default, this routine transforms a statement by delegating to the
336 /// appropriate TransformOMPXXXClause function to transform a specific kind
337 /// of clause. Subclasses may override this function to transform statements
338 /// using some other mechanism.
340 /// \returns the transformed OpenMP clause.
341 OMPClause *TransformOMPClause(OMPClause *S);
343 /// \brief Transform the given attribute.
345 /// By default, this routine transforms a statement by delegating to the
346 /// appropriate TransformXXXAttr function to transform a specific kind
347 /// of attribute. Subclasses may override this function to transform
348 /// attributed statements using some other mechanism.
350 /// \returns the transformed attribute
351 const Attr *TransformAttr(const Attr *S);
353 /// \brief Transform the specified attribute.
355 /// Subclasses should override the transformation of attributes with a pragma
356 /// spelling to transform expressions stored within the attribute.
358 /// \returns the transformed attribute.
360 #define PRAGMA_SPELLING_ATTR(X) \
361 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
362 #include "clang/Basic/AttrList.inc"
364 /// \brief Transform the given expression.
366 /// By default, this routine transforms an expression by delegating to the
367 /// appropriate TransformXXXExpr function to build a new expression.
368 /// Subclasses may override this function to transform expressions using some
371 /// \returns the transformed expression.
372 ExprResult TransformExpr(Expr *E);
374 /// \brief Transform the given initializer.
376 /// By default, this routine transforms an initializer by stripping off the
377 /// semantic nodes added by initialization, then passing the result to
378 /// TransformExpr or TransformExprs.
380 /// \returns the transformed initializer.
381 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
383 /// \brief Transform the given list of expressions.
385 /// This routine transforms a list of expressions by invoking
386 /// \c TransformExpr() for each subexpression. However, it also provides
387 /// support for variadic templates by expanding any pack expansions (if the
388 /// derived class permits such expansion) along the way. When pack expansions
389 /// are present, the number of outputs may not equal the number of inputs.
391 /// \param Inputs The set of expressions to be transformed.
393 /// \param NumInputs The number of expressions in \c Inputs.
395 /// \param IsCall If \c true, then this transform is being performed on
396 /// function-call arguments, and any arguments that should be dropped, will
399 /// \param Outputs The transformed input expressions will be added to this
402 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
403 /// due to transformation.
405 /// \returns true if an error occurred, false otherwise.
406 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
407 SmallVectorImpl<Expr *> &Outputs,
408 bool *ArgChanged = nullptr);
410 /// \brief Transform the given declaration, which is referenced from a type
413 /// By default, acts as the identity function on declarations, unless the
414 /// transformer has had to transform the declaration itself. Subclasses
415 /// may override this function to provide alternate behavior.
416 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
417 llvm::DenseMap<Decl *, Decl *>::iterator Known
418 = TransformedLocalDecls.find(D);
419 if (Known != TransformedLocalDecls.end())
420 return Known->second;
425 /// \brief Transform the specified condition.
427 /// By default, this transforms the variable and expression and rebuilds
429 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
431 Sema::ConditionKind Kind);
433 /// \brief Transform the attributes associated with the given declaration and
434 /// place them on the new declaration.
436 /// By default, this operation does nothing. Subclasses may override this
437 /// behavior to transform attributes.
438 void transformAttrs(Decl *Old, Decl *New) { }
440 /// \brief Note that a local declaration has been transformed by this
443 /// Local declarations are typically transformed via a call to
444 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
445 /// the transformer itself has to transform the declarations. This routine
446 /// can be overridden by a subclass that keeps track of such mappings.
447 void transformedLocalDecl(Decl *Old, Decl *New) {
448 TransformedLocalDecls[Old] = New;
451 /// \brief Transform the definition of the given declaration.
453 /// By default, invokes TransformDecl() to transform the declaration.
454 /// Subclasses may override this function to provide alternate behavior.
455 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
456 return getDerived().TransformDecl(Loc, D);
459 /// \brief Transform the given declaration, which was the first part of a
460 /// nested-name-specifier in a member access expression.
462 /// This specific declaration transformation only applies to the first
463 /// identifier in a nested-name-specifier of a member access expression, e.g.,
464 /// the \c T in \c x->T::member
466 /// By default, invokes TransformDecl() to transform the declaration.
467 /// Subclasses may override this function to provide alternate behavior.
468 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
469 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
472 /// Transform the set of declarations in an OverloadExpr.
473 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
476 /// \brief Transform the given nested-name-specifier with source-location
479 /// By default, transforms all of the types and declarations within the
480 /// nested-name-specifier. Subclasses may override this function to provide
481 /// alternate behavior.
482 NestedNameSpecifierLoc
483 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
484 QualType ObjectType = QualType(),
485 NamedDecl *FirstQualifierInScope = nullptr);
487 /// \brief Transform the given declaration name.
489 /// By default, transforms the types of conversion function, constructor,
490 /// and destructor names and then (if needed) rebuilds the declaration name.
491 /// Identifiers and selectors are returned unmodified. Sublcasses may
492 /// override this function to provide alternate behavior.
494 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
496 /// \brief Transform the given template name.
498 /// \param SS The nested-name-specifier that qualifies the template
499 /// name. This nested-name-specifier must already have been transformed.
501 /// \param Name The template name to transform.
503 /// \param NameLoc The source location of the template name.
505 /// \param ObjectType If we're translating a template name within a member
506 /// access expression, this is the type of the object whose member template
507 /// is being referenced.
509 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
510 /// also refers to a name within the current (lexical) scope, this is the
511 /// declaration it refers to.
513 /// By default, transforms the template name by transforming the declarations
514 /// and nested-name-specifiers that occur within the template name.
515 /// Subclasses may override this function to provide alternate behavior.
517 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
518 SourceLocation NameLoc,
519 QualType ObjectType = QualType(),
520 NamedDecl *FirstQualifierInScope = nullptr,
521 bool AllowInjectedClassName = false);
523 /// \brief Transform the given template argument.
525 /// By default, this operation transforms the type, expression, or
526 /// declaration stored within the template argument and constructs a
527 /// new template argument from the transformed result. Subclasses may
528 /// override this function to provide alternate behavior.
530 /// Returns true if there was an error.
531 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
532 TemplateArgumentLoc &Output,
533 bool Uneval = false);
535 /// \brief Transform the given set of template arguments.
537 /// By default, this operation transforms all of the template arguments
538 /// in the input set using \c TransformTemplateArgument(), and appends
539 /// the transformed arguments to the output list.
541 /// Note that this overload of \c TransformTemplateArguments() is merely
542 /// a convenience function. Subclasses that wish to override this behavior
543 /// should override the iterator-based member template version.
545 /// \param Inputs The set of template arguments to be transformed.
547 /// \param NumInputs The number of template arguments in \p Inputs.
549 /// \param Outputs The set of transformed template arguments output by this
552 /// Returns true if an error occurred.
553 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
555 TemplateArgumentListInfo &Outputs,
556 bool Uneval = false) {
557 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
561 /// \brief Transform the given set of template arguments.
563 /// By default, this operation transforms all of the template arguments
564 /// in the input set using \c TransformTemplateArgument(), and appends
565 /// the transformed arguments to the output list.
567 /// \param First An iterator to the first template argument.
569 /// \param Last An iterator one step past the last template argument.
571 /// \param Outputs The set of transformed template arguments output by this
574 /// Returns true if an error occurred.
575 template<typename InputIterator>
576 bool TransformTemplateArguments(InputIterator First,
578 TemplateArgumentListInfo &Outputs,
579 bool Uneval = false);
581 /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
582 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
583 TemplateArgumentLoc &ArgLoc);
585 /// \brief Fakes up a TypeSourceInfo for a type.
586 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
587 return SemaRef.Context.getTrivialTypeSourceInfo(T,
588 getDerived().getBaseLocation());
591 #define ABSTRACT_TYPELOC(CLASS, PARENT)
592 #define TYPELOC(CLASS, PARENT) \
593 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
594 #include "clang/AST/TypeLocNodes.def"
596 template<typename Fn>
597 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
598 FunctionProtoTypeLoc TL,
599 CXXRecordDecl *ThisContext,
600 unsigned ThisTypeQuals,
601 Fn TransformExceptionSpec);
603 bool TransformExceptionSpec(SourceLocation Loc,
604 FunctionProtoType::ExceptionSpecInfo &ESI,
605 SmallVectorImpl<QualType> &Exceptions,
608 StmtResult TransformSEHHandler(Stmt *Handler);
611 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
612 TemplateSpecializationTypeLoc TL,
613 TemplateName Template);
616 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
617 DependentTemplateSpecializationTypeLoc TL,
618 TemplateName Template,
621 QualType TransformDependentTemplateSpecializationType(
622 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
623 NestedNameSpecifierLoc QualifierLoc);
625 /// \brief Transforms the parameters of a function type into the
628 /// The result vectors should be kept in sync; null entries in the
629 /// variables vector are acceptable.
631 /// Return true on error.
632 bool TransformFunctionTypeParams(
633 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
634 const QualType *ParamTypes,
635 const FunctionProtoType::ExtParameterInfo *ParamInfos,
636 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
637 Sema::ExtParameterInfoBuilder &PInfos);
639 /// \brief Transforms a single function-type parameter. Return null
642 /// \param indexAdjustment - A number to add to the parameter's
643 /// scope index; can be negative
644 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
646 Optional<unsigned> NumExpansions,
647 bool ExpectParameterPack);
649 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
651 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
652 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
654 TemplateParameterList *TransformTemplateParameterList(
655 TemplateParameterList *TPL) {
659 ExprResult TransformAddressOfOperand(Expr *E);
661 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
662 bool IsAddressOfOperand,
663 TypeSourceInfo **RecoveryTSI);
665 ExprResult TransformParenDependentScopeDeclRefExpr(
666 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
667 TypeSourceInfo **RecoveryTSI);
669 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
671 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
672 // amount of stack usage with clang.
673 #define STMT(Node, Parent) \
674 LLVM_ATTRIBUTE_NOINLINE \
675 StmtResult Transform##Node(Node *S);
676 #define EXPR(Node, Parent) \
677 LLVM_ATTRIBUTE_NOINLINE \
678 ExprResult Transform##Node(Node *E);
679 #define ABSTRACT_STMT(Stmt)
680 #include "clang/AST/StmtNodes.inc"
682 #define OPENMP_CLAUSE(Name, Class) \
683 LLVM_ATTRIBUTE_NOINLINE \
684 OMPClause *Transform ## Class(Class *S);
685 #include "clang/Basic/OpenMPKinds.def"
687 /// \brief Build a new qualified type given its unqualified type and type
690 /// By default, this routine adds type qualifiers only to types that can
691 /// have qualifiers, and silently suppresses those qualifiers that are not
692 /// permitted. Subclasses may override this routine to provide different
694 QualType RebuildQualifiedType(QualType T, SourceLocation Loc,
697 /// \brief Build a new pointer type given its pointee type.
699 /// By default, performs semantic analysis when building the pointer type.
700 /// Subclasses may override this routine to provide different behavior.
701 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
703 /// \brief Build a new block pointer type given its pointee type.
705 /// By default, performs semantic analysis when building the block pointer
706 /// type. Subclasses may override this routine to provide different behavior.
707 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
709 /// \brief Build a new reference type given the type it references.
711 /// By default, performs semantic analysis when building the
712 /// reference type. Subclasses may override this routine to provide
713 /// different behavior.
715 /// \param LValue whether the type was written with an lvalue sigil
716 /// or an rvalue sigil.
717 QualType RebuildReferenceType(QualType ReferentType,
719 SourceLocation Sigil);
721 /// \brief Build a new member pointer type given the pointee type and the
722 /// class type it refers into.
724 /// By default, performs semantic analysis when building the member pointer
725 /// type. Subclasses may override this routine to provide different behavior.
726 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
727 SourceLocation Sigil);
729 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
730 SourceLocation ProtocolLAngleLoc,
731 ArrayRef<ObjCProtocolDecl *> Protocols,
732 ArrayRef<SourceLocation> ProtocolLocs,
733 SourceLocation ProtocolRAngleLoc);
735 /// \brief Build an Objective-C object type.
737 /// By default, performs semantic analysis when building the object type.
738 /// Subclasses may override this routine to provide different behavior.
739 QualType RebuildObjCObjectType(QualType BaseType,
741 SourceLocation TypeArgsLAngleLoc,
742 ArrayRef<TypeSourceInfo *> TypeArgs,
743 SourceLocation TypeArgsRAngleLoc,
744 SourceLocation ProtocolLAngleLoc,
745 ArrayRef<ObjCProtocolDecl *> Protocols,
746 ArrayRef<SourceLocation> ProtocolLocs,
747 SourceLocation ProtocolRAngleLoc);
749 /// \brief Build a new Objective-C object pointer type given the pointee type.
751 /// By default, directly builds the pointer type, with no additional semantic
753 QualType RebuildObjCObjectPointerType(QualType PointeeType,
754 SourceLocation Star);
756 /// \brief Build a new array type given the element type, size
757 /// modifier, size of the array (if known), size expression, and index type
760 /// By default, performs semantic analysis when building the array type.
761 /// Subclasses may override this routine to provide different behavior.
762 /// Also by default, all of the other Rebuild*Array
763 QualType RebuildArrayType(QualType ElementType,
764 ArrayType::ArraySizeModifier SizeMod,
765 const llvm::APInt *Size,
767 unsigned IndexTypeQuals,
768 SourceRange BracketsRange);
770 /// \brief Build a new constant array type given the element type, size
771 /// modifier, (known) size of the array, and index type qualifiers.
773 /// By default, performs semantic analysis when building the array type.
774 /// Subclasses may override this routine to provide different behavior.
775 QualType RebuildConstantArrayType(QualType ElementType,
776 ArrayType::ArraySizeModifier SizeMod,
777 const llvm::APInt &Size,
778 unsigned IndexTypeQuals,
779 SourceRange BracketsRange);
781 /// \brief Build a new incomplete array type given the element type, size
782 /// modifier, and index type qualifiers.
784 /// By default, performs semantic analysis when building the array type.
785 /// Subclasses may override this routine to provide different behavior.
786 QualType RebuildIncompleteArrayType(QualType ElementType,
787 ArrayType::ArraySizeModifier SizeMod,
788 unsigned IndexTypeQuals,
789 SourceRange BracketsRange);
791 /// \brief Build a new variable-length array type given the element type,
792 /// size modifier, size expression, and index type qualifiers.
794 /// By default, performs semantic analysis when building the array type.
795 /// Subclasses may override this routine to provide different behavior.
796 QualType RebuildVariableArrayType(QualType ElementType,
797 ArrayType::ArraySizeModifier SizeMod,
799 unsigned IndexTypeQuals,
800 SourceRange BracketsRange);
802 /// \brief Build a new dependent-sized array type given the element type,
803 /// size modifier, size expression, and index type qualifiers.
805 /// By default, performs semantic analysis when building the array type.
806 /// Subclasses may override this routine to provide different behavior.
807 QualType RebuildDependentSizedArrayType(QualType ElementType,
808 ArrayType::ArraySizeModifier SizeMod,
810 unsigned IndexTypeQuals,
811 SourceRange BracketsRange);
813 /// \brief Build a new vector type given the element type and
814 /// number of elements.
816 /// By default, performs semantic analysis when building the vector type.
817 /// Subclasses may override this routine to provide different behavior.
818 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
819 VectorType::VectorKind VecKind);
821 /// \brief Build a new extended vector type given the element type and
822 /// number of elements.
824 /// By default, performs semantic analysis when building the vector type.
825 /// Subclasses may override this routine to provide different behavior.
826 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
827 SourceLocation AttributeLoc);
829 /// \brief Build a new potentially dependently-sized extended vector type
830 /// given the element type and number of elements.
832 /// By default, performs semantic analysis when building the vector type.
833 /// Subclasses may override this routine to provide different behavior.
834 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
836 SourceLocation AttributeLoc);
838 /// \brief Build a new function type.
840 /// By default, performs semantic analysis when building the function type.
841 /// Subclasses may override this routine to provide different behavior.
842 QualType RebuildFunctionProtoType(QualType T,
843 MutableArrayRef<QualType> ParamTypes,
844 const FunctionProtoType::ExtProtoInfo &EPI);
846 /// \brief Build a new unprototyped function type.
847 QualType RebuildFunctionNoProtoType(QualType ResultType);
849 /// \brief Rebuild an unresolved typename type, given the decl that
850 /// the UnresolvedUsingTypenameDecl was transformed to.
851 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
853 /// \brief Build a new typedef type.
854 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
855 return SemaRef.Context.getTypeDeclType(Typedef);
858 /// \brief Build a new class/struct/union type.
859 QualType RebuildRecordType(RecordDecl *Record) {
860 return SemaRef.Context.getTypeDeclType(Record);
863 /// \brief Build a new Enum type.
864 QualType RebuildEnumType(EnumDecl *Enum) {
865 return SemaRef.Context.getTypeDeclType(Enum);
868 /// \brief Build a new typeof(expr) type.
870 /// By default, performs semantic analysis when building the typeof type.
871 /// Subclasses may override this routine to provide different behavior.
872 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
874 /// \brief Build a new typeof(type) type.
876 /// By default, builds a new TypeOfType with the given underlying type.
877 QualType RebuildTypeOfType(QualType Underlying);
879 /// \brief Build a new unary transform type.
880 QualType RebuildUnaryTransformType(QualType BaseType,
881 UnaryTransformType::UTTKind UKind,
884 /// \brief Build a new C++11 decltype type.
886 /// By default, performs semantic analysis when building the decltype type.
887 /// Subclasses may override this routine to provide different behavior.
888 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
890 /// \brief Build a new C++11 auto type.
892 /// By default, builds a new AutoType with the given deduced type.
893 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
894 // Note, IsDependent is always false here: we implicitly convert an 'auto'
895 // which has been deduced to a dependent type into an undeduced 'auto', so
896 // that we'll retry deduction after the transformation.
897 return SemaRef.Context.getAutoType(Deduced, Keyword,
898 /*IsDependent*/ false);
901 /// By default, builds a new DeducedTemplateSpecializationType with the given
903 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
905 return SemaRef.Context.getDeducedTemplateSpecializationType(
906 Template, Deduced, /*IsDependent*/ false);
909 /// \brief Build a new template specialization type.
911 /// By default, performs semantic analysis when building the template
912 /// specialization type. Subclasses may override this routine to provide
913 /// different behavior.
914 QualType RebuildTemplateSpecializationType(TemplateName Template,
915 SourceLocation TemplateLoc,
916 TemplateArgumentListInfo &Args);
918 /// \brief Build a new parenthesized type.
920 /// By default, builds a new ParenType type from the inner type.
921 /// Subclasses may override this routine to provide different behavior.
922 QualType RebuildParenType(QualType InnerType) {
923 return SemaRef.BuildParenType(InnerType);
926 /// \brief Build a new qualified name type.
928 /// By default, builds a new ElaboratedType type from the keyword,
929 /// the nested-name-specifier and the named type.
930 /// Subclasses may override this routine to provide different behavior.
931 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
932 ElaboratedTypeKeyword Keyword,
933 NestedNameSpecifierLoc QualifierLoc,
935 return SemaRef.Context.getElaboratedType(Keyword,
936 QualifierLoc.getNestedNameSpecifier(),
940 /// \brief Build a new typename type that refers to a template-id.
942 /// By default, builds a new DependentNameType type from the
943 /// nested-name-specifier and the given type. Subclasses may override
944 /// this routine to provide different behavior.
945 QualType RebuildDependentTemplateSpecializationType(
946 ElaboratedTypeKeyword Keyword,
947 NestedNameSpecifierLoc QualifierLoc,
948 const IdentifierInfo *Name,
949 SourceLocation NameLoc,
950 TemplateArgumentListInfo &Args,
951 bool AllowInjectedClassName) {
952 // Rebuild the template name.
953 // TODO: avoid TemplateName abstraction
955 SS.Adopt(QualifierLoc);
956 TemplateName InstName
957 = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(),
958 nullptr, AllowInjectedClassName);
960 if (InstName.isNull())
963 // If it's still dependent, make a dependent specialization.
964 if (InstName.getAsDependentTemplateName())
965 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
966 QualifierLoc.getNestedNameSpecifier(),
970 // Otherwise, make an elaborated type wrapping a non-dependent
973 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
974 if (T.isNull()) return QualType();
976 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
979 return SemaRef.Context.getElaboratedType(Keyword,
980 QualifierLoc.getNestedNameSpecifier(),
984 /// \brief Build a new typename type that refers to an identifier.
986 /// By default, performs semantic analysis when building the typename type
987 /// (or elaborated type). Subclasses may override this routine to provide
988 /// different behavior.
989 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
990 SourceLocation KeywordLoc,
991 NestedNameSpecifierLoc QualifierLoc,
992 const IdentifierInfo *Id,
993 SourceLocation IdLoc,
994 bool DeducedTSTContext) {
996 SS.Adopt(QualifierLoc);
998 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
999 // If the name is still dependent, just build a new dependent name type.
1000 if (!SemaRef.computeDeclContext(SS))
1001 return SemaRef.Context.getDependentNameType(Keyword,
1002 QualifierLoc.getNestedNameSpecifier(),
1006 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1007 QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1009 // If a dependent name resolves to a deduced template specialization type,
1010 // check that we're in one of the syntactic contexts permitting it.
1011 if (!DeducedTSTContext) {
1012 if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1013 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1014 SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1015 << (int)SemaRef.getTemplateNameKindForDiagnostics(
1016 Deduced->getTemplateName())
1017 << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1018 if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1019 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1026 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1028 // We had a dependent elaborated-type-specifier that has been transformed
1029 // into a non-dependent elaborated-type-specifier. Find the tag we're
1031 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1032 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1036 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1039 TagDecl *Tag = nullptr;
1040 SemaRef.LookupQualifiedName(Result, DC);
1041 switch (Result.getResultKind()) {
1042 case LookupResult::NotFound:
1043 case LookupResult::NotFoundInCurrentInstantiation:
1046 case LookupResult::Found:
1047 Tag = Result.getAsSingle<TagDecl>();
1050 case LookupResult::FoundOverloaded:
1051 case LookupResult::FoundUnresolvedValue:
1052 llvm_unreachable("Tag lookup cannot find non-tags");
1054 case LookupResult::Ambiguous:
1055 // Let the LookupResult structure handle ambiguities.
1060 // Check where the name exists but isn't a tag type and use that to emit
1061 // better diagnostics.
1062 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1063 SemaRef.LookupQualifiedName(Result, DC);
1064 switch (Result.getResultKind()) {
1065 case LookupResult::Found:
1066 case LookupResult::FoundOverloaded:
1067 case LookupResult::FoundUnresolvedValue: {
1068 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1069 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1070 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1072 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1076 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1077 << Kind << Id << DC << QualifierLoc.getSourceRange();
1083 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1085 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1086 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1090 // Build the elaborated-type-specifier type.
1091 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1092 return SemaRef.Context.getElaboratedType(Keyword,
1093 QualifierLoc.getNestedNameSpecifier(),
1097 /// \brief Build a new pack expansion type.
1099 /// By default, builds a new PackExpansionType type from the given pattern.
1100 /// Subclasses may override this routine to provide different behavior.
1101 QualType RebuildPackExpansionType(QualType Pattern,
1102 SourceRange PatternRange,
1103 SourceLocation EllipsisLoc,
1104 Optional<unsigned> NumExpansions) {
1105 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1109 /// \brief Build a new atomic type given its value type.
1111 /// By default, performs semantic analysis when building the atomic type.
1112 /// Subclasses may override this routine to provide different behavior.
1113 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1115 /// \brief Build a new pipe type given its value type.
1116 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1119 /// \brief Build a new template name given a nested name specifier, a flag
1120 /// indicating whether the "template" keyword was provided, and the template
1121 /// that the template name refers to.
1123 /// By default, builds the new template name directly. Subclasses may override
1124 /// this routine to provide different behavior.
1125 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1127 TemplateDecl *Template);
1129 /// \brief Build a new template name given a nested name specifier and the
1130 /// name that is referred to as a template.
1132 /// By default, performs semantic analysis to determine whether the name can
1133 /// be resolved to a specific template, then builds the appropriate kind of
1134 /// template name. Subclasses may override this routine to provide different
1136 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1137 const IdentifierInfo &Name,
1138 SourceLocation NameLoc,
1139 QualType ObjectType,
1140 NamedDecl *FirstQualifierInScope,
1141 bool AllowInjectedClassName);
1143 /// \brief Build a new template name given a nested name specifier and the
1144 /// overloaded operator name that is referred to as a template.
1146 /// By default, performs semantic analysis to determine whether the name can
1147 /// be resolved to a specific template, then builds the appropriate kind of
1148 /// template name. Subclasses may override this routine to provide different
1150 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1151 OverloadedOperatorKind Operator,
1152 SourceLocation NameLoc,
1153 QualType ObjectType,
1154 bool AllowInjectedClassName);
1156 /// \brief Build a new template name given a template template parameter pack
1159 /// By default, performs semantic analysis to determine whether the name can
1160 /// be resolved to a specific template, then builds the appropriate kind of
1161 /// template name. Subclasses may override this routine to provide different
1163 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1164 const TemplateArgument &ArgPack) {
1165 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1168 /// \brief Build a new compound statement.
1170 /// By default, performs semantic analysis to build the new statement.
1171 /// Subclasses may override this routine to provide different behavior.
1172 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1173 MultiStmtArg Statements,
1174 SourceLocation RBraceLoc,
1176 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1180 /// \brief Build a new case statement.
1182 /// By default, performs semantic analysis to build the new statement.
1183 /// Subclasses may override this routine to provide different behavior.
1184 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1186 SourceLocation EllipsisLoc,
1188 SourceLocation ColonLoc) {
1189 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1193 /// \brief Attach the body to a new case statement.
1195 /// By default, performs semantic analysis to build the new statement.
1196 /// Subclasses may override this routine to provide different behavior.
1197 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1198 getSema().ActOnCaseStmtBody(S, Body);
1202 /// \brief Build a new default statement.
1204 /// By default, performs semantic analysis to build the new statement.
1205 /// Subclasses may override this routine to provide different behavior.
1206 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1207 SourceLocation ColonLoc,
1209 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1210 /*CurScope=*/nullptr);
1213 /// \brief Build a new label statement.
1215 /// By default, performs semantic analysis to build the new statement.
1216 /// Subclasses may override this routine to provide different behavior.
1217 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1218 SourceLocation ColonLoc, Stmt *SubStmt) {
1219 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1222 /// \brief Build a new label statement.
1224 /// By default, performs semantic analysis to build the new statement.
1225 /// Subclasses may override this routine to provide different behavior.
1226 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1227 ArrayRef<const Attr*> Attrs,
1229 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1232 /// \brief Build a new "if" statement.
1234 /// By default, performs semantic analysis to build the new statement.
1235 /// Subclasses may override this routine to provide different behavior.
1236 StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1237 Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1238 SourceLocation ElseLoc, Stmt *Else) {
1239 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1243 /// \brief Start building a new switch statement.
1245 /// By default, performs semantic analysis to build the new statement.
1246 /// Subclasses may override this routine to provide different behavior.
1247 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1248 Sema::ConditionResult Cond) {
1249 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1252 /// \brief Attach the body to the switch statement.
1254 /// By default, performs semantic analysis to build the new statement.
1255 /// Subclasses may override this routine to provide different behavior.
1256 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1257 Stmt *Switch, Stmt *Body) {
1258 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1261 /// \brief Build a new while statement.
1263 /// By default, performs semantic analysis to build the new statement.
1264 /// Subclasses may override this routine to provide different behavior.
1265 StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1266 Sema::ConditionResult Cond, Stmt *Body) {
1267 return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1270 /// \brief Build a new do-while statement.
1272 /// By default, performs semantic analysis to build the new statement.
1273 /// Subclasses may override this routine to provide different behavior.
1274 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1275 SourceLocation WhileLoc, SourceLocation LParenLoc,
1276 Expr *Cond, SourceLocation RParenLoc) {
1277 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1281 /// \brief Build a new for statement.
1283 /// By default, performs semantic analysis to build the new statement.
1284 /// Subclasses may override this routine to provide different behavior.
1285 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1286 Stmt *Init, Sema::ConditionResult Cond,
1287 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1289 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1290 Inc, RParenLoc, Body);
1293 /// \brief Build a new goto statement.
1295 /// By default, performs semantic analysis to build the new statement.
1296 /// Subclasses may override this routine to provide different behavior.
1297 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1299 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1302 /// \brief Build a new indirect goto statement.
1304 /// By default, performs semantic analysis to build the new statement.
1305 /// Subclasses may override this routine to provide different behavior.
1306 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1307 SourceLocation StarLoc,
1309 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1312 /// \brief Build a new return statement.
1314 /// By default, performs semantic analysis to build the new statement.
1315 /// Subclasses may override this routine to provide different behavior.
1316 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1317 return getSema().BuildReturnStmt(ReturnLoc, Result);
1320 /// \brief Build a new declaration statement.
1322 /// By default, performs semantic analysis to build the new statement.
1323 /// Subclasses may override this routine to provide different behavior.
1324 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1325 SourceLocation StartLoc, SourceLocation EndLoc) {
1326 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1327 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1330 /// \brief Build a new inline asm statement.
1332 /// By default, performs semantic analysis to build the new statement.
1333 /// Subclasses may override this routine to provide different behavior.
1334 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1335 bool IsVolatile, unsigned NumOutputs,
1336 unsigned NumInputs, IdentifierInfo **Names,
1337 MultiExprArg Constraints, MultiExprArg Exprs,
1338 Expr *AsmString, MultiExprArg Clobbers,
1339 SourceLocation RParenLoc) {
1340 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1341 NumInputs, Names, Constraints, Exprs,
1342 AsmString, Clobbers, RParenLoc);
1345 /// \brief Build a new MS style inline asm statement.
1347 /// By default, performs semantic analysis to build the new statement.
1348 /// Subclasses may override this routine to provide different behavior.
1349 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1350 ArrayRef<Token> AsmToks,
1351 StringRef AsmString,
1352 unsigned NumOutputs, unsigned NumInputs,
1353 ArrayRef<StringRef> Constraints,
1354 ArrayRef<StringRef> Clobbers,
1355 ArrayRef<Expr*> Exprs,
1356 SourceLocation EndLoc) {
1357 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1358 NumOutputs, NumInputs,
1359 Constraints, Clobbers, Exprs, EndLoc);
1362 /// \brief Build a new co_return statement.
1364 /// By default, performs semantic analysis to build the new statement.
1365 /// Subclasses may override this routine to provide different behavior.
1366 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1368 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1371 /// \brief Build a new co_await expression.
1373 /// By default, performs semantic analysis to build the new expression.
1374 /// Subclasses may override this routine to provide different behavior.
1375 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1377 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1380 /// \brief Build a new co_await expression.
1382 /// By default, performs semantic analysis to build the new expression.
1383 /// Subclasses may override this routine to provide different behavior.
1384 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1386 UnresolvedLookupExpr *Lookup) {
1387 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1390 /// \brief Build a new co_yield expression.
1392 /// By default, performs semantic analysis to build the new expression.
1393 /// Subclasses may override this routine to provide different behavior.
1394 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1395 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1398 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1399 return getSema().BuildCoroutineBodyStmt(Args);
1402 /// \brief Build a new Objective-C \@try statement.
1404 /// By default, performs semantic analysis to build the new statement.
1405 /// Subclasses may override this routine to provide different behavior.
1406 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1408 MultiStmtArg CatchStmts,
1410 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1414 /// \brief Rebuild an Objective-C exception declaration.
1416 /// By default, performs semantic analysis to build the new declaration.
1417 /// Subclasses may override this routine to provide different behavior.
1418 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1419 TypeSourceInfo *TInfo, QualType T) {
1420 return getSema().BuildObjCExceptionDecl(TInfo, T,
1421 ExceptionDecl->getInnerLocStart(),
1422 ExceptionDecl->getLocation(),
1423 ExceptionDecl->getIdentifier());
1426 /// \brief Build a new Objective-C \@catch statement.
1428 /// By default, performs semantic analysis to build the new statement.
1429 /// Subclasses may override this routine to provide different behavior.
1430 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1431 SourceLocation RParenLoc,
1434 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1438 /// \brief Build a new Objective-C \@finally statement.
1440 /// By default, performs semantic analysis to build the new statement.
1441 /// Subclasses may override this routine to provide different behavior.
1442 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1444 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1447 /// \brief Build a new Objective-C \@throw statement.
1449 /// By default, performs semantic analysis to build the new statement.
1450 /// Subclasses may override this routine to provide different behavior.
1451 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1453 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1456 /// \brief Build a new OpenMP executable directive.
1458 /// By default, performs semantic analysis to build the new statement.
1459 /// Subclasses may override this routine to provide different behavior.
1460 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1461 DeclarationNameInfo DirName,
1462 OpenMPDirectiveKind CancelRegion,
1463 ArrayRef<OMPClause *> Clauses,
1464 Stmt *AStmt, SourceLocation StartLoc,
1465 SourceLocation EndLoc) {
1466 return getSema().ActOnOpenMPExecutableDirective(
1467 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1470 /// \brief Build a new OpenMP 'if' clause.
1472 /// By default, performs semantic analysis to build the new OpenMP clause.
1473 /// Subclasses may override this routine to provide different behavior.
1474 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1475 Expr *Condition, SourceLocation StartLoc,
1476 SourceLocation LParenLoc,
1477 SourceLocation NameModifierLoc,
1478 SourceLocation ColonLoc,
1479 SourceLocation EndLoc) {
1480 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1481 LParenLoc, NameModifierLoc, ColonLoc,
1485 /// \brief Build a new OpenMP 'final' clause.
1487 /// By default, performs semantic analysis to build the new OpenMP clause.
1488 /// Subclasses may override this routine to provide different behavior.
1489 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1490 SourceLocation LParenLoc,
1491 SourceLocation EndLoc) {
1492 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1496 /// \brief Build a new OpenMP 'num_threads' clause.
1498 /// By default, performs semantic analysis to build the new OpenMP clause.
1499 /// Subclasses may override this routine to provide different behavior.
1500 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1501 SourceLocation StartLoc,
1502 SourceLocation LParenLoc,
1503 SourceLocation EndLoc) {
1504 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1508 /// \brief Build a new OpenMP 'safelen' clause.
1510 /// By default, performs semantic analysis to build the new OpenMP clause.
1511 /// Subclasses may override this routine to provide different behavior.
1512 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1513 SourceLocation LParenLoc,
1514 SourceLocation EndLoc) {
1515 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1518 /// \brief Build a new OpenMP 'simdlen' 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 *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1523 SourceLocation LParenLoc,
1524 SourceLocation EndLoc) {
1525 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1528 /// \brief Build a new OpenMP 'collapse' clause.
1530 /// By default, performs semantic analysis to build the new OpenMP clause.
1531 /// Subclasses may override this routine to provide different behavior.
1532 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1533 SourceLocation LParenLoc,
1534 SourceLocation EndLoc) {
1535 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1539 /// \brief Build a new OpenMP 'default' clause.
1541 /// By default, performs semantic analysis to build the new OpenMP clause.
1542 /// Subclasses may override this routine to provide different behavior.
1543 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1544 SourceLocation KindKwLoc,
1545 SourceLocation StartLoc,
1546 SourceLocation LParenLoc,
1547 SourceLocation EndLoc) {
1548 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1549 StartLoc, LParenLoc, EndLoc);
1552 /// \brief Build a new OpenMP 'proc_bind' clause.
1554 /// By default, performs semantic analysis to build the new OpenMP clause.
1555 /// Subclasses may override this routine to provide different behavior.
1556 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1557 SourceLocation KindKwLoc,
1558 SourceLocation StartLoc,
1559 SourceLocation LParenLoc,
1560 SourceLocation EndLoc) {
1561 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1562 StartLoc, LParenLoc, EndLoc);
1565 /// \brief Build a new OpenMP 'schedule' clause.
1567 /// By default, performs semantic analysis to build the new OpenMP clause.
1568 /// Subclasses may override this routine to provide different behavior.
1569 OMPClause *RebuildOMPScheduleClause(
1570 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1571 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1572 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1573 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1574 return getSema().ActOnOpenMPScheduleClause(
1575 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1579 /// \brief Build a new OpenMP 'ordered' clause.
1581 /// By default, performs semantic analysis to build the new OpenMP clause.
1582 /// Subclasses may override this routine to provide different behavior.
1583 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1584 SourceLocation EndLoc,
1585 SourceLocation LParenLoc, Expr *Num) {
1586 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1589 /// \brief Build a new OpenMP 'private' clause.
1591 /// By default, performs semantic analysis to build the new OpenMP clause.
1592 /// Subclasses may override this routine to provide different behavior.
1593 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1594 SourceLocation StartLoc,
1595 SourceLocation LParenLoc,
1596 SourceLocation EndLoc) {
1597 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1601 /// \brief Build a new OpenMP 'firstprivate' clause.
1603 /// By default, performs semantic analysis to build the new OpenMP clause.
1604 /// Subclasses may override this routine to provide different behavior.
1605 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1606 SourceLocation StartLoc,
1607 SourceLocation LParenLoc,
1608 SourceLocation EndLoc) {
1609 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1613 /// \brief Build a new OpenMP 'lastprivate' clause.
1615 /// By default, performs semantic analysis to build the new OpenMP clause.
1616 /// Subclasses may override this routine to provide different behavior.
1617 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1618 SourceLocation StartLoc,
1619 SourceLocation LParenLoc,
1620 SourceLocation EndLoc) {
1621 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1625 /// \brief Build a new OpenMP 'shared' clause.
1627 /// By default, performs semantic analysis to build the new OpenMP clause.
1628 /// Subclasses may override this routine to provide different behavior.
1629 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1630 SourceLocation StartLoc,
1631 SourceLocation LParenLoc,
1632 SourceLocation EndLoc) {
1633 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1637 /// \brief Build a new OpenMP 'reduction' clause.
1639 /// By default, performs semantic analysis to build the new statement.
1640 /// Subclasses may override this routine to provide different behavior.
1641 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1642 SourceLocation StartLoc,
1643 SourceLocation LParenLoc,
1644 SourceLocation ColonLoc,
1645 SourceLocation EndLoc,
1646 CXXScopeSpec &ReductionIdScopeSpec,
1647 const DeclarationNameInfo &ReductionId,
1648 ArrayRef<Expr *> UnresolvedReductions) {
1649 return getSema().ActOnOpenMPReductionClause(
1650 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1651 ReductionId, UnresolvedReductions);
1654 /// \brief Build a new OpenMP 'linear' clause.
1656 /// By default, performs semantic analysis to build the new OpenMP clause.
1657 /// Subclasses may override this routine to provide different behavior.
1658 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1659 SourceLocation StartLoc,
1660 SourceLocation LParenLoc,
1661 OpenMPLinearClauseKind Modifier,
1662 SourceLocation ModifierLoc,
1663 SourceLocation ColonLoc,
1664 SourceLocation EndLoc) {
1665 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1666 Modifier, ModifierLoc, ColonLoc,
1670 /// \brief Build a new OpenMP 'aligned' clause.
1672 /// By default, performs semantic analysis to build the new OpenMP clause.
1673 /// Subclasses may override this routine to provide different behavior.
1674 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1675 SourceLocation StartLoc,
1676 SourceLocation LParenLoc,
1677 SourceLocation ColonLoc,
1678 SourceLocation EndLoc) {
1679 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1680 LParenLoc, ColonLoc, EndLoc);
1683 /// \brief Build a new OpenMP 'copyin' clause.
1685 /// By default, performs semantic analysis to build the new OpenMP clause.
1686 /// Subclasses may override this routine to provide different behavior.
1687 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1688 SourceLocation StartLoc,
1689 SourceLocation LParenLoc,
1690 SourceLocation EndLoc) {
1691 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1695 /// \brief Build a new OpenMP 'copyprivate' clause.
1697 /// By default, performs semantic analysis to build the new OpenMP clause.
1698 /// Subclasses may override this routine to provide different behavior.
1699 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1700 SourceLocation StartLoc,
1701 SourceLocation LParenLoc,
1702 SourceLocation EndLoc) {
1703 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1707 /// \brief Build a new OpenMP 'flush' pseudo clause.
1709 /// By default, performs semantic analysis to build the new OpenMP clause.
1710 /// Subclasses may override this routine to provide different behavior.
1711 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1712 SourceLocation StartLoc,
1713 SourceLocation LParenLoc,
1714 SourceLocation EndLoc) {
1715 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1719 /// \brief Build a new OpenMP 'depend' pseudo clause.
1721 /// By default, performs semantic analysis to build the new OpenMP clause.
1722 /// Subclasses may override this routine to provide different behavior.
1724 RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1725 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1726 SourceLocation StartLoc, SourceLocation LParenLoc,
1727 SourceLocation EndLoc) {
1728 return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1729 StartLoc, LParenLoc, EndLoc);
1732 /// \brief Build a new OpenMP 'device' clause.
1734 /// By default, performs semantic analysis to build the new statement.
1735 /// Subclasses may override this routine to provide different behavior.
1736 OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1737 SourceLocation LParenLoc,
1738 SourceLocation EndLoc) {
1739 return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1743 /// \brief Build a new OpenMP 'map' clause.
1745 /// By default, performs semantic analysis to build the new OpenMP clause.
1746 /// Subclasses may override this routine to provide different behavior.
1748 RebuildOMPMapClause(OpenMPMapClauseKind MapTypeModifier,
1749 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1750 SourceLocation MapLoc, SourceLocation ColonLoc,
1751 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1752 SourceLocation LParenLoc, SourceLocation EndLoc) {
1753 return getSema().ActOnOpenMPMapClause(MapTypeModifier, MapType,
1754 IsMapTypeImplicit, MapLoc, ColonLoc,
1755 VarList, StartLoc, LParenLoc, EndLoc);
1758 /// \brief Build a new OpenMP 'num_teams' clause.
1760 /// By default, performs semantic analysis to build the new statement.
1761 /// Subclasses may override this routine to provide different behavior.
1762 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1763 SourceLocation LParenLoc,
1764 SourceLocation EndLoc) {
1765 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1769 /// \brief Build a new OpenMP 'thread_limit' clause.
1771 /// By default, performs semantic analysis to build the new statement.
1772 /// Subclasses may override this routine to provide different behavior.
1773 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1774 SourceLocation StartLoc,
1775 SourceLocation LParenLoc,
1776 SourceLocation EndLoc) {
1777 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1781 /// \brief Build a new OpenMP 'priority' clause.
1783 /// By default, performs semantic analysis to build the new statement.
1784 /// Subclasses may override this routine to provide different behavior.
1785 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1786 SourceLocation LParenLoc,
1787 SourceLocation EndLoc) {
1788 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1792 /// \brief Build a new OpenMP 'grainsize' clause.
1794 /// By default, performs semantic analysis to build the new statement.
1795 /// Subclasses may override this routine to provide different behavior.
1796 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1797 SourceLocation LParenLoc,
1798 SourceLocation EndLoc) {
1799 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1803 /// \brief Build a new OpenMP 'num_tasks' clause.
1805 /// By default, performs semantic analysis to build the new statement.
1806 /// Subclasses may override this routine to provide different behavior.
1807 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1808 SourceLocation LParenLoc,
1809 SourceLocation EndLoc) {
1810 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1814 /// \brief Build a new OpenMP 'hint' clause.
1816 /// By default, performs semantic analysis to build the new statement.
1817 /// Subclasses may override this routine to provide different behavior.
1818 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1819 SourceLocation LParenLoc,
1820 SourceLocation EndLoc) {
1821 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1824 /// \brief Build a new OpenMP 'dist_schedule' clause.
1826 /// By default, performs semantic analysis to build the new OpenMP clause.
1827 /// Subclasses may override this routine to provide different behavior.
1829 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1830 Expr *ChunkSize, SourceLocation StartLoc,
1831 SourceLocation LParenLoc, SourceLocation KindLoc,
1832 SourceLocation CommaLoc, SourceLocation EndLoc) {
1833 return getSema().ActOnOpenMPDistScheduleClause(
1834 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1837 /// \brief Build a new OpenMP 'to' clause.
1839 /// By default, performs semantic analysis to build the new statement.
1840 /// Subclasses may override this routine to provide different behavior.
1841 OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1842 SourceLocation StartLoc,
1843 SourceLocation LParenLoc,
1844 SourceLocation EndLoc) {
1845 return getSema().ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
1848 /// \brief Build a new OpenMP 'from' clause.
1850 /// By default, performs semantic analysis to build the new statement.
1851 /// Subclasses may override this routine to provide different behavior.
1852 OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1853 SourceLocation StartLoc,
1854 SourceLocation LParenLoc,
1855 SourceLocation EndLoc) {
1856 return getSema().ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc,
1860 /// Build a new OpenMP 'use_device_ptr' clause.
1862 /// By default, performs semantic analysis to build the new OpenMP clause.
1863 /// Subclasses may override this routine to provide different behavior.
1864 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1865 SourceLocation StartLoc,
1866 SourceLocation LParenLoc,
1867 SourceLocation EndLoc) {
1868 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc,
1872 /// Build a new OpenMP 'is_device_ptr' clause.
1874 /// By default, performs semantic analysis to build the new OpenMP clause.
1875 /// Subclasses may override this routine to provide different behavior.
1876 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1877 SourceLocation StartLoc,
1878 SourceLocation LParenLoc,
1879 SourceLocation EndLoc) {
1880 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc,
1884 /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
1886 /// By default, performs semantic analysis to build the new statement.
1887 /// Subclasses may override this routine to provide different behavior.
1888 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1890 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1893 /// \brief Build a new Objective-C \@synchronized statement.
1895 /// By default, performs semantic analysis to build the new statement.
1896 /// Subclasses may override this routine to provide different behavior.
1897 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1898 Expr *Object, Stmt *Body) {
1899 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1902 /// \brief Build a new Objective-C \@autoreleasepool statement.
1904 /// By default, performs semantic analysis to build the new statement.
1905 /// Subclasses may override this routine to provide different behavior.
1906 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1908 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1911 /// \brief Build a new Objective-C fast enumeration statement.
1913 /// By default, performs semantic analysis to build the new statement.
1914 /// Subclasses may override this routine to provide different behavior.
1915 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1918 SourceLocation RParenLoc,
1920 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1924 if (ForEachStmt.isInvalid())
1927 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
1930 /// \brief Build a new C++ exception declaration.
1932 /// By default, performs semantic analysis to build the new decaration.
1933 /// Subclasses may override this routine to provide different behavior.
1934 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1935 TypeSourceInfo *Declarator,
1936 SourceLocation StartLoc,
1937 SourceLocation IdLoc,
1938 IdentifierInfo *Id) {
1939 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
1940 StartLoc, IdLoc, Id);
1942 getSema().CurContext->addDecl(Var);
1946 /// \brief Build a new C++ catch statement.
1948 /// By default, performs semantic analysis to build the new statement.
1949 /// Subclasses may override this routine to provide different behavior.
1950 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
1951 VarDecl *ExceptionDecl,
1953 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
1957 /// \brief Build a new C++ try statement.
1959 /// By default, performs semantic analysis to build the new statement.
1960 /// Subclasses may override this routine to provide different behavior.
1961 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
1962 ArrayRef<Stmt *> Handlers) {
1963 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
1966 /// \brief Build a new C++0x range-based for statement.
1968 /// By default, performs semantic analysis to build the new statement.
1969 /// Subclasses may override this routine to provide different behavior.
1970 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
1971 SourceLocation CoawaitLoc,
1972 SourceLocation ColonLoc,
1973 Stmt *Range, Stmt *Begin, Stmt *End,
1974 Expr *Cond, Expr *Inc,
1976 SourceLocation RParenLoc) {
1977 // If we've just learned that the range is actually an Objective-C
1978 // collection, treat this as an Objective-C fast enumeration loop.
1979 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
1980 if (RangeStmt->isSingleDecl()) {
1981 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
1982 if (RangeVar->isInvalidDecl())
1985 Expr *RangeExpr = RangeVar->getInit();
1986 if (!RangeExpr->isTypeDependent() &&
1987 RangeExpr->getType()->isObjCObjectPointerType())
1988 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
1994 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc,
1996 Cond, Inc, LoopVar, RParenLoc,
1997 Sema::BFRK_Rebuild);
2000 /// \brief Build a new C++0x range-based for statement.
2002 /// By default, performs semantic analysis to build the new statement.
2003 /// Subclasses may override this routine to provide different behavior.
2004 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2006 NestedNameSpecifierLoc QualifierLoc,
2007 DeclarationNameInfo NameInfo,
2009 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2010 QualifierLoc, NameInfo, Nested);
2013 /// \brief Attach body to a C++0x range-based for statement.
2015 /// By default, performs semantic analysis to finish the new statement.
2016 /// Subclasses may override this routine to provide different behavior.
2017 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2018 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2021 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2022 Stmt *TryBlock, Stmt *Handler) {
2023 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2026 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2028 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2031 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2032 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2035 /// \brief Build a new predefined expression.
2037 /// By default, performs semantic analysis to build the new expression.
2038 /// Subclasses may override this routine to provide different behavior.
2039 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2040 PredefinedExpr::IdentType IT) {
2041 return getSema().BuildPredefinedExpr(Loc, IT);
2044 /// \brief Build a new expression that references a declaration.
2046 /// By default, performs semantic analysis to build the new expression.
2047 /// Subclasses may override this routine to provide different behavior.
2048 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2051 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2055 /// \brief Build a new expression that references a declaration.
2057 /// By default, performs semantic analysis to build the new expression.
2058 /// Subclasses may override this routine to provide different behavior.
2059 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2061 const DeclarationNameInfo &NameInfo,
2062 TemplateArgumentListInfo *TemplateArgs) {
2064 SS.Adopt(QualifierLoc);
2066 // FIXME: loses template args.
2068 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
2071 /// \brief Build a new expression in parentheses.
2073 /// By default, performs semantic analysis to build the new expression.
2074 /// Subclasses may override this routine to provide different behavior.
2075 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2076 SourceLocation RParen) {
2077 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2080 /// \brief Build a new pseudo-destructor expression.
2082 /// By default, performs semantic analysis to build the new expression.
2083 /// Subclasses may override this routine to provide different behavior.
2084 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2085 SourceLocation OperatorLoc,
2088 TypeSourceInfo *ScopeType,
2089 SourceLocation CCLoc,
2090 SourceLocation TildeLoc,
2091 PseudoDestructorTypeStorage Destroyed);
2093 /// \brief Build a new unary operator expression.
2095 /// By default, performs semantic analysis to build the new expression.
2096 /// Subclasses may override this routine to provide different behavior.
2097 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2098 UnaryOperatorKind Opc,
2100 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2103 /// \brief Build a new builtin offsetof expression.
2105 /// By default, performs semantic analysis to build the new expression.
2106 /// Subclasses may override this routine to provide different behavior.
2107 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2108 TypeSourceInfo *Type,
2109 ArrayRef<Sema::OffsetOfComponent> Components,
2110 SourceLocation RParenLoc) {
2111 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2115 /// \brief Build a new sizeof, alignof or vec_step expression with a
2118 /// By default, performs semantic analysis to build the new expression.
2119 /// Subclasses may override this routine to provide different behavior.
2120 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2121 SourceLocation OpLoc,
2122 UnaryExprOrTypeTrait ExprKind,
2124 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2127 /// \brief Build a new sizeof, alignof or vec step expression with an
2128 /// expression argument.
2130 /// By default, performs semantic analysis to build the new expression.
2131 /// Subclasses may override this routine to provide different behavior.
2132 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2133 UnaryExprOrTypeTrait ExprKind,
2136 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2137 if (Result.isInvalid())
2143 /// \brief Build a new array subscript expression.
2145 /// By default, performs semantic analysis to build the new expression.
2146 /// Subclasses may override this routine to provide different behavior.
2147 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2148 SourceLocation LBracketLoc,
2150 SourceLocation RBracketLoc) {
2151 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2156 /// \brief Build a new array section expression.
2158 /// By default, performs semantic analysis to build the new expression.
2159 /// Subclasses may override this routine to provide different behavior.
2160 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2162 SourceLocation ColonLoc, Expr *Length,
2163 SourceLocation RBracketLoc) {
2164 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2165 ColonLoc, Length, RBracketLoc);
2168 /// \brief Build a new call expression.
2170 /// By default, performs semantic analysis to build the new expression.
2171 /// Subclasses may override this routine to provide different behavior.
2172 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2174 SourceLocation RParenLoc,
2175 Expr *ExecConfig = nullptr) {
2176 return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
2177 Args, RParenLoc, ExecConfig);
2180 /// \brief Build a new member access expression.
2182 /// By default, performs semantic analysis to build the new expression.
2183 /// Subclasses may override this routine to provide different behavior.
2184 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2186 NestedNameSpecifierLoc QualifierLoc,
2187 SourceLocation TemplateKWLoc,
2188 const DeclarationNameInfo &MemberNameInfo,
2190 NamedDecl *FoundDecl,
2191 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2192 NamedDecl *FirstQualifierInScope) {
2193 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2195 if (!Member->getDeclName()) {
2196 // We have a reference to an unnamed field. This is always the
2197 // base of an anonymous struct/union member access, i.e. the
2198 // field is always of record type.
2199 assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
2200 assert(Member->getType()->isRecordType() &&
2201 "unnamed member not of record type?");
2204 getSema().PerformObjectMemberConversion(BaseResult.get(),
2205 QualifierLoc.getNestedNameSpecifier(),
2207 if (BaseResult.isInvalid())
2209 Base = BaseResult.get();
2210 ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
2211 MemberExpr *ME = new (getSema().Context)
2212 MemberExpr(Base, isArrow, OpLoc, Member, MemberNameInfo,
2213 cast<FieldDecl>(Member)->getType(), VK, OK_Ordinary);
2218 SS.Adopt(QualifierLoc);
2220 Base = BaseResult.get();
2221 QualType BaseType = Base->getType();
2223 // FIXME: this involves duplicating earlier analysis in a lot of
2224 // cases; we should avoid this when possible.
2225 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2226 R.addDecl(FoundDecl);
2229 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2231 FirstQualifierInScope,
2232 R, ExplicitTemplateArgs,
2236 /// \brief Build a new binary operator expression.
2238 /// By default, performs semantic analysis to build the new expression.
2239 /// Subclasses may override this routine to provide different behavior.
2240 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2241 BinaryOperatorKind Opc,
2242 Expr *LHS, Expr *RHS) {
2243 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2246 /// \brief Build a new conditional operator expression.
2248 /// By default, performs semantic analysis to build the new expression.
2249 /// Subclasses may override this routine to provide different behavior.
2250 ExprResult RebuildConditionalOperator(Expr *Cond,
2251 SourceLocation QuestionLoc,
2253 SourceLocation ColonLoc,
2255 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2259 /// \brief Build a new C-style cast expression.
2261 /// By default, performs semantic analysis to build the new expression.
2262 /// Subclasses may override this routine to provide different behavior.
2263 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2264 TypeSourceInfo *TInfo,
2265 SourceLocation RParenLoc,
2267 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2271 /// \brief Build a new compound literal expression.
2273 /// By default, performs semantic analysis to build the new expression.
2274 /// Subclasses may override this routine to provide different behavior.
2275 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2276 TypeSourceInfo *TInfo,
2277 SourceLocation RParenLoc,
2279 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2283 /// \brief Build a new extended vector element access expression.
2285 /// By default, performs semantic analysis to build the new expression.
2286 /// Subclasses may override this routine to provide different behavior.
2287 ExprResult RebuildExtVectorElementExpr(Expr *Base,
2288 SourceLocation OpLoc,
2289 SourceLocation AccessorLoc,
2290 IdentifierInfo &Accessor) {
2293 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2294 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2295 OpLoc, /*IsArrow*/ false,
2296 SS, SourceLocation(),
2297 /*FirstQualifierInScope*/ nullptr,
2299 /* TemplateArgs */ nullptr,
2303 /// \brief Build a new initializer list expression.
2305 /// By default, performs semantic analysis to build the new expression.
2306 /// Subclasses may override this routine to provide different behavior.
2307 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2309 SourceLocation RBraceLoc,
2310 QualType ResultTy) {
2312 = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
2313 if (Result.isInvalid() || ResultTy->isDependentType())
2316 // Patch in the result type we were given, which may have been computed
2317 // when the initial InitListExpr was built.
2318 InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
2319 ILE->setType(ResultTy);
2323 /// \brief Build a new designated initializer expression.
2325 /// By default, performs semantic analysis to build the new expression.
2326 /// Subclasses may override this routine to provide different behavior.
2327 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2328 MultiExprArg ArrayExprs,
2329 SourceLocation EqualOrColonLoc,
2333 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2335 if (Result.isInvalid())
2341 /// \brief Build a new value-initialized expression.
2343 /// By default, builds the implicit value initialization without performing
2344 /// any semantic analysis. Subclasses may override this routine to provide
2345 /// different behavior.
2346 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2347 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2350 /// \brief Build a new \c va_arg expression.
2352 /// By default, performs semantic analysis to build the new expression.
2353 /// Subclasses may override this routine to provide different behavior.
2354 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2355 Expr *SubExpr, TypeSourceInfo *TInfo,
2356 SourceLocation RParenLoc) {
2357 return getSema().BuildVAArgExpr(BuiltinLoc,
2362 /// \brief Build a new expression list in parentheses.
2364 /// By default, performs semantic analysis to build the new expression.
2365 /// Subclasses may override this routine to provide different behavior.
2366 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2367 MultiExprArg SubExprs,
2368 SourceLocation RParenLoc) {
2369 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2372 /// \brief Build a new address-of-label expression.
2374 /// By default, performs semantic analysis, using the name of the label
2375 /// rather than attempting to map the label statement itself.
2376 /// Subclasses may override this routine to provide different behavior.
2377 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2378 SourceLocation LabelLoc, LabelDecl *Label) {
2379 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2382 /// \brief Build a new GNU statement expression.
2384 /// By default, performs semantic analysis to build the new expression.
2385 /// Subclasses may override this routine to provide different behavior.
2386 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2388 SourceLocation RParenLoc) {
2389 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2392 /// \brief Build a new __builtin_choose_expr expression.
2394 /// By default, performs semantic analysis to build the new expression.
2395 /// Subclasses may override this routine to provide different behavior.
2396 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2397 Expr *Cond, Expr *LHS, Expr *RHS,
2398 SourceLocation RParenLoc) {
2399 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2404 /// \brief Build a new generic selection expression.
2406 /// By default, performs semantic analysis to build the new expression.
2407 /// Subclasses may override this routine to provide different behavior.
2408 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2409 SourceLocation DefaultLoc,
2410 SourceLocation RParenLoc,
2411 Expr *ControllingExpr,
2412 ArrayRef<TypeSourceInfo *> Types,
2413 ArrayRef<Expr *> Exprs) {
2414 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2415 ControllingExpr, Types, Exprs);
2418 /// \brief Build a new overloaded operator call expression.
2420 /// By default, performs semantic analysis to build the new expression.
2421 /// The semantic analysis provides the behavior of template instantiation,
2422 /// copying with transformations that turn what looks like an overloaded
2423 /// operator call into a use of a builtin operator, performing
2424 /// argument-dependent lookup, etc. Subclasses may override this routine to
2425 /// provide different behavior.
2426 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2427 SourceLocation OpLoc,
2432 /// \brief Build a new C++ "named" cast expression, such as static_cast or
2433 /// reinterpret_cast.
2435 /// By default, this routine dispatches to one of the more-specific routines
2436 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2437 /// Subclasses may override this routine to provide different behavior.
2438 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2439 Stmt::StmtClass Class,
2440 SourceLocation LAngleLoc,
2441 TypeSourceInfo *TInfo,
2442 SourceLocation RAngleLoc,
2443 SourceLocation LParenLoc,
2445 SourceLocation RParenLoc) {
2447 case Stmt::CXXStaticCastExprClass:
2448 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2449 RAngleLoc, LParenLoc,
2450 SubExpr, RParenLoc);
2452 case Stmt::CXXDynamicCastExprClass:
2453 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2454 RAngleLoc, LParenLoc,
2455 SubExpr, RParenLoc);
2457 case Stmt::CXXReinterpretCastExprClass:
2458 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2459 RAngleLoc, LParenLoc,
2463 case Stmt::CXXConstCastExprClass:
2464 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2465 RAngleLoc, LParenLoc,
2466 SubExpr, RParenLoc);
2469 llvm_unreachable("Invalid C++ named cast");
2473 /// \brief Build a new C++ static_cast expression.
2475 /// By default, performs semantic analysis to build the new expression.
2476 /// Subclasses may override this routine to provide different behavior.
2477 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2478 SourceLocation LAngleLoc,
2479 TypeSourceInfo *TInfo,
2480 SourceLocation RAngleLoc,
2481 SourceLocation LParenLoc,
2483 SourceLocation RParenLoc) {
2484 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2486 SourceRange(LAngleLoc, RAngleLoc),
2487 SourceRange(LParenLoc, RParenLoc));
2490 /// \brief Build a new C++ dynamic_cast expression.
2492 /// By default, performs semantic analysis to build the new expression.
2493 /// Subclasses may override this routine to provide different behavior.
2494 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2495 SourceLocation LAngleLoc,
2496 TypeSourceInfo *TInfo,
2497 SourceLocation RAngleLoc,
2498 SourceLocation LParenLoc,
2500 SourceLocation RParenLoc) {
2501 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2503 SourceRange(LAngleLoc, RAngleLoc),
2504 SourceRange(LParenLoc, RParenLoc));
2507 /// \brief Build a new C++ reinterpret_cast expression.
2509 /// By default, performs semantic analysis to build the new expression.
2510 /// Subclasses may override this routine to provide different behavior.
2511 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2512 SourceLocation LAngleLoc,
2513 TypeSourceInfo *TInfo,
2514 SourceLocation RAngleLoc,
2515 SourceLocation LParenLoc,
2517 SourceLocation RParenLoc) {
2518 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2520 SourceRange(LAngleLoc, RAngleLoc),
2521 SourceRange(LParenLoc, RParenLoc));
2524 /// \brief Build a new C++ const_cast expression.
2526 /// By default, performs semantic analysis to build the new expression.
2527 /// Subclasses may override this routine to provide different behavior.
2528 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2529 SourceLocation LAngleLoc,
2530 TypeSourceInfo *TInfo,
2531 SourceLocation RAngleLoc,
2532 SourceLocation LParenLoc,
2534 SourceLocation RParenLoc) {
2535 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2537 SourceRange(LAngleLoc, RAngleLoc),
2538 SourceRange(LParenLoc, RParenLoc));
2541 /// \brief Build a new C++ functional-style cast expression.
2543 /// By default, performs semantic analysis to build the new expression.
2544 /// Subclasses may override this routine to provide different behavior.
2545 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2546 SourceLocation LParenLoc,
2548 SourceLocation RParenLoc) {
2549 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2550 MultiExprArg(&Sub, 1),
2554 /// \brief Build a new C++ typeid(type) expression.
2556 /// By default, performs semantic analysis to build the new expression.
2557 /// Subclasses may override this routine to provide different behavior.
2558 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2559 SourceLocation TypeidLoc,
2560 TypeSourceInfo *Operand,
2561 SourceLocation RParenLoc) {
2562 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2567 /// \brief Build a new C++ typeid(expr) expression.
2569 /// By default, performs semantic analysis to build the new expression.
2570 /// Subclasses may override this routine to provide different behavior.
2571 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2572 SourceLocation TypeidLoc,
2574 SourceLocation RParenLoc) {
2575 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2579 /// \brief Build a new C++ __uuidof(type) expression.
2581 /// By default, performs semantic analysis to build the new expression.
2582 /// Subclasses may override this routine to provide different behavior.
2583 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2584 SourceLocation TypeidLoc,
2585 TypeSourceInfo *Operand,
2586 SourceLocation RParenLoc) {
2587 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2591 /// \brief Build a new C++ __uuidof(expr) expression.
2593 /// By default, performs semantic analysis to build the new expression.
2594 /// Subclasses may override this routine to provide different behavior.
2595 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2596 SourceLocation TypeidLoc,
2598 SourceLocation RParenLoc) {
2599 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2603 /// \brief Build a new C++ "this" expression.
2605 /// By default, builds a new "this" expression without performing any
2606 /// semantic analysis. Subclasses may override this routine to provide
2607 /// different behavior.
2608 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2611 getSema().CheckCXXThisCapture(ThisLoc);
2612 return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
2615 /// \brief Build a new C++ throw expression.
2617 /// By default, performs semantic analysis to build the new expression.
2618 /// Subclasses may override this routine to provide different behavior.
2619 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2620 bool IsThrownVariableInScope) {
2621 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2624 /// \brief Build a new C++ default-argument expression.
2626 /// By default, builds a new default-argument expression, which does not
2627 /// require any semantic analysis. Subclasses may override this routine to
2628 /// provide different behavior.
2629 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
2630 ParmVarDecl *Param) {
2631 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
2634 /// \brief Build a new C++11 default-initialization expression.
2636 /// By default, builds a new default field initialization expression, which
2637 /// does not require any semantic analysis. Subclasses may override this
2638 /// routine to provide different behavior.
2639 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2641 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
2644 /// \brief Build a new C++ zero-initialization expression.
2646 /// By default, performs semantic analysis to build the new expression.
2647 /// Subclasses may override this routine to provide different behavior.
2648 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2649 SourceLocation LParenLoc,
2650 SourceLocation RParenLoc) {
2651 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
2655 /// \brief Build a new C++ "new" expression.
2657 /// By default, performs semantic analysis to build the new expression.
2658 /// Subclasses may override this routine to provide different behavior.
2659 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2661 SourceLocation PlacementLParen,
2662 MultiExprArg PlacementArgs,
2663 SourceLocation PlacementRParen,
2664 SourceRange TypeIdParens,
2665 QualType AllocatedType,
2666 TypeSourceInfo *AllocatedTypeInfo,
2668 SourceRange DirectInitRange,
2669 Expr *Initializer) {
2670 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2682 /// \brief Build a new C++ "delete" expression.
2684 /// By default, performs semantic analysis to build the new expression.
2685 /// Subclasses may override this routine to provide different behavior.
2686 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2687 bool IsGlobalDelete,
2690 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2694 /// \brief Build a new type trait expression.
2696 /// By default, performs semantic analysis to build the new expression.
2697 /// Subclasses may override this routine to provide different behavior.
2698 ExprResult RebuildTypeTrait(TypeTrait Trait,
2699 SourceLocation StartLoc,
2700 ArrayRef<TypeSourceInfo *> Args,
2701 SourceLocation RParenLoc) {
2702 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2705 /// \brief Build a new array type trait expression.
2707 /// By default, performs semantic analysis to build the new expression.
2708 /// Subclasses may override this routine to provide different behavior.
2709 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2710 SourceLocation StartLoc,
2711 TypeSourceInfo *TSInfo,
2713 SourceLocation RParenLoc) {
2714 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2717 /// \brief Build a new expression trait expression.
2719 /// By default, performs semantic analysis to build the new expression.
2720 /// Subclasses may override this routine to provide different behavior.
2721 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2722 SourceLocation StartLoc,
2724 SourceLocation RParenLoc) {
2725 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2728 /// \brief Build a new (previously unresolved) declaration reference
2731 /// By default, performs semantic analysis to build the new expression.
2732 /// Subclasses may override this routine to provide different behavior.
2733 ExprResult RebuildDependentScopeDeclRefExpr(
2734 NestedNameSpecifierLoc QualifierLoc,
2735 SourceLocation TemplateKWLoc,
2736 const DeclarationNameInfo &NameInfo,
2737 const TemplateArgumentListInfo *TemplateArgs,
2738 bool IsAddressOfOperand,
2739 TypeSourceInfo **RecoveryTSI) {
2741 SS.Adopt(QualifierLoc);
2743 if (TemplateArgs || TemplateKWLoc.isValid())
2744 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2747 return getSema().BuildQualifiedDeclarationNameExpr(
2748 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2751 /// \brief Build a new template-id expression.
2753 /// By default, performs semantic analysis to build the new expression.
2754 /// Subclasses may override this routine to provide different behavior.
2755 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2756 SourceLocation TemplateKWLoc,
2759 const TemplateArgumentListInfo *TemplateArgs) {
2760 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2764 /// \brief Build a new object-construction expression.
2766 /// By default, performs semantic analysis to build the new expression.
2767 /// Subclasses may override this routine to provide different behavior.
2768 ExprResult RebuildCXXConstructExpr(QualType T,
2770 CXXConstructorDecl *Constructor,
2773 bool HadMultipleCandidates,
2774 bool ListInitialization,
2775 bool StdInitListInitialization,
2776 bool RequiresZeroInit,
2777 CXXConstructExpr::ConstructionKind ConstructKind,
2778 SourceRange ParenRange) {
2779 SmallVector<Expr*, 8> ConvertedArgs;
2780 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2784 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2787 HadMultipleCandidates,
2789 StdInitListInitialization,
2790 RequiresZeroInit, ConstructKind,
2794 /// \brief Build a new implicit construction via inherited constructor
2796 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2797 CXXConstructorDecl *Constructor,
2798 bool ConstructsVBase,
2799 bool InheritedFromVBase) {
2800 return new (getSema().Context) CXXInheritedCtorInitExpr(
2801 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2804 /// \brief Build a new object-construction expression.
2806 /// By default, performs semantic analysis to build the new expression.
2807 /// Subclasses may override this routine to provide different behavior.
2808 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2809 SourceLocation LParenLoc,
2811 SourceLocation RParenLoc) {
2812 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2818 /// \brief Build a new object-construction expression.
2820 /// By default, performs semantic analysis to build the new expression.
2821 /// Subclasses may override this routine to provide different behavior.
2822 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2823 SourceLocation LParenLoc,
2825 SourceLocation RParenLoc) {
2826 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2832 /// \brief Build a new member reference expression.
2834 /// By default, performs semantic analysis to build the new expression.
2835 /// Subclasses may override this routine to provide different behavior.
2836 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2839 SourceLocation OperatorLoc,
2840 NestedNameSpecifierLoc QualifierLoc,
2841 SourceLocation TemplateKWLoc,
2842 NamedDecl *FirstQualifierInScope,
2843 const DeclarationNameInfo &MemberNameInfo,
2844 const TemplateArgumentListInfo *TemplateArgs) {
2846 SS.Adopt(QualifierLoc);
2848 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2849 OperatorLoc, IsArrow,
2851 FirstQualifierInScope,
2853 TemplateArgs, /*S*/nullptr);
2856 /// \brief Build a new member reference expression.
2858 /// By default, performs semantic analysis to build the new expression.
2859 /// Subclasses may override this routine to provide different behavior.
2860 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2861 SourceLocation OperatorLoc,
2863 NestedNameSpecifierLoc QualifierLoc,
2864 SourceLocation TemplateKWLoc,
2865 NamedDecl *FirstQualifierInScope,
2867 const TemplateArgumentListInfo *TemplateArgs) {
2869 SS.Adopt(QualifierLoc);
2871 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2872 OperatorLoc, IsArrow,
2874 FirstQualifierInScope,
2875 R, TemplateArgs, /*S*/nullptr);
2878 /// \brief Build a new noexcept expression.
2880 /// By default, performs semantic analysis to build the new expression.
2881 /// Subclasses may override this routine to provide different behavior.
2882 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2883 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2886 /// \brief Build a new expression to compute the length of a parameter pack.
2887 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
2889 SourceLocation PackLoc,
2890 SourceLocation RParenLoc,
2891 Optional<unsigned> Length,
2892 ArrayRef<TemplateArgument> PartialArgs) {
2893 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
2894 RParenLoc, Length, PartialArgs);
2897 /// \brief Build a new Objective-C boxed expression.
2899 /// By default, performs semantic analysis to build the new expression.
2900 /// Subclasses may override this routine to provide different behavior.
2901 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
2902 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
2905 /// \brief Build a new Objective-C array literal.
2907 /// By default, performs semantic analysis to build the new expression.
2908 /// Subclasses may override this routine to provide different behavior.
2909 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
2910 Expr **Elements, unsigned NumElements) {
2911 return getSema().BuildObjCArrayLiteral(Range,
2912 MultiExprArg(Elements, NumElements));
2915 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
2916 Expr *Base, Expr *Key,
2917 ObjCMethodDecl *getterMethod,
2918 ObjCMethodDecl *setterMethod) {
2919 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
2920 getterMethod, setterMethod);
2923 /// \brief Build a new Objective-C dictionary literal.
2925 /// By default, performs semantic analysis to build the new expression.
2926 /// Subclasses may override this routine to provide different behavior.
2927 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
2928 MutableArrayRef<ObjCDictionaryElement> Elements) {
2929 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
2932 /// \brief Build a new Objective-C \@encode expression.
2934 /// By default, performs semantic analysis to build the new expression.
2935 /// Subclasses may override this routine to provide different behavior.
2936 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2937 TypeSourceInfo *EncodeTypeInfo,
2938 SourceLocation RParenLoc) {
2939 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
2942 /// \brief Build a new Objective-C class message.
2943 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2945 ArrayRef<SourceLocation> SelectorLocs,
2946 ObjCMethodDecl *Method,
2947 SourceLocation LBracLoc,
2949 SourceLocation RBracLoc) {
2950 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
2951 ReceiverTypeInfo->getType(),
2952 /*SuperLoc=*/SourceLocation(),
2953 Sel, Method, LBracLoc, SelectorLocs,
2957 /// \brief Build a new Objective-C instance message.
2958 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
2960 ArrayRef<SourceLocation> SelectorLocs,
2961 ObjCMethodDecl *Method,
2962 SourceLocation LBracLoc,
2964 SourceLocation RBracLoc) {
2965 return SemaRef.BuildInstanceMessage(Receiver,
2966 Receiver->getType(),
2967 /*SuperLoc=*/SourceLocation(),
2968 Sel, Method, LBracLoc, SelectorLocs,
2972 /// \brief Build a new Objective-C instance/class message to 'super'.
2973 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
2975 ArrayRef<SourceLocation> SelectorLocs,
2977 ObjCMethodDecl *Method,
2978 SourceLocation LBracLoc,
2980 SourceLocation RBracLoc) {
2981 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
2984 Sel, Method, LBracLoc, SelectorLocs,
2986 : SemaRef.BuildClassMessage(nullptr,
2989 Sel, Method, LBracLoc, SelectorLocs,
2995 /// \brief Build a new Objective-C ivar reference expression.
2997 /// By default, performs semantic analysis to build the new expression.
2998 /// Subclasses may override this routine to provide different behavior.
2999 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3000 SourceLocation IvarLoc,
3001 bool IsArrow, bool IsFreeIvar) {
3003 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3004 ExprResult Result = getSema().BuildMemberReferenceExpr(
3005 BaseArg, BaseArg->getType(),
3006 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3007 /*FirstQualifierInScope=*/nullptr, NameInfo,
3008 /*TemplateArgs=*/nullptr,
3010 if (IsFreeIvar && Result.isUsable())
3011 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3015 /// \brief Build a new Objective-C property reference expression.
3017 /// By default, performs semantic analysis to build the new expression.
3018 /// Subclasses may override this routine to provide different behavior.
3019 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3020 ObjCPropertyDecl *Property,
3021 SourceLocation PropertyLoc) {
3023 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3024 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3025 /*FIXME:*/PropertyLoc,
3027 SS, SourceLocation(),
3028 /*FirstQualifierInScope=*/nullptr,
3030 /*TemplateArgs=*/nullptr,
3034 /// \brief Build a new Objective-C property reference expression.
3036 /// By default, performs semantic analysis to build the new expression.
3037 /// Subclasses may override this routine to provide different behavior.
3038 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3039 ObjCMethodDecl *Getter,
3040 ObjCMethodDecl *Setter,
3041 SourceLocation PropertyLoc) {
3042 // Since these expressions can only be value-dependent, we do not
3043 // need to perform semantic analysis again.
3045 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3046 VK_LValue, OK_ObjCProperty,
3047 PropertyLoc, Base));
3050 /// \brief Build a new Objective-C "isa" expression.
3052 /// By default, performs semantic analysis to build the new expression.
3053 /// Subclasses may override this routine to provide different behavior.
3054 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3055 SourceLocation OpLoc, bool IsArrow) {
3057 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3058 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3060 SS, SourceLocation(),
3061 /*FirstQualifierInScope=*/nullptr,
3063 /*TemplateArgs=*/nullptr,
3067 /// \brief Build a new shuffle vector expression.
3069 /// By default, performs semantic analysis to build the new expression.
3070 /// Subclasses may override this routine to provide different behavior.
3071 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3072 MultiExprArg SubExprs,
3073 SourceLocation RParenLoc) {
3074 // Find the declaration for __builtin_shufflevector
3075 const IdentifierInfo &Name
3076 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3077 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3078 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3079 assert(!Lookup.empty() && "No __builtin_shufflevector?");
3081 // Build a reference to the __builtin_shufflevector builtin
3082 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3083 Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
3084 SemaRef.Context.BuiltinFnTy,
3085 VK_RValue, BuiltinLoc);
3086 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3087 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3088 CK_BuiltinFnToFnPtr).get();
3090 // Build the CallExpr
3091 ExprResult TheCall = new (SemaRef.Context) CallExpr(
3092 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3093 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3095 // Type-check the __builtin_shufflevector expression.
3096 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3099 /// \brief Build a new convert vector expression.
3100 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3101 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3102 SourceLocation RParenLoc) {
3103 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3104 BuiltinLoc, RParenLoc);
3107 /// \brief Build a new template argument pack expansion.
3109 /// By default, performs semantic analysis to build a new pack expansion
3110 /// for a template argument. Subclasses may override this routine to provide
3111 /// different behavior.
3112 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3113 SourceLocation EllipsisLoc,
3114 Optional<unsigned> NumExpansions) {
3115 switch (Pattern.getArgument().getKind()) {
3116 case TemplateArgument::Expression: {
3118 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3119 EllipsisLoc, NumExpansions);
3120 if (Result.isInvalid())
3121 return TemplateArgumentLoc();
3123 return TemplateArgumentLoc(Result.get(), Result.get());
3126 case TemplateArgument::Template:
3127 return TemplateArgumentLoc(TemplateArgument(
3128 Pattern.getArgument().getAsTemplate(),
3130 Pattern.getTemplateQualifierLoc(),
3131 Pattern.getTemplateNameLoc(),
3134 case TemplateArgument::Null:
3135 case TemplateArgument::Integral:
3136 case TemplateArgument::Declaration:
3137 case TemplateArgument::Pack:
3138 case TemplateArgument::TemplateExpansion:
3139 case TemplateArgument::NullPtr:
3140 llvm_unreachable("Pack expansion pattern has no parameter packs");
3142 case TemplateArgument::Type:
3143 if (TypeSourceInfo *Expansion
3144 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3147 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3152 return TemplateArgumentLoc();
3155 /// \brief Build a new expression pack expansion.
3157 /// By default, performs semantic analysis to build a new pack expansion
3158 /// for an expression. Subclasses may override this routine to provide
3159 /// different behavior.
3160 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3161 Optional<unsigned> NumExpansions) {
3162 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3165 /// \brief Build a new C++1z fold-expression.
3167 /// By default, performs semantic analysis in order to build a new fold
3169 ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3170 BinaryOperatorKind Operator,
3171 SourceLocation EllipsisLoc, Expr *RHS,
3172 SourceLocation RParenLoc) {
3173 return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3177 /// \brief Build an empty C++1z fold-expression with the given operator.
3179 /// By default, produces the fallback value for the fold-expression, or
3180 /// produce an error if there is no fallback value.
3181 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3182 BinaryOperatorKind Operator) {
3183 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3186 /// \brief Build a new atomic operation expression.
3188 /// By default, performs semantic analysis to build the new expression.
3189 /// Subclasses may override this routine to provide different behavior.
3190 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
3191 MultiExprArg SubExprs,
3193 AtomicExpr::AtomicOp Op,
3194 SourceLocation RParenLoc) {
3195 // Just create the expression; there is not any interesting semantic
3196 // analysis here because we can't actually build an AtomicExpr until
3197 // we are sure it is semantically sound.
3198 return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
3203 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3204 QualType ObjectType,
3205 NamedDecl *FirstQualifierInScope,
3208 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3209 QualType ObjectType,
3210 NamedDecl *FirstQualifierInScope,
3213 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3214 NamedDecl *FirstQualifierInScope,
3217 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3218 DependentNameTypeLoc TL,
3219 bool DeducibleTSTContext);
3222 template<typename Derived>
3223 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
3227 switch (S->getStmtClass()) {
3228 case Stmt::NoStmtClass: break;
3230 // Transform individual statement nodes
3231 #define STMT(Node, Parent) \
3232 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3233 #define ABSTRACT_STMT(Node)
3234 #define EXPR(Node, Parent)
3235 #include "clang/AST/StmtNodes.inc"
3237 // Transform expressions by calling TransformExpr.
3238 #define STMT(Node, Parent)
3239 #define ABSTRACT_STMT(Stmt)
3240 #define EXPR(Node, Parent) case Stmt::Node##Class:
3241 #include "clang/AST/StmtNodes.inc"
3243 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3247 return getSema().ActOnExprStmt(E);
3254 template<typename Derived>
3255 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3259 switch (S->getClauseKind()) {
3261 // Transform individual clause nodes
3262 #define OPENMP_CLAUSE(Name, Class) \
3263 case OMPC_ ## Name : \
3264 return getDerived().Transform ## Class(cast<Class>(S));
3265 #include "clang/Basic/OpenMPKinds.def"
3272 template<typename Derived>
3273 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3277 switch (E->getStmtClass()) {
3278 case Stmt::NoStmtClass: break;
3279 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3280 #define ABSTRACT_STMT(Stmt)
3281 #define EXPR(Node, Parent) \
3282 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3283 #include "clang/AST/StmtNodes.inc"
3289 template<typename Derived>
3290 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3292 // Initializers are instantiated like expressions, except that various outer
3293 // layers are stripped.
3297 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
3298 Init = ExprTemp->getSubExpr();
3300 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3301 Init = AIL->getCommonExpr();
3303 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3304 Init = MTE->GetTemporaryExpr();
3306 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3307 Init = Binder->getSubExpr();
3309 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3310 Init = ICE->getSubExprAsWritten();
3312 if (CXXStdInitializerListExpr *ILE =
3313 dyn_cast<CXXStdInitializerListExpr>(Init))
3314 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3316 // If this is copy-initialization, we only need to reconstruct
3317 // InitListExprs. Other forms of copy-initialization will be a no-op if
3318 // the initializer is already the right type.
3319 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3320 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3321 return getDerived().TransformExpr(Init);
3323 // Revert value-initialization back to empty parens.
3324 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3325 SourceRange Parens = VIE->getSourceRange();
3326 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3330 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3331 if (isa<ImplicitValueInitExpr>(Init))
3332 return getDerived().RebuildParenListExpr(SourceLocation(), None,
3335 // Revert initialization by constructor back to a parenthesized or braced list
3336 // of expressions. Any other form of initializer can just be reused directly.
3337 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3338 return getDerived().TransformExpr(Init);
3340 // If the initialization implicitly converted an initializer list to a
3341 // std::initializer_list object, unwrap the std::initializer_list too.
3342 if (Construct && Construct->isStdInitListInitialization())
3343 return TransformInitializer(Construct->getArg(0), NotCopyInit);
3345 SmallVector<Expr*, 8> NewArgs;
3346 bool ArgChanged = false;
3347 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3348 /*IsCall*/true, NewArgs, &ArgChanged))
3351 // If this was list initialization, revert to list form.
3352 if (Construct->isListInitialization())
3353 return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
3354 Construct->getLocEnd(),
3355 Construct->getType());
3357 // Build a ParenListExpr to represent anything else.
3358 SourceRange Parens = Construct->getParenOrBraceRange();
3359 if (Parens.isInvalid()) {
3360 // This was a variable declaration's initialization for which no initializer
3362 assert(NewArgs.empty() &&
3363 "no parens or braces but have direct init with arguments?");
3366 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3370 template<typename Derived>
3371 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3374 SmallVectorImpl<Expr *> &Outputs,
3376 for (unsigned I = 0; I != NumInputs; ++I) {
3377 // If requested, drop call arguments that need to be dropped.
3378 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3385 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3386 Expr *Pattern = Expansion->getPattern();
3388 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3389 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3390 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3392 // Determine whether the set of unexpanded parameter packs can and should
3395 bool RetainExpansion = false;
3396 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3397 Optional<unsigned> NumExpansions = OrigNumExpansions;
3398 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3399 Pattern->getSourceRange(),
3401 Expand, RetainExpansion,
3406 // The transform has determined that we should perform a simple
3407 // transformation on the pack expansion, producing another pack
3409 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3410 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3411 if (OutPattern.isInvalid())
3414 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3415 Expansion->getEllipsisLoc(),
3417 if (Out.isInvalid())
3422 Outputs.push_back(Out.get());
3426 // Record right away that the argument was changed. This needs
3427 // to happen even if the array expands to nothing.
3428 if (ArgChanged) *ArgChanged = true;
3430 // The transform has determined that we should perform an elementwise
3431 // expansion of the pattern. Do so.
3432 for (unsigned I = 0; I != *NumExpansions; ++I) {
3433 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3434 ExprResult Out = getDerived().TransformExpr(Pattern);
3435 if (Out.isInvalid())
3438 if (Out.get()->containsUnexpandedParameterPack()) {
3439 Out = getDerived().RebuildPackExpansion(
3440 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3441 if (Out.isInvalid())
3445 Outputs.push_back(Out.get());
3448 // If we're supposed to retain a pack expansion, do so by temporarily
3449 // forgetting the partially-substituted parameter pack.
3450 if (RetainExpansion) {
3451 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3453 ExprResult Out = getDerived().TransformExpr(Pattern);
3454 if (Out.isInvalid())
3457 Out = getDerived().RebuildPackExpansion(
3458 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3459 if (Out.isInvalid())
3462 Outputs.push_back(Out.get());
3469 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3470 : getDerived().TransformExpr(Inputs[I]);
3471 if (Result.isInvalid())
3474 if (Result.get() != Inputs[I] && ArgChanged)
3477 Outputs.push_back(Result.get());
3483 template <typename Derived>
3484 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3485 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3487 VarDecl *ConditionVar = cast_or_null<VarDecl>(
3488 getDerived().TransformDefinition(Var->getLocation(), Var));
3491 return Sema::ConditionError();
3493 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3497 ExprResult CondExpr = getDerived().TransformExpr(Expr);
3499 if (CondExpr.isInvalid())
3500 return Sema::ConditionError();
3502 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3505 return Sema::ConditionResult();
3508 template<typename Derived>
3509 NestedNameSpecifierLoc
3510 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3511 NestedNameSpecifierLoc NNS,
3512 QualType ObjectType,
3513 NamedDecl *FirstQualifierInScope) {
3514 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3515 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3516 Qualifier = Qualifier.getPrefix())
3517 Qualifiers.push_back(Qualifier);
3520 while (!Qualifiers.empty()) {
3521 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3522 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3524 switch (QNNS->getKind()) {
3525 case NestedNameSpecifier::Identifier: {
3526 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3527 Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3528 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3529 SS, FirstQualifierInScope, false))
3530 return NestedNameSpecifierLoc();
3534 case NestedNameSpecifier::Namespace: {
3536 = cast_or_null<NamespaceDecl>(
3537 getDerived().TransformDecl(
3538 Q.getLocalBeginLoc(),
3539 QNNS->getAsNamespace()));
3540 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3544 case NestedNameSpecifier::NamespaceAlias: {
3545 NamespaceAliasDecl *Alias
3546 = cast_or_null<NamespaceAliasDecl>(
3547 getDerived().TransformDecl(Q.getLocalBeginLoc(),
3548 QNNS->getAsNamespaceAlias()));
3549 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3550 Q.getLocalEndLoc());
3554 case NestedNameSpecifier::Global:
3555 // There is no meaningful transformation that one could perform on the
3557 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3560 case NestedNameSpecifier::Super: {
3562 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3563 SourceLocation(), QNNS->getAsRecordDecl()));
3564 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3568 case NestedNameSpecifier::TypeSpecWithTemplate:
3569 case NestedNameSpecifier::TypeSpec: {
3570 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3571 FirstQualifierInScope, SS);
3574 return NestedNameSpecifierLoc();
3576 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3577 (SemaRef.getLangOpts().CPlusPlus11 &&
3578 TL.getType()->isEnumeralType())) {
3579 assert(!TL.getType().hasLocalQualifiers() &&
3580 "Can't get cv-qualifiers here");
3581 if (TL.getType()->isEnumeralType())
3582 SemaRef.Diag(TL.getBeginLoc(),
3583 diag::warn_cxx98_compat_enum_nested_name_spec);
3584 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3585 Q.getLocalEndLoc());
3588 // If the nested-name-specifier is an invalid type def, don't emit an
3589 // error because a previous error should have already been emitted.
3590 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3591 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3592 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3593 << TL.getType() << SS.getRange();
3595 return NestedNameSpecifierLoc();
3599 // The qualifier-in-scope and object type only apply to the leftmost entity.
3600 FirstQualifierInScope = nullptr;
3601 ObjectType = QualType();
3604 // Don't rebuild the nested-name-specifier if we don't have to.
3605 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3606 !getDerived().AlwaysRebuild())
3609 // If we can re-use the source-location data from the original
3610 // nested-name-specifier, do so.
3611 if (SS.location_size() == NNS.getDataLength() &&
3612 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3613 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3615 // Allocate new nested-name-specifier location information.
3616 return SS.getWithLocInContext(SemaRef.Context);
3619 template<typename Derived>
3621 TreeTransform<Derived>
3622 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3623 DeclarationName Name = NameInfo.getName();
3625 return DeclarationNameInfo();
3627 switch (Name.getNameKind()) {
3628 case DeclarationName::Identifier:
3629 case DeclarationName::ObjCZeroArgSelector:
3630 case DeclarationName::ObjCOneArgSelector:
3631 case DeclarationName::ObjCMultiArgSelector:
3632 case DeclarationName::CXXOperatorName:
3633 case DeclarationName::CXXLiteralOperatorName:
3634 case DeclarationName::CXXUsingDirective:
3637 case DeclarationName::CXXDeductionGuideName: {
3638 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3639 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3640 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3642 return DeclarationNameInfo();
3644 DeclarationNameInfo NewNameInfo(NameInfo);
3645 NewNameInfo.setName(
3646 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3650 case DeclarationName::CXXConstructorName:
3651 case DeclarationName::CXXDestructorName:
3652 case DeclarationName::CXXConversionFunctionName: {
3653 TypeSourceInfo *NewTInfo;
3654 CanQualType NewCanTy;
3655 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3656 NewTInfo = getDerived().TransformType(OldTInfo);
3658 return DeclarationNameInfo();
3659 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3663 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3664 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3666 return DeclarationNameInfo();
3667 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3670 DeclarationName NewName
3671 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3673 DeclarationNameInfo NewNameInfo(NameInfo);
3674 NewNameInfo.setName(NewName);
3675 NewNameInfo.setNamedTypeInfo(NewTInfo);
3680 llvm_unreachable("Unknown name kind.");
3683 template<typename Derived>
3685 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3687 SourceLocation NameLoc,
3688 QualType ObjectType,
3689 NamedDecl *FirstQualifierInScope,
3690 bool AllowInjectedClassName) {
3691 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3692 TemplateDecl *Template = QTN->getTemplateDecl();
3693 assert(Template && "qualified template name must refer to a template");
3695 TemplateDecl *TransTemplate
3696 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3699 return TemplateName();
3701 if (!getDerived().AlwaysRebuild() &&
3702 SS.getScopeRep() == QTN->getQualifier() &&
3703 TransTemplate == Template)
3706 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3710 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3711 if (SS.getScopeRep()) {
3712 // These apply to the scope specifier, not the template.
3713 ObjectType = QualType();
3714 FirstQualifierInScope = nullptr;
3717 if (!getDerived().AlwaysRebuild() &&
3718 SS.getScopeRep() == DTN->getQualifier() &&
3719 ObjectType.isNull())
3722 if (DTN->isIdentifier()) {
3723 return getDerived().RebuildTemplateName(SS,
3724 *DTN->getIdentifier(),
3727 FirstQualifierInScope,
3728 AllowInjectedClassName);
3731 return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
3732 ObjectType, AllowInjectedClassName);
3735 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3736 TemplateDecl *TransTemplate
3737 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3740 return TemplateName();
3742 if (!getDerived().AlwaysRebuild() &&
3743 TransTemplate == Template)
3746 return TemplateName(TransTemplate);
3749 if (SubstTemplateTemplateParmPackStorage *SubstPack
3750 = Name.getAsSubstTemplateTemplateParmPack()) {
3751 TemplateTemplateParmDecl *TransParam
3752 = cast_or_null<TemplateTemplateParmDecl>(
3753 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3755 return TemplateName();
3757 if (!getDerived().AlwaysRebuild() &&
3758 TransParam == SubstPack->getParameterPack())
3761 return getDerived().RebuildTemplateName(TransParam,
3762 SubstPack->getArgumentPack());
3765 // These should be getting filtered out before they reach the AST.
3766 llvm_unreachable("overloaded function decl survived to here");
3769 template<typename Derived>
3770 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3771 const TemplateArgument &Arg,
3772 TemplateArgumentLoc &Output) {
3773 SourceLocation Loc = getDerived().getBaseLocation();
3774 switch (Arg.getKind()) {
3775 case TemplateArgument::Null:
3776 llvm_unreachable("null template argument in TreeTransform");
3779 case TemplateArgument::Type:
3780 Output = TemplateArgumentLoc(Arg,
3781 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3785 case TemplateArgument::Template:
3786 case TemplateArgument::TemplateExpansion: {
3787 NestedNameSpecifierLocBuilder Builder;
3788 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3789 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3790 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3791 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3792 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3794 if (Arg.getKind() == TemplateArgument::Template)
3795 Output = TemplateArgumentLoc(Arg,
3796 Builder.getWithLocInContext(SemaRef.Context),
3799 Output = TemplateArgumentLoc(Arg,
3800 Builder.getWithLocInContext(SemaRef.Context),
3806 case TemplateArgument::Expression:
3807 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3810 case TemplateArgument::Declaration:
3811 case TemplateArgument::Integral:
3812 case TemplateArgument::Pack:
3813 case TemplateArgument::NullPtr:
3814 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3819 template<typename Derived>
3820 bool TreeTransform<Derived>::TransformTemplateArgument(
3821 const TemplateArgumentLoc &Input,
3822 TemplateArgumentLoc &Output, bool Uneval) {
3823 const TemplateArgument &Arg = Input.getArgument();
3824 switch (Arg.getKind()) {
3825 case TemplateArgument::Null:
3826 case TemplateArgument::Integral:
3827 case TemplateArgument::Pack:
3828 case TemplateArgument::Declaration:
3829 case TemplateArgument::NullPtr:
3830 llvm_unreachable("Unexpected TemplateArgument");
3832 case TemplateArgument::Type: {
3833 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3835 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3837 DI = getDerived().TransformType(DI);
3838 if (!DI) return true;
3840 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3844 case TemplateArgument::Template: {
3845 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3847 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3853 SS.Adopt(QualifierLoc);
3854 TemplateName Template
3855 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3856 Input.getTemplateNameLoc());
3857 if (Template.isNull())
3860 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3861 Input.getTemplateNameLoc());
3865 case TemplateArgument::TemplateExpansion:
3866 llvm_unreachable("Caller should expand pack expansions");
3868 case TemplateArgument::Expression: {
3869 // Template argument expressions are constant expressions.
3870 EnterExpressionEvaluationContext Unevaluated(
3872 ? Sema::ExpressionEvaluationContext::Unevaluated
3873 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
3875 Expr *InputExpr = Input.getSourceExpression();
3876 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
3878 ExprResult E = getDerived().TransformExpr(InputExpr);
3879 E = SemaRef.ActOnConstantExpression(E);
3880 if (E.isInvalid()) return true;
3881 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
3886 // Work around bogus GCC warning
3890 /// \brief Iterator adaptor that invents template argument location information
3891 /// for each of the template arguments in its underlying iterator.
3892 template<typename Derived, typename InputIterator>
3893 class TemplateArgumentLocInventIterator {
3894 TreeTransform<Derived> &Self;
3898 typedef TemplateArgumentLoc value_type;
3899 typedef TemplateArgumentLoc reference;
3900 typedef typename std::iterator_traits<InputIterator>::difference_type
3902 typedef std::input_iterator_tag iterator_category;
3905 TemplateArgumentLoc Arg;
3908 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
3910 const TemplateArgumentLoc *operator->() const { return &Arg; }
3913 TemplateArgumentLocInventIterator() { }
3915 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
3917 : Self(Self), Iter(Iter) { }
3919 TemplateArgumentLocInventIterator &operator++() {
3924 TemplateArgumentLocInventIterator operator++(int) {
3925 TemplateArgumentLocInventIterator Old(*this);
3930 reference operator*() const {
3931 TemplateArgumentLoc Result;
3932 Self.InventTemplateArgumentLoc(*Iter, Result);
3936 pointer operator->() const { return pointer(**this); }
3938 friend bool operator==(const TemplateArgumentLocInventIterator &X,
3939 const TemplateArgumentLocInventIterator &Y) {
3940 return X.Iter == Y.Iter;
3943 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
3944 const TemplateArgumentLocInventIterator &Y) {
3945 return X.Iter != Y.Iter;
3949 template<typename Derived>
3950 template<typename InputIterator>
3951 bool TreeTransform<Derived>::TransformTemplateArguments(
3952 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
3954 for (; First != Last; ++First) {
3955 TemplateArgumentLoc Out;
3956 TemplateArgumentLoc In = *First;
3958 if (In.getArgument().getKind() == TemplateArgument::Pack) {
3959 // Unpack argument packs, which we translate them into separate
3961 // FIXME: We could do much better if we could guarantee that the
3962 // TemplateArgumentLocInfo for the pack expansion would be usable for
3963 // all of the template arguments in the argument pack.
3964 typedef TemplateArgumentLocInventIterator<Derived,
3965 TemplateArgument::pack_iterator>
3967 if (TransformTemplateArguments(PackLocIterator(*this,
3968 In.getArgument().pack_begin()),
3969 PackLocIterator(*this,
3970 In.getArgument().pack_end()),
3977 if (In.getArgument().isPackExpansion()) {
3978 // We have a pack expansion, for which we will be substituting into
3980 SourceLocation Ellipsis;
3981 Optional<unsigned> OrigNumExpansions;
3982 TemplateArgumentLoc Pattern
3983 = getSema().getTemplateArgumentPackExpansionPattern(
3984 In, Ellipsis, OrigNumExpansions);
3986 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3987 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3988 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3990 // Determine whether the set of unexpanded parameter packs can and should
3993 bool RetainExpansion = false;
3994 Optional<unsigned> NumExpansions = OrigNumExpansions;
3995 if (getDerived().TryExpandParameterPacks(Ellipsis,
3996 Pattern.getSourceRange(),
4004 // The transform has determined that we should perform a simple
4005 // transformation on the pack expansion, producing another pack
4007 TemplateArgumentLoc OutPattern;
4008 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4009 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4012 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4014 if (Out.getArgument().isNull())
4017 Outputs.addArgument(Out);
4021 // The transform has determined that we should perform an elementwise
4022 // expansion of the pattern. Do so.
4023 for (unsigned I = 0; I != *NumExpansions; ++I) {
4024 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4026 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4029 if (Out.getArgument().containsUnexpandedParameterPack()) {
4030 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4032 if (Out.getArgument().isNull())
4036 Outputs.addArgument(Out);
4039 // If we're supposed to retain a pack expansion, do so by temporarily
4040 // forgetting the partially-substituted parameter pack.
4041 if (RetainExpansion) {
4042 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4044 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4047 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4049 if (Out.getArgument().isNull())
4052 Outputs.addArgument(Out);
4059 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4062 Outputs.addArgument(Out);
4069 //===----------------------------------------------------------------------===//
4070 // Type transformation
4071 //===----------------------------------------------------------------------===//
4073 template<typename Derived>
4074 QualType TreeTransform<Derived>::TransformType(QualType T) {
4075 if (getDerived().AlreadyTransformed(T))
4078 // Temporary workaround. All of these transformations should
4079 // eventually turn into transformations on TypeLocs.
4080 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4081 getDerived().getBaseLocation());
4083 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4088 return NewDI->getType();
4091 template<typename Derived>
4092 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4093 // Refine the base location to the type's location.
4094 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4095 getDerived().getBaseEntity());
4096 if (getDerived().AlreadyTransformed(DI->getType()))
4101 TypeLoc TL = DI->getTypeLoc();
4102 TLB.reserve(TL.getFullDataSize());
4104 QualType Result = getDerived().TransformType(TLB, TL);
4105 if (Result.isNull())
4108 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4111 template<typename Derived>
4113 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4114 switch (T.getTypeLocClass()) {
4115 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4116 #define TYPELOC(CLASS, PARENT) \
4117 case TypeLoc::CLASS: \
4118 return getDerived().Transform##CLASS##Type(TLB, \
4119 T.castAs<CLASS##TypeLoc>());
4120 #include "clang/AST/TypeLocNodes.def"
4123 llvm_unreachable("unhandled type loc!");
4126 template<typename Derived>
4127 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4128 if (!isa<DependentNameType>(T))
4129 return TransformType(T);
4131 if (getDerived().AlreadyTransformed(T))
4133 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4134 getDerived().getBaseLocation());
4135 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4136 return NewDI ? NewDI->getType() : QualType();
4139 template<typename Derived>
4141 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4142 if (!isa<DependentNameType>(DI->getType()))
4143 return TransformType(DI);
4145 // Refine the base location to the type's location.
4146 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4147 getDerived().getBaseEntity());
4148 if (getDerived().AlreadyTransformed(DI->getType()))
4153 TypeLoc TL = DI->getTypeLoc();
4154 TLB.reserve(TL.getFullDataSize());
4157 auto QTL = TL.getAs<QualifiedTypeLoc>();
4159 TL = QTL.getUnqualifiedLoc();
4161 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4163 QualType Result = getDerived().TransformDependentNameType(
4164 TLB, DNTL, /*DeducedTSTContext*/true);
4165 if (Result.isNull())
4169 Result = getDerived().RebuildQualifiedType(
4170 Result, QTL.getBeginLoc(), QTL.getType().getLocalQualifiers());
4171 TLB.TypeWasModifiedSafely(Result);
4174 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4177 template<typename Derived>
4179 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4180 QualifiedTypeLoc T) {
4181 Qualifiers Quals = T.getType().getLocalQualifiers();
4183 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4184 if (Result.isNull())
4187 Result = getDerived().RebuildQualifiedType(Result, T.getBeginLoc(), Quals);
4189 // RebuildQualifiedType might have updated the type, but not in a way
4190 // that invalidates the TypeLoc. (There's no location information for
4192 TLB.TypeWasModifiedSafely(Result);
4197 template<typename Derived>
4198 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4202 // [When] adding cv-qualifications on top of the function type [...] the
4203 // cv-qualifiers are ignored.
4205 // when the cv-qualifiers are introduced through the use of a typedef-name
4206 // or decltype-specifier [...] the cv-qualifiers are ignored.
4207 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4208 // applied to a reference type.
4209 // FIXME: This removes all qualifiers, not just cv-qualifiers!
4210 if (T->isFunctionType() || T->isReferenceType())
4213 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4215 if (Quals.hasObjCLifetime()) {
4216 if (!T->isObjCLifetimeType() && !T->isDependentType())
4217 Quals.removeObjCLifetime();
4218 else if (T.getObjCLifetime()) {
4220 // A lifetime qualifier applied to a substituted template parameter
4221 // overrides the lifetime qualifier from the template argument.
4222 const AutoType *AutoTy;
4223 if (const SubstTemplateTypeParmType *SubstTypeParam
4224 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4225 QualType Replacement = SubstTypeParam->getReplacementType();
4226 Qualifiers Qs = Replacement.getQualifiers();
4227 Qs.removeObjCLifetime();
4228 Replacement = SemaRef.Context.getQualifiedType(
4229 Replacement.getUnqualifiedType(), Qs);
4230 T = SemaRef.Context.getSubstTemplateTypeParmType(
4231 SubstTypeParam->getReplacedParameter(), Replacement);
4232 } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4233 // 'auto' types behave the same way as template parameters.
4234 QualType Deduced = AutoTy->getDeducedType();
4235 Qualifiers Qs = Deduced.getQualifiers();
4236 Qs.removeObjCLifetime();
4238 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4239 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4240 AutoTy->isDependentType());
4242 // Otherwise, complain about the addition of a qualifier to an
4243 // already-qualified type.
4244 // FIXME: Why is this check not in Sema::BuildQualifiedType?
4245 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4246 Quals.removeObjCLifetime();
4251 return SemaRef.BuildQualifiedType(T, Loc, Quals);
4254 template<typename Derived>
4256 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4257 QualType ObjectType,
4258 NamedDecl *UnqualLookup,
4260 if (getDerived().AlreadyTransformed(TL.getType()))
4263 TypeSourceInfo *TSI =
4264 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4266 return TSI->getTypeLoc();
4270 template<typename Derived>
4272 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4273 QualType ObjectType,
4274 NamedDecl *UnqualLookup,
4276 if (getDerived().AlreadyTransformed(TSInfo->getType()))
4279 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4283 template <typename Derived>
4284 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4285 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4287 QualType T = TL.getType();
4288 assert(!getDerived().AlreadyTransformed(T));
4293 if (isa<TemplateSpecializationType>(T)) {
4294 TemplateSpecializationTypeLoc SpecTL =
4295 TL.castAs<TemplateSpecializationTypeLoc>();
4297 TemplateName Template = getDerived().TransformTemplateName(
4298 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4299 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4300 if (Template.isNull())
4303 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4305 } else if (isa<DependentTemplateSpecializationType>(T)) {
4306 DependentTemplateSpecializationTypeLoc SpecTL =
4307 TL.castAs<DependentTemplateSpecializationTypeLoc>();
4309 TemplateName Template
4310 = getDerived().RebuildTemplateName(SS,
4311 *SpecTL.getTypePtr()->getIdentifier(),
4312 SpecTL.getTemplateNameLoc(),
4313 ObjectType, UnqualLookup,
4314 /*AllowInjectedClassName*/true);
4315 if (Template.isNull())
4318 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4323 // Nothing special needs to be done for these.
4324 Result = getDerived().TransformType(TLB, TL);
4327 if (Result.isNull())
4330 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4333 template <class TyLoc> static inline
4334 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4335 TyLoc NewT = TLB.push<TyLoc>(T.getType());
4336 NewT.setNameLoc(T.getNameLoc());
4340 template<typename Derived>
4341 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4343 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4344 NewT.setBuiltinLoc(T.getBuiltinLoc());
4345 if (T.needsExtraLocalData())
4346 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4350 template<typename Derived>
4351 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4354 return TransformTypeSpecType(TLB, T);
4357 template <typename Derived>
4358 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4359 AdjustedTypeLoc TL) {
4360 // Adjustments applied during transformation are handled elsewhere.
4361 return getDerived().TransformType(TLB, TL.getOriginalLoc());
4364 template<typename Derived>
4365 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4366 DecayedTypeLoc TL) {
4367 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4368 if (OriginalType.isNull())
4371 QualType Result = TL.getType();
4372 if (getDerived().AlwaysRebuild() ||
4373 OriginalType != TL.getOriginalLoc().getType())
4374 Result = SemaRef.Context.getDecayedType(OriginalType);
4375 TLB.push<DecayedTypeLoc>(Result);
4376 // Nothing to set for DecayedTypeLoc.
4380 template<typename Derived>
4381 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4382 PointerTypeLoc TL) {
4383 QualType PointeeType
4384 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4385 if (PointeeType.isNull())
4388 QualType Result = TL.getType();
4389 if (PointeeType->getAs<ObjCObjectType>()) {
4390 // A dependent pointer type 'T *' has is being transformed such
4391 // that an Objective-C class type is being replaced for 'T'. The
4392 // resulting pointer type is an ObjCObjectPointerType, not a
4394 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4396 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4397 NewT.setStarLoc(TL.getStarLoc());
4401 if (getDerived().AlwaysRebuild() ||
4402 PointeeType != TL.getPointeeLoc().getType()) {
4403 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4404 if (Result.isNull())
4408 // Objective-C ARC can add lifetime qualifiers to the type that we're
4410 TLB.TypeWasModifiedSafely(Result->getPointeeType());
4412 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4413 NewT.setSigilLoc(TL.getSigilLoc());
4417 template<typename Derived>
4419 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4420 BlockPointerTypeLoc TL) {
4421 QualType PointeeType
4422 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4423 if (PointeeType.isNull())
4426 QualType Result = TL.getType();
4427 if (getDerived().AlwaysRebuild() ||
4428 PointeeType != TL.getPointeeLoc().getType()) {
4429 Result = getDerived().RebuildBlockPointerType(PointeeType,
4431 if (Result.isNull())
4435 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4436 NewT.setSigilLoc(TL.getSigilLoc());
4440 /// Transforms a reference type. Note that somewhat paradoxically we
4441 /// don't care whether the type itself is an l-value type or an r-value
4442 /// type; we only care if the type was *written* as an l-value type
4443 /// or an r-value type.
4444 template<typename Derived>
4446 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4447 ReferenceTypeLoc TL) {
4448 const ReferenceType *T = TL.getTypePtr();
4450 // Note that this works with the pointee-as-written.
4451 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4452 if (PointeeType.isNull())
4455 QualType Result = TL.getType();
4456 if (getDerived().AlwaysRebuild() ||
4457 PointeeType != T->getPointeeTypeAsWritten()) {
4458 Result = getDerived().RebuildReferenceType(PointeeType,
4459 T->isSpelledAsLValue(),
4461 if (Result.isNull())
4465 // Objective-C ARC can add lifetime qualifiers to the type that we're
4467 TLB.TypeWasModifiedSafely(
4468 Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4470 // r-value references can be rebuilt as l-value references.
4471 ReferenceTypeLoc NewTL;
4472 if (isa<LValueReferenceType>(Result))
4473 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4475 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4476 NewTL.setSigilLoc(TL.getSigilLoc());
4481 template<typename Derived>
4483 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4484 LValueReferenceTypeLoc TL) {
4485 return TransformReferenceType(TLB, TL);
4488 template<typename Derived>
4490 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4491 RValueReferenceTypeLoc TL) {
4492 return TransformReferenceType(TLB, TL);
4495 template<typename Derived>
4497 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4498 MemberPointerTypeLoc TL) {
4499 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4500 if (PointeeType.isNull())
4503 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4504 TypeSourceInfo *NewClsTInfo = nullptr;
4506 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4511 const MemberPointerType *T = TL.getTypePtr();
4512 QualType OldClsType = QualType(T->getClass(), 0);
4513 QualType NewClsType;
4515 NewClsType = NewClsTInfo->getType();
4517 NewClsType = getDerived().TransformType(OldClsType);
4518 if (NewClsType.isNull())
4522 QualType Result = TL.getType();
4523 if (getDerived().AlwaysRebuild() ||
4524 PointeeType != T->getPointeeType() ||
4525 NewClsType != OldClsType) {
4526 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4528 if (Result.isNull())
4532 // If we had to adjust the pointee type when building a member pointer, make
4533 // sure to push TypeLoc info for it.
4534 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4535 if (MPT && PointeeType != MPT->getPointeeType()) {
4536 assert(isa<AdjustedType>(MPT->getPointeeType()));
4537 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4540 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4541 NewTL.setSigilLoc(TL.getSigilLoc());
4542 NewTL.setClassTInfo(NewClsTInfo);
4547 template<typename Derived>
4549 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4550 ConstantArrayTypeLoc TL) {
4551 const ConstantArrayType *T = TL.getTypePtr();
4552 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4553 if (ElementType.isNull())
4556 QualType Result = TL.getType();
4557 if (getDerived().AlwaysRebuild() ||
4558 ElementType != T->getElementType()) {
4559 Result = getDerived().RebuildConstantArrayType(ElementType,
4560 T->getSizeModifier(),
4562 T->getIndexTypeCVRQualifiers(),
4563 TL.getBracketsRange());
4564 if (Result.isNull())
4568 // We might have either a ConstantArrayType or a VariableArrayType now:
4569 // a ConstantArrayType is allowed to have an element type which is a
4570 // VariableArrayType if the type is dependent. Fortunately, all array
4571 // types have the same location layout.
4572 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4573 NewTL.setLBracketLoc(TL.getLBracketLoc());
4574 NewTL.setRBracketLoc(TL.getRBracketLoc());
4576 Expr *Size = TL.getSizeExpr();
4578 EnterExpressionEvaluationContext Unevaluated(
4579 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4580 Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4581 Size = SemaRef.ActOnConstantExpression(Size).get();
4583 NewTL.setSizeExpr(Size);
4588 template<typename Derived>
4589 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4590 TypeLocBuilder &TLB,
4591 IncompleteArrayTypeLoc TL) {
4592 const IncompleteArrayType *T = TL.getTypePtr();
4593 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4594 if (ElementType.isNull())
4597 QualType Result = TL.getType();
4598 if (getDerived().AlwaysRebuild() ||
4599 ElementType != T->getElementType()) {
4600 Result = getDerived().RebuildIncompleteArrayType(ElementType,
4601 T->getSizeModifier(),
4602 T->getIndexTypeCVRQualifiers(),
4603 TL.getBracketsRange());
4604 if (Result.isNull())
4608 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4609 NewTL.setLBracketLoc(TL.getLBracketLoc());
4610 NewTL.setRBracketLoc(TL.getRBracketLoc());
4611 NewTL.setSizeExpr(nullptr);
4616 template<typename Derived>
4618 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4619 VariableArrayTypeLoc TL) {
4620 const VariableArrayType *T = TL.getTypePtr();
4621 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4622 if (ElementType.isNull())
4625 ExprResult SizeResult;
4627 EnterExpressionEvaluationContext Context(
4628 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4629 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4631 if (SizeResult.isInvalid())
4633 SizeResult = SemaRef.ActOnFinishFullExpr(SizeResult.get());
4634 if (SizeResult.isInvalid())
4637 Expr *Size = SizeResult.get();
4639 QualType Result = TL.getType();
4640 if (getDerived().AlwaysRebuild() ||
4641 ElementType != T->getElementType() ||
4642 Size != T->getSizeExpr()) {
4643 Result = getDerived().RebuildVariableArrayType(ElementType,
4644 T->getSizeModifier(),
4646 T->getIndexTypeCVRQualifiers(),
4647 TL.getBracketsRange());
4648 if (Result.isNull())
4652 // We might have constant size array now, but fortunately it has the same
4654 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4655 NewTL.setLBracketLoc(TL.getLBracketLoc());
4656 NewTL.setRBracketLoc(TL.getRBracketLoc());
4657 NewTL.setSizeExpr(Size);
4662 template<typename Derived>
4664 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4665 DependentSizedArrayTypeLoc TL) {
4666 const DependentSizedArrayType *T = TL.getTypePtr();
4667 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4668 if (ElementType.isNull())
4671 // Array bounds are constant expressions.
4672 EnterExpressionEvaluationContext Unevaluated(
4673 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4675 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4676 Expr *origSize = TL.getSizeExpr();
4677 if (!origSize) origSize = T->getSizeExpr();
4679 ExprResult sizeResult
4680 = getDerived().TransformExpr(origSize);
4681 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4682 if (sizeResult.isInvalid())
4685 Expr *size = sizeResult.get();
4687 QualType Result = TL.getType();
4688 if (getDerived().AlwaysRebuild() ||
4689 ElementType != T->getElementType() ||
4691 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4692 T->getSizeModifier(),
4694 T->getIndexTypeCVRQualifiers(),
4695 TL.getBracketsRange());
4696 if (Result.isNull())
4700 // We might have any sort of array type now, but fortunately they
4701 // all have the same location layout.
4702 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4703 NewTL.setLBracketLoc(TL.getLBracketLoc());
4704 NewTL.setRBracketLoc(TL.getRBracketLoc());
4705 NewTL.setSizeExpr(size);
4710 template<typename Derived>
4711 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4712 TypeLocBuilder &TLB,
4713 DependentSizedExtVectorTypeLoc TL) {
4714 const DependentSizedExtVectorType *T = TL.getTypePtr();
4716 // FIXME: ext vector locs should be nested
4717 QualType ElementType = getDerived().TransformType(T->getElementType());
4718 if (ElementType.isNull())
4721 // Vector sizes are constant expressions.
4722 EnterExpressionEvaluationContext Unevaluated(
4723 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4725 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4726 Size = SemaRef.ActOnConstantExpression(Size);
4727 if (Size.isInvalid())
4730 QualType Result = TL.getType();
4731 if (getDerived().AlwaysRebuild() ||
4732 ElementType != T->getElementType() ||
4733 Size.get() != T->getSizeExpr()) {
4734 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4736 T->getAttributeLoc());
4737 if (Result.isNull())
4741 // Result might be dependent or not.
4742 if (isa<DependentSizedExtVectorType>(Result)) {
4743 DependentSizedExtVectorTypeLoc NewTL
4744 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4745 NewTL.setNameLoc(TL.getNameLoc());
4747 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4748 NewTL.setNameLoc(TL.getNameLoc());
4754 template<typename Derived>
4755 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
4757 const VectorType *T = TL.getTypePtr();
4758 QualType ElementType = getDerived().TransformType(T->getElementType());
4759 if (ElementType.isNull())
4762 QualType Result = TL.getType();
4763 if (getDerived().AlwaysRebuild() ||
4764 ElementType != T->getElementType()) {
4765 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
4766 T->getVectorKind());
4767 if (Result.isNull())
4771 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4772 NewTL.setNameLoc(TL.getNameLoc());
4777 template<typename Derived>
4778 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
4779 ExtVectorTypeLoc TL) {
4780 const VectorType *T = TL.getTypePtr();
4781 QualType ElementType = getDerived().TransformType(T->getElementType());
4782 if (ElementType.isNull())
4785 QualType Result = TL.getType();
4786 if (getDerived().AlwaysRebuild() ||
4787 ElementType != T->getElementType()) {
4788 Result = getDerived().RebuildExtVectorType(ElementType,
4789 T->getNumElements(),
4790 /*FIXME*/ SourceLocation());
4791 if (Result.isNull())
4795 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4796 NewTL.setNameLoc(TL.getNameLoc());
4801 template <typename Derived>
4802 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
4803 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
4804 bool ExpectParameterPack) {
4805 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
4806 TypeSourceInfo *NewDI = nullptr;
4808 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
4809 // If we're substituting into a pack expansion type and we know the
4810 // length we want to expand to, just substitute for the pattern.
4811 TypeLoc OldTL = OldDI->getTypeLoc();
4812 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
4815 TypeLoc NewTL = OldDI->getTypeLoc();
4816 TLB.reserve(NewTL.getFullDataSize());
4818 QualType Result = getDerived().TransformType(TLB,
4819 OldExpansionTL.getPatternLoc());
4820 if (Result.isNull())
4823 Result = RebuildPackExpansionType(Result,
4824 OldExpansionTL.getPatternLoc().getSourceRange(),
4825 OldExpansionTL.getEllipsisLoc(),
4827 if (Result.isNull())
4830 PackExpansionTypeLoc NewExpansionTL
4831 = TLB.push<PackExpansionTypeLoc>(Result);
4832 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
4833 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
4835 NewDI = getDerived().TransformType(OldDI);
4839 if (NewDI == OldDI && indexAdjustment == 0)
4842 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
4843 OldParm->getDeclContext(),
4844 OldParm->getInnerLocStart(),
4845 OldParm->getLocation(),
4846 OldParm->getIdentifier(),
4849 OldParm->getStorageClass(),
4850 /* DefArg */ nullptr);
4851 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
4852 OldParm->getFunctionScopeIndex() + indexAdjustment);
4856 template <typename Derived>
4857 bool TreeTransform<Derived>::TransformFunctionTypeParams(
4858 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
4859 const QualType *ParamTypes,
4860 const FunctionProtoType::ExtParameterInfo *ParamInfos,
4861 SmallVectorImpl<QualType> &OutParamTypes,
4862 SmallVectorImpl<ParmVarDecl *> *PVars,
4863 Sema::ExtParameterInfoBuilder &PInfos) {
4864 int indexAdjustment = 0;
4866 unsigned NumParams = Params.size();
4867 for (unsigned i = 0; i != NumParams; ++i) {
4868 if (ParmVarDecl *OldParm = Params[i]) {
4869 assert(OldParm->getFunctionScopeIndex() == i);
4871 Optional<unsigned> NumExpansions;
4872 ParmVarDecl *NewParm = nullptr;
4873 if (OldParm->isParameterPack()) {
4874 // We have a function parameter pack that may need to be expanded.
4875 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4877 // Find the parameter packs that could be expanded.
4878 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
4879 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
4880 TypeLoc Pattern = ExpansionTL.getPatternLoc();
4881 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
4882 assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
4884 // Determine whether we should expand the parameter packs.
4885 bool ShouldExpand = false;
4886 bool RetainExpansion = false;
4887 Optional<unsigned> OrigNumExpansions =
4888 ExpansionTL.getTypePtr()->getNumExpansions();
4889 NumExpansions = OrigNumExpansions;
4890 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
4891 Pattern.getSourceRange(),
4900 // Expand the function parameter pack into multiple, separate
4902 getDerived().ExpandingFunctionParameterPack(OldParm);
4903 for (unsigned I = 0; I != *NumExpansions; ++I) {
4904 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4905 ParmVarDecl *NewParm
4906 = getDerived().TransformFunctionTypeParam(OldParm,
4909 /*ExpectParameterPack=*/false);
4914 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
4915 OutParamTypes.push_back(NewParm->getType());
4917 PVars->push_back(NewParm);
4920 // If we're supposed to retain a pack expansion, do so by temporarily
4921 // forgetting the partially-substituted parameter pack.
4922 if (RetainExpansion) {
4923 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4924 ParmVarDecl *NewParm
4925 = getDerived().TransformFunctionTypeParam(OldParm,
4928 /*ExpectParameterPack=*/false);
4933 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
4934 OutParamTypes.push_back(NewParm->getType());
4936 PVars->push_back(NewParm);
4939 // The next parameter should have the same adjustment as the
4940 // last thing we pushed, but we post-incremented indexAdjustment
4941 // on every push. Also, if we push nothing, the adjustment should
4945 // We're done with the pack expansion.
4949 // We'll substitute the parameter now without expanding the pack
4951 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4952 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
4955 /*ExpectParameterPack=*/true);
4957 NewParm = getDerived().TransformFunctionTypeParam(
4958 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
4965 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
4966 OutParamTypes.push_back(NewParm->getType());
4968 PVars->push_back(NewParm);
4972 // Deal with the possibility that we don't have a parameter
4973 // declaration for this parameter.
4974 QualType OldType = ParamTypes[i];
4975 bool IsPackExpansion = false;
4976 Optional<unsigned> NumExpansions;
4978 if (const PackExpansionType *Expansion
4979 = dyn_cast<PackExpansionType>(OldType)) {
4980 // We have a function parameter pack that may need to be expanded.
4981 QualType Pattern = Expansion->getPattern();
4982 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4983 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4985 // Determine whether we should expand the parameter packs.
4986 bool ShouldExpand = false;
4987 bool RetainExpansion = false;
4988 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
4997 // Expand the function parameter pack into multiple, separate
4999 for (unsigned I = 0; I != *NumExpansions; ++I) {
5000 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5001 QualType NewType = getDerived().TransformType(Pattern);
5002 if (NewType.isNull())
5005 if (NewType->containsUnexpandedParameterPack()) {
5007 getSema().getASTContext().getPackExpansionType(NewType, None);
5009 if (NewType.isNull())
5014 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5015 OutParamTypes.push_back(NewType);
5017 PVars->push_back(nullptr);
5020 // We're done with the pack expansion.
5024 // If we're supposed to retain a pack expansion, do so by temporarily
5025 // forgetting the partially-substituted parameter pack.
5026 if (RetainExpansion) {
5027 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5028 QualType NewType = getDerived().TransformType(Pattern);
5029 if (NewType.isNull())
5033 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5034 OutParamTypes.push_back(NewType);
5036 PVars->push_back(nullptr);
5039 // We'll substitute the parameter now without expanding the pack
5041 OldType = Expansion->getPattern();
5042 IsPackExpansion = true;
5043 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5044 NewType = getDerived().TransformType(OldType);
5046 NewType = getDerived().TransformType(OldType);
5049 if (NewType.isNull())
5052 if (IsPackExpansion)
5053 NewType = getSema().Context.getPackExpansionType(NewType,
5057 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5058 OutParamTypes.push_back(NewType);
5060 PVars->push_back(nullptr);
5065 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5066 if (ParmVarDecl *parm = (*PVars)[i])
5067 assert(parm->getFunctionScopeIndex() == i);
5074 template<typename Derived>
5076 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5077 FunctionProtoTypeLoc TL) {
5078 SmallVector<QualType, 4> ExceptionStorage;
5079 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5080 return getDerived().TransformFunctionProtoType(
5081 TLB, TL, nullptr, 0,
5082 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5083 return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5084 ExceptionStorage, Changed);
5088 template<typename Derived> template<typename Fn>
5089 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5090 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5091 unsigned ThisTypeQuals, Fn TransformExceptionSpec) {
5093 // Transform the parameters and return type.
5095 // We are required to instantiate the params and return type in source order.
5096 // When the function has a trailing return type, we instantiate the
5097 // parameters before the return type, since the return type can then refer
5098 // to the parameters themselves (via decltype, sizeof, etc.).
5100 SmallVector<QualType, 4> ParamTypes;
5101 SmallVector<ParmVarDecl*, 4> ParamDecls;
5102 Sema::ExtParameterInfoBuilder ExtParamInfos;
5103 const FunctionProtoType *T = TL.getTypePtr();
5105 QualType ResultType;
5107 if (T->hasTrailingReturn()) {
5108 if (getDerived().TransformFunctionTypeParams(
5109 TL.getBeginLoc(), TL.getParams(),
5110 TL.getTypePtr()->param_type_begin(),
5111 T->getExtParameterInfosOrNull(),
5112 ParamTypes, &ParamDecls, ExtParamInfos))
5116 // C++11 [expr.prim.general]p3:
5117 // If a declaration declares a member function or member function
5118 // template of a class X, the expression this is a prvalue of type
5119 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5120 // and the end of the function-definition, member-declarator, or
5122 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5124 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5125 if (ResultType.isNull())
5130 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5131 if (ResultType.isNull())
5134 if (getDerived().TransformFunctionTypeParams(
5135 TL.getBeginLoc(), TL.getParams(),
5136 TL.getTypePtr()->param_type_begin(),
5137 T->getExtParameterInfosOrNull(),
5138 ParamTypes, &ParamDecls, ExtParamInfos))
5142 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5144 bool EPIChanged = false;
5145 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5148 // Handle extended parameter information.
5149 if (auto NewExtParamInfos =
5150 ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5151 if (!EPI.ExtParameterInfos ||
5152 llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5153 != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5156 EPI.ExtParameterInfos = NewExtParamInfos;
5157 } else if (EPI.ExtParameterInfos) {
5159 EPI.ExtParameterInfos = nullptr;
5162 QualType Result = TL.getType();
5163 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5164 T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5165 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5166 if (Result.isNull())
5170 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5171 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5172 NewTL.setLParenLoc(TL.getLParenLoc());
5173 NewTL.setRParenLoc(TL.getRParenLoc());
5174 NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5175 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5176 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5177 NewTL.setParam(i, ParamDecls[i]);
5182 template<typename Derived>
5183 bool TreeTransform<Derived>::TransformExceptionSpec(
5184 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5185 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5186 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5188 // Instantiate a dynamic noexcept expression, if any.
5189 if (ESI.Type == EST_ComputedNoexcept) {
5190 EnterExpressionEvaluationContext Unevaluated(
5191 getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5192 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5193 if (NoexceptExpr.isInvalid())
5196 // FIXME: This is bogus, a noexcept expression is not a condition.
5197 NoexceptExpr = getSema().CheckBooleanCondition(Loc, NoexceptExpr.get());
5198 if (NoexceptExpr.isInvalid())
5201 if (!NoexceptExpr.get()->isValueDependent()) {
5202 NoexceptExpr = getSema().VerifyIntegerConstantExpression(
5203 NoexceptExpr.get(), nullptr,
5204 diag::err_noexcept_needs_constant_expression,
5205 /*AllowFold*/false);
5206 if (NoexceptExpr.isInvalid())
5210 if (ESI.NoexceptExpr != NoexceptExpr.get())
5212 ESI.NoexceptExpr = NoexceptExpr.get();
5215 if (ESI.Type != EST_Dynamic)
5218 // Instantiate a dynamic exception specification's type.
5219 for (QualType T : ESI.Exceptions) {
5220 if (const PackExpansionType *PackExpansion =
5221 T->getAs<PackExpansionType>()) {
5224 // We have a pack expansion. Instantiate it.
5225 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5226 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5228 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5230 // Determine whether the set of unexpanded parameter packs can and
5233 bool Expand = false;
5234 bool RetainExpansion = false;
5235 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5236 // FIXME: Track the location of the ellipsis (and track source location
5237 // information for the types in the exception specification in general).
5238 if (getDerived().TryExpandParameterPacks(
5239 Loc, SourceRange(), Unexpanded, Expand,
5240 RetainExpansion, NumExpansions))
5244 // We can't expand this pack expansion into separate arguments yet;
5245 // just substitute into the pattern and create a new pack expansion
5247 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5248 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5252 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5253 Exceptions.push_back(U);
5257 // Substitute into the pack expansion pattern for each slice of the
5259 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5260 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5262 QualType U = getDerived().TransformType(PackExpansion->getPattern());
5263 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5266 Exceptions.push_back(U);
5269 QualType U = getDerived().TransformType(T);
5270 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5275 Exceptions.push_back(U);
5279 ESI.Exceptions = Exceptions;
5280 if (ESI.Exceptions.empty())
5281 ESI.Type = EST_DynamicNone;
5285 template<typename Derived>
5286 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5287 TypeLocBuilder &TLB,
5288 FunctionNoProtoTypeLoc TL) {
5289 const FunctionNoProtoType *T = TL.getTypePtr();
5290 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5291 if (ResultType.isNull())
5294 QualType Result = TL.getType();
5295 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5296 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5298 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5299 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5300 NewTL.setLParenLoc(TL.getLParenLoc());
5301 NewTL.setRParenLoc(TL.getRParenLoc());
5302 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5307 template<typename Derived> QualType
5308 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5309 UnresolvedUsingTypeLoc TL) {
5310 const UnresolvedUsingType *T = TL.getTypePtr();
5311 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5315 QualType Result = TL.getType();
5316 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5317 Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5318 if (Result.isNull())
5322 // We might get an arbitrary type spec type back. We should at
5323 // least always get a type spec type, though.
5324 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5325 NewTL.setNameLoc(TL.getNameLoc());
5330 template<typename Derived>
5331 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5332 TypedefTypeLoc TL) {
5333 const TypedefType *T = TL.getTypePtr();
5334 TypedefNameDecl *Typedef
5335 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5340 QualType Result = TL.getType();
5341 if (getDerived().AlwaysRebuild() ||
5342 Typedef != T->getDecl()) {
5343 Result = getDerived().RebuildTypedefType(Typedef);
5344 if (Result.isNull())
5348 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5349 NewTL.setNameLoc(TL.getNameLoc());
5354 template<typename Derived>
5355 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5356 TypeOfExprTypeLoc TL) {
5357 // typeof expressions are not potentially evaluated contexts
5358 EnterExpressionEvaluationContext Unevaluated(
5359 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5360 Sema::ReuseLambdaContextDecl);
5362 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5366 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5370 QualType Result = TL.getType();
5371 if (getDerived().AlwaysRebuild() ||
5372 E.get() != TL.getUnderlyingExpr()) {
5373 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5374 if (Result.isNull())
5379 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5380 NewTL.setTypeofLoc(TL.getTypeofLoc());
5381 NewTL.setLParenLoc(TL.getLParenLoc());
5382 NewTL.setRParenLoc(TL.getRParenLoc());
5387 template<typename Derived>
5388 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5390 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5391 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5395 QualType Result = TL.getType();
5396 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5397 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5398 if (Result.isNull())
5402 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5403 NewTL.setTypeofLoc(TL.getTypeofLoc());
5404 NewTL.setLParenLoc(TL.getLParenLoc());
5405 NewTL.setRParenLoc(TL.getRParenLoc());
5406 NewTL.setUnderlyingTInfo(New_Under_TI);
5411 template<typename Derived>
5412 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5413 DecltypeTypeLoc TL) {
5414 const DecltypeType *T = TL.getTypePtr();
5416 // decltype expressions are not potentially evaluated contexts
5417 EnterExpressionEvaluationContext Unevaluated(
5418 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5419 /*IsDecltype=*/true);
5421 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5425 E = getSema().ActOnDecltypeExpression(E.get());
5429 QualType Result = TL.getType();
5430 if (getDerived().AlwaysRebuild() ||
5431 E.get() != T->getUnderlyingExpr()) {
5432 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5433 if (Result.isNull())
5438 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5439 NewTL.setNameLoc(TL.getNameLoc());
5444 template<typename Derived>
5445 QualType TreeTransform<Derived>::TransformUnaryTransformType(
5446 TypeLocBuilder &TLB,
5447 UnaryTransformTypeLoc TL) {
5448 QualType Result = TL.getType();
5449 if (Result->isDependentType()) {
5450 const UnaryTransformType *T = TL.getTypePtr();
5452 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5453 Result = getDerived().RebuildUnaryTransformType(NewBase,
5456 if (Result.isNull())
5460 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5461 NewTL.setKWLoc(TL.getKWLoc());
5462 NewTL.setParensRange(TL.getParensRange());
5463 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5467 template<typename Derived>
5468 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5470 const AutoType *T = TL.getTypePtr();
5471 QualType OldDeduced = T->getDeducedType();
5472 QualType NewDeduced;
5473 if (!OldDeduced.isNull()) {
5474 NewDeduced = getDerived().TransformType(OldDeduced);
5475 if (NewDeduced.isNull())
5479 QualType Result = TL.getType();
5480 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5481 T->isDependentType()) {
5482 Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
5483 if (Result.isNull())
5487 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5488 NewTL.setNameLoc(TL.getNameLoc());
5493 template<typename Derived>
5494 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5495 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5496 const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5499 TemplateName TemplateName = getDerived().TransformTemplateName(
5500 SS, T->getTemplateName(), TL.getTemplateNameLoc());
5501 if (TemplateName.isNull())
5504 QualType OldDeduced = T->getDeducedType();
5505 QualType NewDeduced;
5506 if (!OldDeduced.isNull()) {
5507 NewDeduced = getDerived().TransformType(OldDeduced);
5508 if (NewDeduced.isNull())
5512 QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5513 TemplateName, NewDeduced);
5514 if (Result.isNull())
5517 DeducedTemplateSpecializationTypeLoc NewTL =
5518 TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5519 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5524 template<typename Derived>
5525 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5527 const RecordType *T = TL.getTypePtr();
5529 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5534 QualType Result = TL.getType();
5535 if (getDerived().AlwaysRebuild() ||
5536 Record != T->getDecl()) {
5537 Result = getDerived().RebuildRecordType(Record);
5538 if (Result.isNull())
5542 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5543 NewTL.setNameLoc(TL.getNameLoc());
5548 template<typename Derived>
5549 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5551 const EnumType *T = TL.getTypePtr();
5553 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5558 QualType Result = TL.getType();
5559 if (getDerived().AlwaysRebuild() ||
5560 Enum != T->getDecl()) {
5561 Result = getDerived().RebuildEnumType(Enum);
5562 if (Result.isNull())
5566 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5567 NewTL.setNameLoc(TL.getNameLoc());
5572 template<typename Derived>
5573 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5574 TypeLocBuilder &TLB,
5575 InjectedClassNameTypeLoc TL) {
5576 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5577 TL.getTypePtr()->getDecl());
5578 if (!D) return QualType();
5580 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5581 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5585 template<typename Derived>
5586 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5587 TypeLocBuilder &TLB,
5588 TemplateTypeParmTypeLoc TL) {
5589 return TransformTypeSpecType(TLB, TL);
5592 template<typename Derived>
5593 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5594 TypeLocBuilder &TLB,
5595 SubstTemplateTypeParmTypeLoc TL) {
5596 const SubstTemplateTypeParmType *T = TL.getTypePtr();
5598 // Substitute into the replacement type, which itself might involve something
5599 // that needs to be transformed. This only tends to occur with default
5600 // template arguments of template template parameters.
5601 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5602 QualType Replacement = getDerived().TransformType(T->getReplacementType());
5603 if (Replacement.isNull())
5606 // Always canonicalize the replacement type.
5607 Replacement = SemaRef.Context.getCanonicalType(Replacement);
5609 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5612 // Propagate type-source information.
5613 SubstTemplateTypeParmTypeLoc NewTL
5614 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5615 NewTL.setNameLoc(TL.getNameLoc());
5620 template<typename Derived>
5621 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5622 TypeLocBuilder &TLB,
5623 SubstTemplateTypeParmPackTypeLoc TL) {
5624 return TransformTypeSpecType(TLB, TL);
5627 template<typename Derived>
5628 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5629 TypeLocBuilder &TLB,
5630 TemplateSpecializationTypeLoc TL) {
5631 const TemplateSpecializationType *T = TL.getTypePtr();
5633 // The nested-name-specifier never matters in a TemplateSpecializationType,
5634 // because we can't have a dependent nested-name-specifier anyway.
5636 TemplateName Template
5637 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5638 TL.getTemplateNameLoc());
5639 if (Template.isNull())
5642 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5645 template<typename Derived>
5646 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5648 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5649 if (ValueType.isNull())
5652 QualType Result = TL.getType();
5653 if (getDerived().AlwaysRebuild() ||
5654 ValueType != TL.getValueLoc().getType()) {
5655 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5656 if (Result.isNull())
5660 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5661 NewTL.setKWLoc(TL.getKWLoc());
5662 NewTL.setLParenLoc(TL.getLParenLoc());
5663 NewTL.setRParenLoc(TL.getRParenLoc());
5668 template <typename Derived>
5669 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
5671 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5672 if (ValueType.isNull())
5675 QualType Result = TL.getType();
5676 if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
5677 const PipeType *PT = Result->getAs<PipeType>();
5678 bool isReadPipe = PT->isReadOnly();
5679 Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
5680 if (Result.isNull())
5684 PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
5685 NewTL.setKWLoc(TL.getKWLoc());
5690 /// \brief Simple iterator that traverses the template arguments in a
5691 /// container that provides a \c getArgLoc() member function.
5693 /// This iterator is intended to be used with the iterator form of
5694 /// \c TreeTransform<Derived>::TransformTemplateArguments().
5695 template<typename ArgLocContainer>
5696 class TemplateArgumentLocContainerIterator {
5697 ArgLocContainer *Container;
5701 typedef TemplateArgumentLoc value_type;
5702 typedef TemplateArgumentLoc reference;
5703 typedef int difference_type;
5704 typedef std::input_iterator_tag iterator_category;
5707 TemplateArgumentLoc Arg;
5710 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5712 const TemplateArgumentLoc *operator->() const {
5718 TemplateArgumentLocContainerIterator() {}
5720 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5722 : Container(&Container), Index(Index) { }
5724 TemplateArgumentLocContainerIterator &operator++() {
5729 TemplateArgumentLocContainerIterator operator++(int) {
5730 TemplateArgumentLocContainerIterator Old(*this);
5735 TemplateArgumentLoc operator*() const {
5736 return Container->getArgLoc(Index);
5739 pointer operator->() const {
5740 return pointer(Container->getArgLoc(Index));
5743 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5744 const TemplateArgumentLocContainerIterator &Y) {
5745 return X.Container == Y.Container && X.Index == Y.Index;
5748 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
5749 const TemplateArgumentLocContainerIterator &Y) {
5755 template <typename Derived>
5756 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5757 TypeLocBuilder &TLB,
5758 TemplateSpecializationTypeLoc TL,
5759 TemplateName Template) {
5760 TemplateArgumentListInfo NewTemplateArgs;
5761 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5762 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5763 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
5765 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5766 ArgIterator(TL, TL.getNumArgs()),
5770 // FIXME: maybe don't rebuild if all the template arguments are the same.
5773 getDerived().RebuildTemplateSpecializationType(Template,
5774 TL.getTemplateNameLoc(),
5777 if (!Result.isNull()) {
5778 // Specializations of template template parameters are represented as
5779 // TemplateSpecializationTypes, and substitution of type alias templates
5780 // within a dependent context can transform them into
5781 // DependentTemplateSpecializationTypes.
5782 if (isa<DependentTemplateSpecializationType>(Result)) {
5783 DependentTemplateSpecializationTypeLoc NewTL
5784 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5785 NewTL.setElaboratedKeywordLoc(SourceLocation());
5786 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
5787 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5788 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5789 NewTL.setLAngleLoc(TL.getLAngleLoc());
5790 NewTL.setRAngleLoc(TL.getRAngleLoc());
5791 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5792 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5796 TemplateSpecializationTypeLoc NewTL
5797 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5798 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5799 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5800 NewTL.setLAngleLoc(TL.getLAngleLoc());
5801 NewTL.setRAngleLoc(TL.getRAngleLoc());
5802 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5803 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5809 template <typename Derived>
5810 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
5811 TypeLocBuilder &TLB,
5812 DependentTemplateSpecializationTypeLoc TL,
5813 TemplateName Template,
5815 TemplateArgumentListInfo NewTemplateArgs;
5816 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5817 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5818 typedef TemplateArgumentLocContainerIterator<
5819 DependentTemplateSpecializationTypeLoc> ArgIterator;
5820 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5821 ArgIterator(TL, TL.getNumArgs()),
5825 // FIXME: maybe don't rebuild if all the template arguments are the same.
5827 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
5829 = getSema().Context.getDependentTemplateSpecializationType(
5830 TL.getTypePtr()->getKeyword(),
5831 DTN->getQualifier(),
5832 DTN->getIdentifier(),
5835 DependentTemplateSpecializationTypeLoc NewTL
5836 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5837 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5838 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
5839 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5840 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5841 NewTL.setLAngleLoc(TL.getLAngleLoc());
5842 NewTL.setRAngleLoc(TL.getRAngleLoc());
5843 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5844 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5849 = getDerived().RebuildTemplateSpecializationType(Template,
5850 TL.getTemplateNameLoc(),
5853 if (!Result.isNull()) {
5854 /// FIXME: Wrap this in an elaborated-type-specifier?
5855 TemplateSpecializationTypeLoc NewTL
5856 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5857 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5858 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5859 NewTL.setLAngleLoc(TL.getLAngleLoc());
5860 NewTL.setRAngleLoc(TL.getRAngleLoc());
5861 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5862 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5868 template<typename Derived>
5870 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
5871 ElaboratedTypeLoc TL) {
5872 const ElaboratedType *T = TL.getTypePtr();
5874 NestedNameSpecifierLoc QualifierLoc;
5875 // NOTE: the qualifier in an ElaboratedType is optional.
5876 if (TL.getQualifierLoc()) {
5878 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5883 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
5884 if (NamedT.isNull())
5887 // C++0x [dcl.type.elab]p2:
5888 // If the identifier resolves to a typedef-name or the simple-template-id
5889 // resolves to an alias template specialization, the
5890 // elaborated-type-specifier is ill-formed.
5891 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
5892 if (const TemplateSpecializationType *TST =
5893 NamedT->getAs<TemplateSpecializationType>()) {
5894 TemplateName Template = TST->getTemplateName();
5895 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
5896 Template.getAsTemplateDecl())) {
5897 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
5898 diag::err_tag_reference_non_tag)
5899 << TAT << Sema::NTK_TypeAliasTemplate
5900 << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
5901 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
5906 QualType Result = TL.getType();
5907 if (getDerived().AlwaysRebuild() ||
5908 QualifierLoc != TL.getQualifierLoc() ||
5909 NamedT != T->getNamedType()) {
5910 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
5912 QualifierLoc, NamedT);
5913 if (Result.isNull())
5917 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5918 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5919 NewTL.setQualifierLoc(QualifierLoc);
5923 template<typename Derived>
5924 QualType TreeTransform<Derived>::TransformAttributedType(
5925 TypeLocBuilder &TLB,
5926 AttributedTypeLoc TL) {
5927 const AttributedType *oldType = TL.getTypePtr();
5928 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
5929 if (modifiedType.isNull())
5932 QualType result = TL.getType();
5934 // FIXME: dependent operand expressions?
5935 if (getDerived().AlwaysRebuild() ||
5936 modifiedType != oldType->getModifiedType()) {
5937 // TODO: this is really lame; we should really be rebuilding the
5938 // equivalent type from first principles.
5939 QualType equivalentType
5940 = getDerived().TransformType(oldType->getEquivalentType());
5941 if (equivalentType.isNull())
5944 // Check whether we can add nullability; it is only represented as
5945 // type sugar, and therefore cannot be diagnosed in any other way.
5946 if (auto nullability = oldType->getImmediateNullability()) {
5947 if (!modifiedType->canHaveNullability()) {
5948 SemaRef.Diag(TL.getAttrNameLoc(), diag::err_nullability_nonpointer)
5949 << DiagNullabilityKind(*nullability, false) << modifiedType;
5954 result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
5959 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
5960 newTL.setAttrNameLoc(TL.getAttrNameLoc());
5961 if (TL.hasAttrOperand())
5962 newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5963 if (TL.hasAttrExprOperand())
5964 newTL.setAttrExprOperand(TL.getAttrExprOperand());
5965 else if (TL.hasAttrEnumOperand())
5966 newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
5971 template<typename Derived>
5973 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
5975 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
5979 QualType Result = TL.getType();
5980 if (getDerived().AlwaysRebuild() ||
5981 Inner != TL.getInnerLoc().getType()) {
5982 Result = getDerived().RebuildParenType(Inner);
5983 if (Result.isNull())
5987 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
5988 NewTL.setLParenLoc(TL.getLParenLoc());
5989 NewTL.setRParenLoc(TL.getRParenLoc());
5993 template<typename Derived>
5994 QualType TreeTransform<Derived>::TransformDependentNameType(
5995 TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
5996 return TransformDependentNameType(TLB, TL, false);
5999 template<typename Derived>
6000 QualType TreeTransform<Derived>::TransformDependentNameType(
6001 TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6002 const DependentNameType *T = TL.getTypePtr();
6004 NestedNameSpecifierLoc QualifierLoc
6005 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6010 = getDerived().RebuildDependentNameType(T->getKeyword(),
6011 TL.getElaboratedKeywordLoc(),
6016 if (Result.isNull())
6019 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6020 QualType NamedT = ElabT->getNamedType();
6021 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6023 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6024 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6025 NewTL.setQualifierLoc(QualifierLoc);
6027 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6028 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6029 NewTL.setQualifierLoc(QualifierLoc);
6030 NewTL.setNameLoc(TL.getNameLoc());
6035 template<typename Derived>
6036 QualType TreeTransform<Derived>::
6037 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6038 DependentTemplateSpecializationTypeLoc TL) {
6039 NestedNameSpecifierLoc QualifierLoc;
6040 if (TL.getQualifierLoc()) {
6042 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6048 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6051 template<typename Derived>
6052 QualType TreeTransform<Derived>::
6053 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6054 DependentTemplateSpecializationTypeLoc TL,
6055 NestedNameSpecifierLoc QualifierLoc) {
6056 const DependentTemplateSpecializationType *T = TL.getTypePtr();
6058 TemplateArgumentListInfo NewTemplateArgs;
6059 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6060 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6062 typedef TemplateArgumentLocContainerIterator<
6063 DependentTemplateSpecializationTypeLoc> ArgIterator;
6064 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6065 ArgIterator(TL, TL.getNumArgs()),
6069 QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6070 T->getKeyword(), QualifierLoc, T->getIdentifier(),
6071 TL.getTemplateNameLoc(), NewTemplateArgs,
6072 /*AllowInjectedClassName*/ false);
6073 if (Result.isNull())
6076 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6077 QualType NamedT = ElabT->getNamedType();
6079 // Copy information relevant to the template specialization.
6080 TemplateSpecializationTypeLoc NamedTL
6081 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6082 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6083 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6084 NamedTL.setLAngleLoc(TL.getLAngleLoc());
6085 NamedTL.setRAngleLoc(TL.getRAngleLoc());
6086 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6087 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6089 // Copy information relevant to the elaborated type.
6090 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6091 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6092 NewTL.setQualifierLoc(QualifierLoc);
6093 } else if (isa<DependentTemplateSpecializationType>(Result)) {
6094 DependentTemplateSpecializationTypeLoc SpecTL
6095 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6096 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6097 SpecTL.setQualifierLoc(QualifierLoc);
6098 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6099 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6100 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6101 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6102 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6103 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6105 TemplateSpecializationTypeLoc SpecTL
6106 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6107 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6108 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6109 SpecTL.setLAngleLoc(TL.getLAngleLoc());
6110 SpecTL.setRAngleLoc(TL.getRAngleLoc());
6111 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6112 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6117 template<typename Derived>
6118 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6119 PackExpansionTypeLoc TL) {
6121 = getDerived().TransformType(TLB, TL.getPatternLoc());
6122 if (Pattern.isNull())
6125 QualType Result = TL.getType();
6126 if (getDerived().AlwaysRebuild() ||
6127 Pattern != TL.getPatternLoc().getType()) {
6128 Result = getDerived().RebuildPackExpansionType(Pattern,
6129 TL.getPatternLoc().getSourceRange(),
6130 TL.getEllipsisLoc(),
6131 TL.getTypePtr()->getNumExpansions());
6132 if (Result.isNull())
6136 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6137 NewT.setEllipsisLoc(TL.getEllipsisLoc());
6141 template<typename Derived>
6143 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6144 ObjCInterfaceTypeLoc TL) {
6145 // ObjCInterfaceType is never dependent.
6146 TLB.pushFullCopy(TL);
6147 return TL.getType();
6150 template<typename Derived>
6152 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6153 ObjCTypeParamTypeLoc TL) {
6154 const ObjCTypeParamType *T = TL.getTypePtr();
6155 ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6156 getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6160 QualType Result = TL.getType();
6161 if (getDerived().AlwaysRebuild() ||
6162 OTP != T->getDecl()) {
6163 Result = getDerived().RebuildObjCTypeParamType(OTP,
6164 TL.getProtocolLAngleLoc(),
6165 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6166 TL.getNumProtocols()),
6167 TL.getProtocolLocs(),
6168 TL.getProtocolRAngleLoc());
6169 if (Result.isNull())
6173 ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6174 if (TL.getNumProtocols()) {
6175 NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6176 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6177 NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6178 NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6183 template<typename Derived>
6185 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6186 ObjCObjectTypeLoc TL) {
6187 // Transform base type.
6188 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6189 if (BaseType.isNull())
6192 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6194 // Transform type arguments.
6195 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6196 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6197 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6198 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6199 QualType TypeArg = TypeArgInfo->getType();
6200 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6203 // We have a pack expansion. Instantiate it.
6204 const auto *PackExpansion = PackExpansionLoc.getType()
6205 ->castAs<PackExpansionType>();
6206 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6207 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6209 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6211 // Determine whether the set of unexpanded parameter packs can
6212 // and should be expanded.
6213 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6214 bool Expand = false;
6215 bool RetainExpansion = false;
6216 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6217 if (getDerived().TryExpandParameterPacks(
6218 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6219 Unexpanded, Expand, RetainExpansion, NumExpansions))
6223 // We can't expand this pack expansion into separate arguments yet;
6224 // just substitute into the pattern and create a new pack expansion
6226 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6228 TypeLocBuilder TypeArgBuilder;
6229 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6230 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6232 if (NewPatternType.isNull())
6235 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6236 NewPatternType, NumExpansions);
6237 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6238 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6239 NewTypeArgInfos.push_back(
6240 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6244 // Substitute into the pack expansion pattern for each slice of the
6246 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6247 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6249 TypeLocBuilder TypeArgBuilder;
6250 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6252 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6254 if (NewTypeArg.isNull())
6257 NewTypeArgInfos.push_back(
6258 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6264 TypeLocBuilder TypeArgBuilder;
6265 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6266 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6267 if (NewTypeArg.isNull())
6270 // If nothing changed, just keep the old TypeSourceInfo.
6271 if (NewTypeArg == TypeArg) {
6272 NewTypeArgInfos.push_back(TypeArgInfo);
6276 NewTypeArgInfos.push_back(
6277 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6281 QualType Result = TL.getType();
6282 if (getDerived().AlwaysRebuild() || AnyChanged) {
6283 // Rebuild the type.
6284 Result = getDerived().RebuildObjCObjectType(
6287 TL.getTypeArgsLAngleLoc(),
6289 TL.getTypeArgsRAngleLoc(),
6290 TL.getProtocolLAngleLoc(),
6291 llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6292 TL.getNumProtocols()),
6293 TL.getProtocolLocs(),
6294 TL.getProtocolRAngleLoc());
6296 if (Result.isNull())
6300 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6301 NewT.setHasBaseTypeAsWritten(true);
6302 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6303 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6304 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6305 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6306 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6307 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6308 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6309 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6313 template<typename Derived>
6315 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6316 ObjCObjectPointerTypeLoc TL) {
6317 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6318 if (PointeeType.isNull())
6321 QualType Result = TL.getType();
6322 if (getDerived().AlwaysRebuild() ||
6323 PointeeType != TL.getPointeeLoc().getType()) {
6324 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6326 if (Result.isNull())
6330 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6331 NewT.setStarLoc(TL.getStarLoc());
6335 //===----------------------------------------------------------------------===//
6336 // Statement transformation
6337 //===----------------------------------------------------------------------===//
6338 template<typename Derived>
6340 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6344 template<typename Derived>
6346 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6347 return getDerived().TransformCompoundStmt(S, false);
6350 template<typename Derived>
6352 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6354 Sema::CompoundScopeRAII CompoundScope(getSema());
6356 bool SubStmtInvalid = false;
6357 bool SubStmtChanged = false;
6358 SmallVector<Stmt*, 8> Statements;
6359 for (auto *B : S->body()) {
6360 StmtResult Result = getDerived().TransformStmt(B);
6361 if (Result.isInvalid()) {
6362 // Immediately fail if this was a DeclStmt, since it's very
6363 // likely that this will cause problems for future statements.
6364 if (isa<DeclStmt>(B))
6367 // Otherwise, just keep processing substatements and fail later.
6368 SubStmtInvalid = true;
6372 SubStmtChanged = SubStmtChanged || Result.get() != B;
6373 Statements.push_back(Result.getAs<Stmt>());
6379 if (!getDerived().AlwaysRebuild() &&
6383 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6389 template<typename Derived>
6391 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6392 ExprResult LHS, RHS;
6394 EnterExpressionEvaluationContext Unevaluated(
6395 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6397 // Transform the left-hand case value.
6398 LHS = getDerived().TransformExpr(S->getLHS());
6399 LHS = SemaRef.ActOnConstantExpression(LHS);
6400 if (LHS.isInvalid())
6403 // Transform the right-hand case value (for the GNU case-range extension).
6404 RHS = getDerived().TransformExpr(S->getRHS());
6405 RHS = SemaRef.ActOnConstantExpression(RHS);
6406 if (RHS.isInvalid())
6410 // Build the case statement.
6411 // Case statements are always rebuilt so that they will attached to their
6412 // transformed switch statement.
6413 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6415 S->getEllipsisLoc(),
6418 if (Case.isInvalid())
6421 // Transform the statement following the case
6422 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6423 if (SubStmt.isInvalid())
6426 // Attach the body to the case statement
6427 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6430 template<typename Derived>
6432 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6433 // Transform the statement following the default case
6434 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6435 if (SubStmt.isInvalid())
6438 // Default statements are always rebuilt
6439 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6443 template<typename Derived>
6445 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
6446 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6447 if (SubStmt.isInvalid())
6450 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6456 // FIXME: Pass the real colon location in.
6457 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6458 cast<LabelDecl>(LD), SourceLocation(),
6462 template <typename Derived>
6463 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6467 switch (R->getKind()) {
6468 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
6470 #define PRAGMA_SPELLING_ATTR(X) \
6472 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6473 #include "clang/Basic/AttrList.inc"
6479 template <typename Derived>
6480 StmtResult TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
6481 bool AttrsChanged = false;
6482 SmallVector<const Attr *, 1> Attrs;
6484 // Visit attributes and keep track if any are transformed.
6485 for (const auto *I : S->getAttrs()) {
6486 const Attr *R = getDerived().TransformAttr(I);
6487 AttrsChanged |= (I != R);
6491 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6492 if (SubStmt.isInvalid())
6495 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6498 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6502 template<typename Derived>
6504 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6505 // Transform the initialization statement
6506 StmtResult Init = getDerived().TransformStmt(S->getInit());
6507 if (Init.isInvalid())
6510 // Transform the condition
6511 Sema::ConditionResult Cond = getDerived().TransformCondition(
6512 S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6513 S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6514 : Sema::ConditionKind::Boolean);
6515 if (Cond.isInvalid())
6518 // If this is a constexpr if, determine which arm we should instantiate.
6519 llvm::Optional<bool> ConstexprConditionValue;
6520 if (S->isConstexpr())
6521 ConstexprConditionValue = Cond.getKnownValue();
6523 // Transform the "then" branch.
6525 if (!ConstexprConditionValue || *ConstexprConditionValue) {
6526 Then = getDerived().TransformStmt(S->getThen());
6527 if (Then.isInvalid())
6530 Then = new (getSema().Context) NullStmt(S->getThen()->getLocStart());
6533 // Transform the "else" branch.
6535 if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6536 Else = getDerived().TransformStmt(S->getElse());
6537 if (Else.isInvalid())
6541 if (!getDerived().AlwaysRebuild() &&
6542 Init.get() == S->getInit() &&
6543 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6544 Then.get() == S->getThen() &&
6545 Else.get() == S->getElse())
6548 return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6549 Init.get(), Then.get(), S->getElseLoc(),
6553 template<typename Derived>
6555 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6556 // Transform the initialization statement
6557 StmtResult Init = getDerived().TransformStmt(S->getInit());
6558 if (Init.isInvalid())
6561 // Transform the condition.
6562 Sema::ConditionResult Cond = getDerived().TransformCondition(
6563 S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
6564 Sema::ConditionKind::Switch);
6565 if (Cond.isInvalid())
6568 // Rebuild the switch statement.
6570 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(),
6571 S->getInit(), Cond);
6572 if (Switch.isInvalid())
6575 // Transform the body of the switch statement.
6576 StmtResult Body = getDerived().TransformStmt(S->getBody());
6577 if (Body.isInvalid())
6580 // Complete the switch statement.
6581 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6585 template<typename Derived>
6587 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6588 // Transform the condition
6589 Sema::ConditionResult Cond = getDerived().TransformCondition(
6590 S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
6591 Sema::ConditionKind::Boolean);
6592 if (Cond.isInvalid())
6595 // Transform the body
6596 StmtResult Body = getDerived().TransformStmt(S->getBody());
6597 if (Body.isInvalid())
6600 if (!getDerived().AlwaysRebuild() &&
6601 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6602 Body.get() == S->getBody())
6605 return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
6608 template<typename Derived>
6610 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6611 // Transform the body
6612 StmtResult Body = getDerived().TransformStmt(S->getBody());
6613 if (Body.isInvalid())
6616 // Transform the condition
6617 ExprResult Cond = getDerived().TransformExpr(S->getCond());
6618 if (Cond.isInvalid())
6621 if (!getDerived().AlwaysRebuild() &&
6622 Cond.get() == S->getCond() &&
6623 Body.get() == S->getBody())
6626 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6627 /*FIXME:*/S->getWhileLoc(), Cond.get(),
6631 template<typename Derived>
6633 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6634 // Transform the initialization statement
6635 StmtResult Init = getDerived().TransformStmt(S->getInit());
6636 if (Init.isInvalid())
6639 // In OpenMP loop region loop control variable must be captured and be
6640 // private. Perform analysis of first part (if any).
6641 if (getSema().getLangOpts().OpenMP && Init.isUsable())
6642 getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
6644 // Transform the condition
6645 Sema::ConditionResult Cond = getDerived().TransformCondition(
6646 S->getForLoc(), S->getConditionVariable(), S->getCond(),
6647 Sema::ConditionKind::Boolean);
6648 if (Cond.isInvalid())
6651 // Transform the increment
6652 ExprResult Inc = getDerived().TransformExpr(S->getInc());
6653 if (Inc.isInvalid())
6656 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6657 if (S->getInc() && !FullInc.get())
6660 // Transform the body
6661 StmtResult Body = getDerived().TransformStmt(S->getBody());
6662 if (Body.isInvalid())
6665 if (!getDerived().AlwaysRebuild() &&
6666 Init.get() == S->getInit() &&
6667 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6668 Inc.get() == S->getInc() &&
6669 Body.get() == S->getBody())
6672 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6673 Init.get(), Cond, FullInc,
6674 S->getRParenLoc(), Body.get());
6677 template<typename Derived>
6679 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6680 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6685 // Goto statements must always be rebuilt, to resolve the label.
6686 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
6687 cast<LabelDecl>(LD));
6690 template<typename Derived>
6692 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
6693 ExprResult Target = getDerived().TransformExpr(S->getTarget());
6694 if (Target.isInvalid())
6696 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6698 if (!getDerived().AlwaysRebuild() &&
6699 Target.get() == S->getTarget())
6702 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6706 template<typename Derived>
6708 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6712 template<typename Derived>
6714 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6718 template<typename Derived>
6720 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
6721 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
6722 /*NotCopyInit*/false);
6723 if (Result.isInvalid())
6726 // FIXME: We always rebuild the return statement because there is no way
6727 // to tell whether the return type of the function has changed.
6728 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
6731 template<typename Derived>
6733 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
6734 bool DeclChanged = false;
6735 SmallVector<Decl *, 4> Decls;
6736 for (auto *D : S->decls()) {
6737 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
6741 if (Transformed != D)
6744 Decls.push_back(Transformed);
6747 if (!getDerived().AlwaysRebuild() && !DeclChanged)
6750 return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
6753 template<typename Derived>
6755 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
6757 SmallVector<Expr*, 8> Constraints;
6758 SmallVector<Expr*, 8> Exprs;
6759 SmallVector<IdentifierInfo *, 4> Names;
6761 ExprResult AsmString;
6762 SmallVector<Expr*, 8> Clobbers;
6764 bool ExprsChanged = false;
6766 // Go through the outputs.
6767 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
6768 Names.push_back(S->getOutputIdentifier(I));
6770 // No need to transform the constraint literal.
6771 Constraints.push_back(S->getOutputConstraintLiteral(I));
6773 // Transform the output expr.
6774 Expr *OutputExpr = S->getOutputExpr(I);
6775 ExprResult Result = getDerived().TransformExpr(OutputExpr);
6776 if (Result.isInvalid())
6779 ExprsChanged |= Result.get() != OutputExpr;
6781 Exprs.push_back(Result.get());
6784 // Go through the inputs.
6785 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
6786 Names.push_back(S->getInputIdentifier(I));
6788 // No need to transform the constraint literal.
6789 Constraints.push_back(S->getInputConstraintLiteral(I));
6791 // Transform the input expr.
6792 Expr *InputExpr = S->getInputExpr(I);
6793 ExprResult Result = getDerived().TransformExpr(InputExpr);
6794 if (Result.isInvalid())
6797 ExprsChanged |= Result.get() != InputExpr;
6799 Exprs.push_back(Result.get());
6802 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
6805 // Go through the clobbers.
6806 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
6807 Clobbers.push_back(S->getClobberStringLiteral(I));
6809 // No need to transform the asm string literal.
6810 AsmString = S->getAsmString();
6811 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
6812 S->isVolatile(), S->getNumOutputs(),
6813 S->getNumInputs(), Names.data(),
6814 Constraints, Exprs, AsmString.get(),
6815 Clobbers, S->getRParenLoc());
6818 template<typename Derived>
6820 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
6821 ArrayRef<Token> AsmToks =
6822 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
6824 bool HadError = false, HadChange = false;
6826 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
6827 SmallVector<Expr*, 8> TransformedExprs;
6828 TransformedExprs.reserve(SrcExprs.size());
6829 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
6830 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
6831 if (!Result.isUsable()) {
6834 HadChange |= (Result.get() != SrcExprs[i]);
6835 TransformedExprs.push_back(Result.get());
6839 if (HadError) return StmtError();
6840 if (!HadChange && !getDerived().AlwaysRebuild())
6843 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
6844 AsmToks, S->getAsmString(),
6845 S->getNumOutputs(), S->getNumInputs(),
6846 S->getAllConstraints(), S->getClobbers(),
6847 TransformedExprs, S->getEndLoc());
6850 // C++ Coroutines TS
6852 template<typename Derived>
6854 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
6855 auto *ScopeInfo = SemaRef.getCurFunction();
6856 auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
6857 assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
6858 ScopeInfo->NeedsCoroutineSuspends &&
6859 ScopeInfo->CoroutineSuspends.first == nullptr &&
6860 ScopeInfo->CoroutineSuspends.second == nullptr &&
6861 "expected clean scope info");
6863 // Set that we have (possibly-invalid) suspend points before we do anything
6865 ScopeInfo->setNeedsCoroutineSuspends(false);
6867 // The new CoroutinePromise object needs to be built and put into the current
6868 // FunctionScopeInfo before any transformations or rebuilding occurs.
6869 auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
6872 getDerived().transformedLocalDecl(S->getPromiseDecl(), Promise);
6873 ScopeInfo->CoroutinePromise = Promise;
6875 // Transform the implicit coroutine statements we built during the initial
6877 StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
6878 if (InitSuspend.isInvalid())
6880 StmtResult FinalSuspend =
6881 getDerived().TransformStmt(S->getFinalSuspendStmt());
6882 if (FinalSuspend.isInvalid())
6884 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
6885 assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
6887 StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
6888 if (BodyRes.isInvalid())
6891 CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
6892 if (Builder.isInvalid())
6895 Expr *ReturnObject = S->getReturnValueInit();
6896 assert(ReturnObject && "the return object is expected to be valid");
6897 ExprResult Res = getDerived().TransformInitializer(ReturnObject,
6898 /*NoCopyInit*/ false);
6899 if (Res.isInvalid())
6901 Builder.ReturnValue = Res.get();
6903 if (S->hasDependentPromiseType()) {
6904 assert(!Promise->getType()->isDependentType() &&
6905 "the promise type must no longer be dependent");
6906 assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
6907 !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
6908 "these nodes should not have been built yet");
6909 if (!Builder.buildDependentStatements())
6912 if (auto *OnFallthrough = S->getFallthroughHandler()) {
6913 StmtResult Res = getDerived().TransformStmt(OnFallthrough);
6914 if (Res.isInvalid())
6916 Builder.OnFallthrough = Res.get();
6919 if (auto *OnException = S->getExceptionHandler()) {
6920 StmtResult Res = getDerived().TransformStmt(OnException);
6921 if (Res.isInvalid())
6923 Builder.OnException = Res.get();
6926 if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
6927 StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
6928 if (Res.isInvalid())
6930 Builder.ReturnStmtOnAllocFailure = Res.get();
6933 // Transform any additional statements we may have already built
6934 assert(S->getAllocate() && S->getDeallocate() &&
6935 "allocation and deallocation calls must already be built");
6936 ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
6937 if (AllocRes.isInvalid())
6939 Builder.Allocate = AllocRes.get();
6941 ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
6942 if (DeallocRes.isInvalid())
6944 Builder.Deallocate = DeallocRes.get();
6947 return getDerived().RebuildCoroutineBodyStmt(Builder);
6950 template<typename Derived>
6952 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
6953 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
6954 /*NotCopyInit*/false);
6955 if (Result.isInvalid())
6958 // Always rebuild; we don't know if this needs to be injected into a new
6959 // context or if the promise type has changed.
6960 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
6964 template<typename Derived>
6966 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
6967 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
6968 /*NotCopyInit*/false);
6969 if (Result.isInvalid())
6972 // Always rebuild; we don't know if this needs to be injected into a new
6973 // context or if the promise type has changed.
6974 return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
6978 template <typename Derived>
6980 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
6981 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
6982 /*NotCopyInit*/ false);
6983 if (OperandResult.isInvalid())
6986 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
6987 E->getOperatorCoawaitLookup());
6989 if (LookupResult.isInvalid())
6992 // Always rebuild; we don't know if this needs to be injected into a new
6993 // context or if the promise type has changed.
6994 return getDerived().RebuildDependentCoawaitExpr(
6995 E->getKeywordLoc(), OperandResult.get(),
6996 cast<UnresolvedLookupExpr>(LookupResult.get()));
6999 template<typename Derived>
7001 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7002 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7003 /*NotCopyInit*/false);
7004 if (Result.isInvalid())
7007 // Always rebuild; we don't know if this needs to be injected into a new
7008 // context or if the promise type has changed.
7009 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7012 // Objective-C Statements.
7014 template<typename Derived>
7016 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7017 // Transform the body of the @try.
7018 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7019 if (TryBody.isInvalid())
7022 // Transform the @catch statements (if present).
7023 bool AnyCatchChanged = false;
7024 SmallVector<Stmt*, 8> CatchStmts;
7025 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7026 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7027 if (Catch.isInvalid())
7029 if (Catch.get() != S->getCatchStmt(I))
7030 AnyCatchChanged = true;
7031 CatchStmts.push_back(Catch.get());
7034 // Transform the @finally statement (if present).
7036 if (S->getFinallyStmt()) {
7037 Finally = getDerived().TransformStmt(S->getFinallyStmt());
7038 if (Finally.isInvalid())
7042 // If nothing changed, just retain this statement.
7043 if (!getDerived().AlwaysRebuild() &&
7044 TryBody.get() == S->getTryBody() &&
7046 Finally.get() == S->getFinallyStmt())
7049 // Build a new statement.
7050 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7051 CatchStmts, Finally.get());
7054 template<typename Derived>
7056 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7057 // Transform the @catch parameter, if there is one.
7058 VarDecl *Var = nullptr;
7059 if (VarDecl *FromVar = S->getCatchParamDecl()) {
7060 TypeSourceInfo *TSInfo = nullptr;
7061 if (FromVar->getTypeSourceInfo()) {
7062 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7069 T = TSInfo->getType();
7071 T = getDerived().TransformType(FromVar->getType());
7076 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7081 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7082 if (Body.isInvalid())
7085 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7090 template<typename Derived>
7092 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7093 // Transform the body.
7094 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7095 if (Body.isInvalid())
7098 // If nothing changed, just retain this statement.
7099 if (!getDerived().AlwaysRebuild() &&
7100 Body.get() == S->getFinallyBody())
7103 // Build a new statement.
7104 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7108 template<typename Derived>
7110 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7112 if (S->getThrowExpr()) {
7113 Operand = getDerived().TransformExpr(S->getThrowExpr());
7114 if (Operand.isInvalid())
7118 if (!getDerived().AlwaysRebuild() &&
7119 Operand.get() == S->getThrowExpr())
7122 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7125 template<typename Derived>
7127 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7128 ObjCAtSynchronizedStmt *S) {
7129 // Transform the object we are locking.
7130 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7131 if (Object.isInvalid())
7134 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7136 if (Object.isInvalid())
7139 // Transform the body.
7140 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7141 if (Body.isInvalid())
7144 // If nothing change, just retain the current statement.
7145 if (!getDerived().AlwaysRebuild() &&
7146 Object.get() == S->getSynchExpr() &&
7147 Body.get() == S->getSynchBody())
7150 // Build a new statement.
7151 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7152 Object.get(), Body.get());
7155 template<typename Derived>
7157 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7158 ObjCAutoreleasePoolStmt *S) {
7159 // Transform the body.
7160 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7161 if (Body.isInvalid())
7164 // If nothing changed, just retain this statement.
7165 if (!getDerived().AlwaysRebuild() &&
7166 Body.get() == S->getSubStmt())
7169 // Build a new statement.
7170 return getDerived().RebuildObjCAutoreleasePoolStmt(
7171 S->getAtLoc(), Body.get());
7174 template<typename Derived>
7176 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7177 ObjCForCollectionStmt *S) {
7178 // Transform the element statement.
7179 StmtResult Element = getDerived().TransformStmt(S->getElement());
7180 if (Element.isInvalid())
7183 // Transform the collection expression.
7184 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7185 if (Collection.isInvalid())
7188 // Transform the body.
7189 StmtResult Body = getDerived().TransformStmt(S->getBody());
7190 if (Body.isInvalid())
7193 // If nothing changed, just retain this statement.
7194 if (!getDerived().AlwaysRebuild() &&
7195 Element.get() == S->getElement() &&
7196 Collection.get() == S->getCollection() &&
7197 Body.get() == S->getBody())
7200 // Build a new statement.
7201 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7208 template <typename Derived>
7209 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7210 // Transform the exception declaration, if any.
7211 VarDecl *Var = nullptr;
7212 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7214 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7218 Var = getDerived().RebuildExceptionDecl(
7219 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7220 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7221 if (!Var || Var->isInvalidDecl())
7225 // Transform the actual exception handler.
7226 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7227 if (Handler.isInvalid())
7230 if (!getDerived().AlwaysRebuild() && !Var &&
7231 Handler.get() == S->getHandlerBlock())
7234 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7237 template <typename Derived>
7238 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7239 // Transform the try block itself.
7240 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7241 if (TryBlock.isInvalid())
7244 // Transform the handlers.
7245 bool HandlerChanged = false;
7246 SmallVector<Stmt *, 8> Handlers;
7247 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7248 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7249 if (Handler.isInvalid())
7252 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7253 Handlers.push_back(Handler.getAs<Stmt>());
7256 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7260 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7264 template<typename Derived>
7266 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7267 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7268 if (Range.isInvalid())
7271 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7272 if (Begin.isInvalid())
7274 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7275 if (End.isInvalid())
7278 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7279 if (Cond.isInvalid())
7282 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7283 if (Cond.isInvalid())
7286 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7288 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7289 if (Inc.isInvalid())
7292 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7294 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7295 if (LoopVar.isInvalid())
7298 StmtResult NewStmt = S;
7299 if (getDerived().AlwaysRebuild() ||
7300 Range.get() != S->getRangeStmt() ||
7301 Begin.get() != S->getBeginStmt() ||
7302 End.get() != S->getEndStmt() ||
7303 Cond.get() != S->getCond() ||
7304 Inc.get() != S->getInc() ||
7305 LoopVar.get() != S->getLoopVarStmt()) {
7306 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7308 S->getColonLoc(), Range.get(),
7309 Begin.get(), End.get(),
7311 Inc.get(), LoopVar.get(),
7313 if (NewStmt.isInvalid())
7317 StmtResult Body = getDerived().TransformStmt(S->getBody());
7318 if (Body.isInvalid())
7321 // Body has changed but we didn't rebuild the for-range statement. Rebuild
7322 // it now so we have a new statement to attach the body to.
7323 if (Body.get() != S->getBody() && NewStmt.get() == S) {
7324 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7326 S->getColonLoc(), Range.get(),
7327 Begin.get(), End.get(),
7329 Inc.get(), LoopVar.get(),
7331 if (NewStmt.isInvalid())
7335 if (NewStmt.get() == S)
7338 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7341 template<typename Derived>
7343 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7344 MSDependentExistsStmt *S) {
7345 // Transform the nested-name-specifier, if any.
7346 NestedNameSpecifierLoc QualifierLoc;
7347 if (S->getQualifierLoc()) {
7349 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7354 // Transform the declaration name.
7355 DeclarationNameInfo NameInfo = S->getNameInfo();
7356 if (NameInfo.getName()) {
7357 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7358 if (!NameInfo.getName())
7362 // Check whether anything changed.
7363 if (!getDerived().AlwaysRebuild() &&
7364 QualifierLoc == S->getQualifierLoc() &&
7365 NameInfo.getName() == S->getNameInfo().getName())
7368 // Determine whether this name exists, if we can.
7370 SS.Adopt(QualifierLoc);
7371 bool Dependent = false;
7372 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7373 case Sema::IER_Exists:
7374 if (S->isIfExists())
7377 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7379 case Sema::IER_DoesNotExist:
7380 if (S->isIfNotExists())
7383 return new (getSema().Context) NullStmt(S->getKeywordLoc());
7385 case Sema::IER_Dependent:
7389 case Sema::IER_Error:
7393 // We need to continue with the instantiation, so do so now.
7394 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7395 if (SubStmt.isInvalid())
7398 // If we have resolved the name, just transform to the substatement.
7402 // The name is still dependent, so build a dependent expression again.
7403 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7410 template<typename Derived>
7412 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7413 NestedNameSpecifierLoc QualifierLoc;
7414 if (E->getQualifierLoc()) {
7416 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7421 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7422 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7426 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7427 if (Base.isInvalid())
7430 return new (SemaRef.getASTContext())
7431 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7432 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7433 QualifierLoc, E->getMemberLoc());
7436 template <typename Derived>
7437 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7438 MSPropertySubscriptExpr *E) {
7439 auto BaseRes = getDerived().TransformExpr(E->getBase());
7440 if (BaseRes.isInvalid())
7442 auto IdxRes = getDerived().TransformExpr(E->getIdx());
7443 if (IdxRes.isInvalid())
7446 if (!getDerived().AlwaysRebuild() &&
7447 BaseRes.get() == E->getBase() &&
7448 IdxRes.get() == E->getIdx())
7451 return getDerived().RebuildArraySubscriptExpr(
7452 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7455 template <typename Derived>
7456 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7457 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7458 if (TryBlock.isInvalid())
7461 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7462 if (Handler.isInvalid())
7465 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7466 Handler.get() == S->getHandler())
7469 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7470 TryBlock.get(), Handler.get());
7473 template <typename Derived>
7474 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7475 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7476 if (Block.isInvalid())
7479 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7482 template <typename Derived>
7483 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7484 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7485 if (FilterExpr.isInvalid())
7488 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7489 if (Block.isInvalid())
7492 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7496 template <typename Derived>
7497 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7498 if (isa<SEHFinallyStmt>(Handler))
7499 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7501 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7504 template<typename Derived>
7506 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7510 //===----------------------------------------------------------------------===//
7511 // OpenMP directive transformation
7512 //===----------------------------------------------------------------------===//
7513 template <typename Derived>
7514 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7515 OMPExecutableDirective *D) {
7517 // Transform the clauses
7518 llvm::SmallVector<OMPClause *, 16> TClauses;
7519 ArrayRef<OMPClause *> Clauses = D->clauses();
7520 TClauses.reserve(Clauses.size());
7521 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7524 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7525 OMPClause *Clause = getDerived().TransformOMPClause(*I);
7526 getDerived().getSema().EndOpenMPClause();
7528 TClauses.push_back(Clause);
7530 TClauses.push_back(nullptr);
7533 StmtResult AssociatedStmt;
7534 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7535 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7536 /*CurScope=*/nullptr);
7539 Sema::CompoundScopeRAII CompoundScope(getSema());
7540 int ThisCaptureLevel =
7541 Sema::getOpenMPCaptureLevels(D->getDirectiveKind());
7542 Stmt *CS = D->getAssociatedStmt();
7543 while (--ThisCaptureLevel >= 0)
7544 CS = cast<CapturedStmt>(CS)->getCapturedStmt();
7545 Body = getDerived().TransformStmt(CS);
7548 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7549 if (AssociatedStmt.isInvalid()) {
7553 if (TClauses.size() != Clauses.size()) {
7557 // Transform directive name for 'omp critical' directive.
7558 DeclarationNameInfo DirName;
7559 if (D->getDirectiveKind() == OMPD_critical) {
7560 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7561 DirName = getDerived().TransformDeclarationNameInfo(DirName);
7563 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7564 if (D->getDirectiveKind() == OMPD_cancellation_point) {
7565 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7566 } else if (D->getDirectiveKind() == OMPD_cancel) {
7567 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7570 return getDerived().RebuildOMPExecutableDirective(
7571 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7572 AssociatedStmt.get(), D->getLocStart(), D->getLocEnd());
7575 template <typename Derived>
7577 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7578 DeclarationNameInfo DirName;
7579 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7581 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7582 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7586 template <typename Derived>
7588 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7589 DeclarationNameInfo DirName;
7590 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7592 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7593 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7597 template <typename Derived>
7599 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7600 DeclarationNameInfo DirName;
7601 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7603 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7604 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7608 template <typename Derived>
7610 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7611 DeclarationNameInfo DirName;
7612 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7614 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7615 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7619 template <typename Derived>
7621 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7622 DeclarationNameInfo DirName;
7623 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7625 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7626 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7630 template <typename Derived>
7632 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
7633 DeclarationNameInfo DirName;
7634 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
7636 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7637 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7641 template <typename Derived>
7643 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
7644 DeclarationNameInfo DirName;
7645 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
7647 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7648 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7652 template <typename Derived>
7654 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
7655 DeclarationNameInfo DirName;
7656 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
7658 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7659 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7663 template <typename Derived>
7665 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
7666 getDerived().getSema().StartOpenMPDSABlock(
7667 OMPD_critical, D->getDirectiveName(), nullptr, D->getLocStart());
7668 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7669 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7673 template <typename Derived>
7674 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
7675 OMPParallelForDirective *D) {
7676 DeclarationNameInfo DirName;
7677 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
7678 nullptr, D->getLocStart());
7679 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7680 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7684 template <typename Derived>
7685 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
7686 OMPParallelForSimdDirective *D) {
7687 DeclarationNameInfo DirName;
7688 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
7689 nullptr, D->getLocStart());
7690 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7691 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7695 template <typename Derived>
7696 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
7697 OMPParallelSectionsDirective *D) {
7698 DeclarationNameInfo DirName;
7699 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
7700 nullptr, D->getLocStart());
7701 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7702 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7706 template <typename Derived>
7708 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
7709 DeclarationNameInfo DirName;
7710 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
7712 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7713 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7717 template <typename Derived>
7718 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
7719 OMPTaskyieldDirective *D) {
7720 DeclarationNameInfo DirName;
7721 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
7723 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7724 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7728 template <typename Derived>
7730 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
7731 DeclarationNameInfo DirName;
7732 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
7734 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7735 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7739 template <typename Derived>
7741 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
7742 DeclarationNameInfo DirName;
7743 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
7745 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7746 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7750 template <typename Derived>
7751 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
7752 OMPTaskgroupDirective *D) {
7753 DeclarationNameInfo DirName;
7754 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
7756 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7757 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7761 template <typename Derived>
7763 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
7764 DeclarationNameInfo DirName;
7765 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
7767 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7768 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7772 template <typename Derived>
7774 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
7775 DeclarationNameInfo DirName;
7776 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
7778 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7779 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7783 template <typename Derived>
7785 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
7786 DeclarationNameInfo DirName;
7787 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
7789 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7790 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7794 template <typename Derived>
7796 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
7797 DeclarationNameInfo DirName;
7798 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
7800 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7801 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7805 template <typename Derived>
7806 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
7807 OMPTargetDataDirective *D) {
7808 DeclarationNameInfo DirName;
7809 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
7811 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7812 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7816 template <typename Derived>
7817 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
7818 OMPTargetEnterDataDirective *D) {
7819 DeclarationNameInfo DirName;
7820 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
7821 nullptr, D->getLocStart());
7822 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7823 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7827 template <typename Derived>
7828 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
7829 OMPTargetExitDataDirective *D) {
7830 DeclarationNameInfo DirName;
7831 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
7832 nullptr, D->getLocStart());
7833 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7834 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7838 template <typename Derived>
7839 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
7840 OMPTargetParallelDirective *D) {
7841 DeclarationNameInfo DirName;
7842 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
7843 nullptr, D->getLocStart());
7844 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7845 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7849 template <typename Derived>
7850 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
7851 OMPTargetParallelForDirective *D) {
7852 DeclarationNameInfo DirName;
7853 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
7854 nullptr, D->getLocStart());
7855 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7856 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7860 template <typename Derived>
7861 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
7862 OMPTargetUpdateDirective *D) {
7863 DeclarationNameInfo DirName;
7864 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
7865 nullptr, D->getLocStart());
7866 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7867 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7871 template <typename Derived>
7873 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
7874 DeclarationNameInfo DirName;
7875 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
7877 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7878 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7882 template <typename Derived>
7883 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
7884 OMPCancellationPointDirective *D) {
7885 DeclarationNameInfo DirName;
7886 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
7887 nullptr, D->getLocStart());
7888 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7889 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7893 template <typename Derived>
7895 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
7896 DeclarationNameInfo DirName;
7897 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
7899 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7900 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7904 template <typename Derived>
7906 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
7907 DeclarationNameInfo DirName;
7908 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
7910 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7911 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7915 template <typename Derived>
7916 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
7917 OMPTaskLoopSimdDirective *D) {
7918 DeclarationNameInfo DirName;
7919 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
7920 nullptr, D->getLocStart());
7921 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7922 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7926 template <typename Derived>
7927 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
7928 OMPDistributeDirective *D) {
7929 DeclarationNameInfo DirName;
7930 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
7932 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7933 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7937 template <typename Derived>
7938 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
7939 OMPDistributeParallelForDirective *D) {
7940 DeclarationNameInfo DirName;
7941 getDerived().getSema().StartOpenMPDSABlock(
7942 OMPD_distribute_parallel_for, DirName, nullptr, D->getLocStart());
7943 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7944 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7948 template <typename Derived>
7950 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
7951 OMPDistributeParallelForSimdDirective *D) {
7952 DeclarationNameInfo DirName;
7953 getDerived().getSema().StartOpenMPDSABlock(
7954 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getLocStart());
7955 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7956 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7960 template <typename Derived>
7961 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
7962 OMPDistributeSimdDirective *D) {
7963 DeclarationNameInfo DirName;
7964 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
7965 nullptr, D->getLocStart());
7966 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7967 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7971 template <typename Derived>
7972 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
7973 OMPTargetParallelForSimdDirective *D) {
7974 DeclarationNameInfo DirName;
7975 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for_simd,
7978 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7979 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7983 template <typename Derived>
7984 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
7985 OMPTargetSimdDirective *D) {
7986 DeclarationNameInfo DirName;
7987 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
7989 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7990 getDerived().getSema().EndOpenMPDSABlock(Res.get());
7994 template <typename Derived>
7995 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
7996 OMPTeamsDistributeDirective *D) {
7997 DeclarationNameInfo DirName;
7998 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
7999 nullptr, D->getLocStart());
8000 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8001 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8005 template <typename Derived>
8006 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8007 OMPTeamsDistributeSimdDirective *D) {
8008 DeclarationNameInfo DirName;
8009 getDerived().getSema().StartOpenMPDSABlock(
8010 OMPD_teams_distribute_simd, DirName, nullptr, D->getLocStart());
8011 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8012 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8016 template <typename Derived>
8017 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8018 OMPTeamsDistributeParallelForSimdDirective *D) {
8019 DeclarationNameInfo DirName;
8020 getDerived().getSema().StartOpenMPDSABlock(
8021 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr, D->getLocStart());
8022 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8023 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8027 template <typename Derived>
8028 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8029 OMPTeamsDistributeParallelForDirective *D) {
8030 DeclarationNameInfo DirName;
8031 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute_parallel_for,
8032 DirName, nullptr, D->getLocStart());
8033 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8034 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8038 template <typename Derived>
8039 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8040 OMPTargetTeamsDirective *D) {
8041 DeclarationNameInfo DirName;
8042 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8043 nullptr, D->getLocStart());
8044 auto Res = getDerived().TransformOMPExecutableDirective(D);
8045 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8049 template <typename Derived>
8050 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8051 OMPTargetTeamsDistributeDirective *D) {
8052 DeclarationNameInfo DirName;
8053 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_distribute,
8054 DirName, nullptr, D->getLocStart());
8055 auto Res = getDerived().TransformOMPExecutableDirective(D);
8056 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8060 template <typename Derived>
8062 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8063 OMPTargetTeamsDistributeParallelForDirective *D) {
8064 DeclarationNameInfo DirName;
8065 getDerived().getSema().StartOpenMPDSABlock(
8066 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8068 auto Res = getDerived().TransformOMPExecutableDirective(D);
8069 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8073 template <typename Derived>
8074 StmtResult TreeTransform<Derived>::
8075 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8076 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8077 DeclarationNameInfo DirName;
8078 getDerived().getSema().StartOpenMPDSABlock(
8079 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8081 auto Res = getDerived().TransformOMPExecutableDirective(D);
8082 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8086 template <typename Derived>
8088 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8089 OMPTargetTeamsDistributeSimdDirective *D) {
8090 DeclarationNameInfo DirName;
8091 getDerived().getSema().StartOpenMPDSABlock(
8092 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getLocStart());
8093 auto Res = getDerived().TransformOMPExecutableDirective(D);
8094 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8099 //===----------------------------------------------------------------------===//
8100 // OpenMP clause transformation
8101 //===----------------------------------------------------------------------===//
8102 template <typename Derived>
8103 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8104 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8105 if (Cond.isInvalid())
8107 return getDerived().RebuildOMPIfClause(
8108 C->getNameModifier(), Cond.get(), C->getLocStart(), C->getLParenLoc(),
8109 C->getNameModifierLoc(), C->getColonLoc(), C->getLocEnd());
8112 template <typename Derived>
8113 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8114 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8115 if (Cond.isInvalid())
8117 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getLocStart(),
8118 C->getLParenLoc(), C->getLocEnd());
8121 template <typename Derived>
8123 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8124 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8125 if (NumThreads.isInvalid())
8127 return getDerived().RebuildOMPNumThreadsClause(
8128 NumThreads.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8131 template <typename Derived>
8133 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8134 ExprResult E = getDerived().TransformExpr(C->getSafelen());
8137 return getDerived().RebuildOMPSafelenClause(
8138 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8141 template <typename Derived>
8143 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8144 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8147 return getDerived().RebuildOMPSimdlenClause(
8148 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8151 template <typename Derived>
8153 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8154 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8157 return getDerived().RebuildOMPCollapseClause(
8158 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8161 template <typename Derived>
8163 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8164 return getDerived().RebuildOMPDefaultClause(
8165 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getLocStart(),
8166 C->getLParenLoc(), C->getLocEnd());
8169 template <typename Derived>
8171 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8172 return getDerived().RebuildOMPProcBindClause(
8173 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getLocStart(),
8174 C->getLParenLoc(), C->getLocEnd());
8177 template <typename Derived>
8179 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8180 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8183 return getDerived().RebuildOMPScheduleClause(
8184 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8185 C->getScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
8186 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8187 C->getScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
8190 template <typename Derived>
8192 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8194 if (auto *Num = C->getNumForLoops()) {
8195 E = getDerived().TransformExpr(Num);
8199 return getDerived().RebuildOMPOrderedClause(C->getLocStart(), C->getLocEnd(),
8200 C->getLParenLoc(), E.get());
8203 template <typename Derived>
8205 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8206 // No need to rebuild this clause, no template-dependent parameters.
8210 template <typename Derived>
8212 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8213 // No need to rebuild this clause, no template-dependent parameters.
8217 template <typename Derived>
8219 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8220 // No need to rebuild this clause, no template-dependent parameters.
8224 template <typename Derived>
8225 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8226 // No need to rebuild this clause, no template-dependent parameters.
8230 template <typename Derived>
8231 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8232 // No need to rebuild this clause, no template-dependent parameters.
8236 template <typename Derived>
8238 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8239 // No need to rebuild this clause, no template-dependent parameters.
8243 template <typename Derived>
8245 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8246 // No need to rebuild this clause, no template-dependent parameters.
8250 template <typename Derived>
8252 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8253 // No need to rebuild this clause, no template-dependent parameters.
8257 template <typename Derived>
8259 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8260 // No need to rebuild this clause, no template-dependent parameters.
8264 template <typename Derived>
8265 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8266 // No need to rebuild this clause, no template-dependent parameters.
8270 template <typename Derived>
8272 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8273 // No need to rebuild this clause, no template-dependent parameters.
8277 template <typename Derived>
8279 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8280 llvm::SmallVector<Expr *, 16> Vars;
8281 Vars.reserve(C->varlist_size());
8282 for (auto *VE : C->varlists()) {
8283 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8284 if (EVar.isInvalid())
8286 Vars.push_back(EVar.get());
8288 return getDerived().RebuildOMPPrivateClause(
8289 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8292 template <typename Derived>
8293 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8294 OMPFirstprivateClause *C) {
8295 llvm::SmallVector<Expr *, 16> Vars;
8296 Vars.reserve(C->varlist_size());
8297 for (auto *VE : C->varlists()) {
8298 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8299 if (EVar.isInvalid())
8301 Vars.push_back(EVar.get());
8303 return getDerived().RebuildOMPFirstprivateClause(
8304 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8307 template <typename Derived>
8309 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8310 llvm::SmallVector<Expr *, 16> Vars;
8311 Vars.reserve(C->varlist_size());
8312 for (auto *VE : C->varlists()) {
8313 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8314 if (EVar.isInvalid())
8316 Vars.push_back(EVar.get());
8318 return getDerived().RebuildOMPLastprivateClause(
8319 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8322 template <typename Derived>
8324 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8325 llvm::SmallVector<Expr *, 16> Vars;
8326 Vars.reserve(C->varlist_size());
8327 for (auto *VE : C->varlists()) {
8328 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8329 if (EVar.isInvalid())
8331 Vars.push_back(EVar.get());
8333 return getDerived().RebuildOMPSharedClause(Vars, C->getLocStart(),
8334 C->getLParenLoc(), C->getLocEnd());
8337 template <typename Derived>
8339 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8340 llvm::SmallVector<Expr *, 16> Vars;
8341 Vars.reserve(C->varlist_size());
8342 for (auto *VE : C->varlists()) {
8343 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8344 if (EVar.isInvalid())
8346 Vars.push_back(EVar.get());
8348 CXXScopeSpec ReductionIdScopeSpec;
8349 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8351 DeclarationNameInfo NameInfo = C->getNameInfo();
8352 if (NameInfo.getName()) {
8353 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8354 if (!NameInfo.getName())
8357 // Build a list of all UDR decls with the same names ranged by the Scopes.
8358 // The Scope boundary is a duplication of the previous decl.
8359 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8360 for (auto *E : C->reduction_ops()) {
8361 // Transform all the decls.
8363 auto *ULE = cast<UnresolvedLookupExpr>(E);
8364 UnresolvedSet<8> Decls;
8365 for (auto *D : ULE->decls()) {
8367 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8368 Decls.addDecl(InstD, InstD->getAccess());
8370 UnresolvedReductions.push_back(
8371 UnresolvedLookupExpr::Create(
8372 SemaRef.Context, /*NamingClass=*/nullptr,
8373 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8374 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8375 Decls.begin(), Decls.end()));
8377 UnresolvedReductions.push_back(nullptr);
8379 return getDerived().RebuildOMPReductionClause(
8380 Vars, C->getLocStart(), C->getLParenLoc(), C->getColonLoc(),
8381 C->getLocEnd(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8384 template <typename Derived>
8386 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8387 llvm::SmallVector<Expr *, 16> Vars;
8388 Vars.reserve(C->varlist_size());
8389 for (auto *VE : C->varlists()) {
8390 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8391 if (EVar.isInvalid())
8393 Vars.push_back(EVar.get());
8395 ExprResult Step = getDerived().TransformExpr(C->getStep());
8396 if (Step.isInvalid())
8398 return getDerived().RebuildOMPLinearClause(
8399 Vars, Step.get(), C->getLocStart(), C->getLParenLoc(), C->getModifier(),
8400 C->getModifierLoc(), C->getColonLoc(), C->getLocEnd());
8403 template <typename Derived>
8405 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8406 llvm::SmallVector<Expr *, 16> Vars;
8407 Vars.reserve(C->varlist_size());
8408 for (auto *VE : C->varlists()) {
8409 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8410 if (EVar.isInvalid())
8412 Vars.push_back(EVar.get());
8414 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8415 if (Alignment.isInvalid())
8417 return getDerived().RebuildOMPAlignedClause(
8418 Vars, Alignment.get(), C->getLocStart(), C->getLParenLoc(),
8419 C->getColonLoc(), C->getLocEnd());
8422 template <typename Derived>
8424 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8425 llvm::SmallVector<Expr *, 16> Vars;
8426 Vars.reserve(C->varlist_size());
8427 for (auto *VE : C->varlists()) {
8428 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8429 if (EVar.isInvalid())
8431 Vars.push_back(EVar.get());
8433 return getDerived().RebuildOMPCopyinClause(Vars, C->getLocStart(),
8434 C->getLParenLoc(), C->getLocEnd());
8437 template <typename Derived>
8439 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8440 llvm::SmallVector<Expr *, 16> Vars;
8441 Vars.reserve(C->varlist_size());
8442 for (auto *VE : C->varlists()) {
8443 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8444 if (EVar.isInvalid())
8446 Vars.push_back(EVar.get());
8448 return getDerived().RebuildOMPCopyprivateClause(
8449 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8452 template <typename Derived>
8453 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8454 llvm::SmallVector<Expr *, 16> Vars;
8455 Vars.reserve(C->varlist_size());
8456 for (auto *VE : C->varlists()) {
8457 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8458 if (EVar.isInvalid())
8460 Vars.push_back(EVar.get());
8462 return getDerived().RebuildOMPFlushClause(Vars, C->getLocStart(),
8463 C->getLParenLoc(), C->getLocEnd());
8466 template <typename Derived>
8468 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
8469 llvm::SmallVector<Expr *, 16> Vars;
8470 Vars.reserve(C->varlist_size());
8471 for (auto *VE : C->varlists()) {
8472 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8473 if (EVar.isInvalid())
8475 Vars.push_back(EVar.get());
8477 return getDerived().RebuildOMPDependClause(
8478 C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
8479 C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8482 template <typename Derived>
8484 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
8485 ExprResult E = getDerived().TransformExpr(C->getDevice());
8488 return getDerived().RebuildOMPDeviceClause(
8489 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8492 template <typename Derived>
8493 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
8494 llvm::SmallVector<Expr *, 16> Vars;
8495 Vars.reserve(C->varlist_size());
8496 for (auto *VE : C->varlists()) {
8497 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8498 if (EVar.isInvalid())
8500 Vars.push_back(EVar.get());
8502 return getDerived().RebuildOMPMapClause(
8503 C->getMapTypeModifier(), C->getMapType(), C->isImplicitMapType(),
8504 C->getMapLoc(), C->getColonLoc(), Vars, C->getLocStart(),
8505 C->getLParenLoc(), C->getLocEnd());
8508 template <typename Derived>
8510 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
8511 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
8514 return getDerived().RebuildOMPNumTeamsClause(
8515 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8518 template <typename Derived>
8520 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
8521 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
8524 return getDerived().RebuildOMPThreadLimitClause(
8525 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8528 template <typename Derived>
8530 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
8531 ExprResult E = getDerived().TransformExpr(C->getPriority());
8534 return getDerived().RebuildOMPPriorityClause(
8535 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8538 template <typename Derived>
8540 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
8541 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
8544 return getDerived().RebuildOMPGrainsizeClause(
8545 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8548 template <typename Derived>
8550 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
8551 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
8554 return getDerived().RebuildOMPNumTasksClause(
8555 E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8558 template <typename Derived>
8559 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
8560 ExprResult E = getDerived().TransformExpr(C->getHint());
8563 return getDerived().RebuildOMPHintClause(E.get(), C->getLocStart(),
8564 C->getLParenLoc(), C->getLocEnd());
8567 template <typename Derived>
8568 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
8569 OMPDistScheduleClause *C) {
8570 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8573 return getDerived().RebuildOMPDistScheduleClause(
8574 C->getDistScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
8575 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
8578 template <typename Derived>
8580 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
8584 template <typename Derived>
8585 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
8586 llvm::SmallVector<Expr *, 16> Vars;
8587 Vars.reserve(C->varlist_size());
8588 for (auto *VE : C->varlists()) {
8589 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8590 if (EVar.isInvalid())
8592 Vars.push_back(EVar.get());
8594 return getDerived().RebuildOMPToClause(Vars, C->getLocStart(),
8595 C->getLParenLoc(), C->getLocEnd());
8598 template <typename Derived>
8599 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
8600 llvm::SmallVector<Expr *, 16> Vars;
8601 Vars.reserve(C->varlist_size());
8602 for (auto *VE : C->varlists()) {
8603 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8604 if (EVar.isInvalid())
8606 Vars.push_back(EVar.get());
8608 return getDerived().RebuildOMPFromClause(Vars, C->getLocStart(),
8609 C->getLParenLoc(), C->getLocEnd());
8612 template <typename Derived>
8613 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
8614 OMPUseDevicePtrClause *C) {
8615 llvm::SmallVector<Expr *, 16> Vars;
8616 Vars.reserve(C->varlist_size());
8617 for (auto *VE : C->varlists()) {
8618 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8619 if (EVar.isInvalid())
8621 Vars.push_back(EVar.get());
8623 return getDerived().RebuildOMPUseDevicePtrClause(
8624 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8627 template <typename Derived>
8629 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
8630 llvm::SmallVector<Expr *, 16> Vars;
8631 Vars.reserve(C->varlist_size());
8632 for (auto *VE : C->varlists()) {
8633 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8634 if (EVar.isInvalid())
8636 Vars.push_back(EVar.get());
8638 return getDerived().RebuildOMPIsDevicePtrClause(
8639 Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
8642 //===----------------------------------------------------------------------===//
8643 // Expression transformation
8644 //===----------------------------------------------------------------------===//
8645 template<typename Derived>
8647 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
8648 if (!E->isTypeDependent())
8651 return getDerived().RebuildPredefinedExpr(E->getLocation(),
8655 template<typename Derived>
8657 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
8658 NestedNameSpecifierLoc QualifierLoc;
8659 if (E->getQualifierLoc()) {
8661 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8667 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
8672 DeclarationNameInfo NameInfo = E->getNameInfo();
8673 if (NameInfo.getName()) {
8674 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8675 if (!NameInfo.getName())
8679 if (!getDerived().AlwaysRebuild() &&
8680 QualifierLoc == E->getQualifierLoc() &&
8681 ND == E->getDecl() &&
8682 NameInfo.getName() == E->getDecl()->getDeclName() &&
8683 !E->hasExplicitTemplateArgs()) {
8685 // Mark it referenced in the new context regardless.
8686 // FIXME: this is a bit instantiation-specific.
8687 SemaRef.MarkDeclRefReferenced(E);
8692 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
8693 if (E->hasExplicitTemplateArgs()) {
8694 TemplateArgs = &TransArgs;
8695 TransArgs.setLAngleLoc(E->getLAngleLoc());
8696 TransArgs.setRAngleLoc(E->getRAngleLoc());
8697 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
8698 E->getNumTemplateArgs(),
8703 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
8707 template<typename Derived>
8709 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
8713 template<typename Derived>
8715 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
8719 template<typename Derived>
8721 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
8725 template<typename Derived>
8727 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
8731 template<typename Derived>
8733 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
8737 template<typename Derived>
8739 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
8740 if (FunctionDecl *FD = E->getDirectCallee())
8741 SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
8742 return SemaRef.MaybeBindToTemporary(E);
8745 template<typename Derived>
8747 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
8748 ExprResult ControllingExpr =
8749 getDerived().TransformExpr(E->getControllingExpr());
8750 if (ControllingExpr.isInvalid())
8753 SmallVector<Expr *, 4> AssocExprs;
8754 SmallVector<TypeSourceInfo *, 4> AssocTypes;
8755 for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
8756 TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
8758 TypeSourceInfo *AssocType = getDerived().TransformType(TS);
8761 AssocTypes.push_back(AssocType);
8763 AssocTypes.push_back(nullptr);
8766 ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
8767 if (AssocExpr.isInvalid())
8769 AssocExprs.push_back(AssocExpr.get());
8772 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
8775 ControllingExpr.get(),
8780 template<typename Derived>
8782 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
8783 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8784 if (SubExpr.isInvalid())
8787 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
8790 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
8794 /// \brief The operand of a unary address-of operator has special rules: it's
8795 /// allowed to refer to a non-static member of a class even if there's no 'this'
8796 /// object available.
8797 template<typename Derived>
8799 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
8800 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
8801 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
8803 return getDerived().TransformExpr(E);
8806 template<typename Derived>
8808 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
8810 if (E->getOpcode() == UO_AddrOf)
8811 SubExpr = TransformAddressOfOperand(E->getSubExpr());
8813 SubExpr = TransformExpr(E->getSubExpr());
8814 if (SubExpr.isInvalid())
8817 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
8820 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
8825 template<typename Derived>
8827 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
8828 // Transform the type.
8829 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
8833 // Transform all of the components into components similar to what the
8835 // FIXME: It would be slightly more efficient in the non-dependent case to
8836 // just map FieldDecls, rather than requiring the rebuilder to look for
8837 // the fields again. However, __builtin_offsetof is rare enough in
8838 // template code that we don't care.
8839 bool ExprChanged = false;
8840 typedef Sema::OffsetOfComponent Component;
8841 SmallVector<Component, 4> Components;
8842 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
8843 const OffsetOfNode &ON = E->getComponent(I);
8845 Comp.isBrackets = true;
8846 Comp.LocStart = ON.getSourceRange().getBegin();
8847 Comp.LocEnd = ON.getSourceRange().getEnd();
8848 switch (ON.getKind()) {
8849 case OffsetOfNode::Array: {
8850 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
8851 ExprResult Index = getDerived().TransformExpr(FromIndex);
8852 if (Index.isInvalid())
8855 ExprChanged = ExprChanged || Index.get() != FromIndex;
8856 Comp.isBrackets = true;
8857 Comp.U.E = Index.get();
8861 case OffsetOfNode::Field:
8862 case OffsetOfNode::Identifier:
8863 Comp.isBrackets = false;
8864 Comp.U.IdentInfo = ON.getFieldName();
8865 if (!Comp.U.IdentInfo)
8870 case OffsetOfNode::Base:
8871 // Will be recomputed during the rebuild.
8875 Components.push_back(Comp);
8878 // If nothing changed, retain the existing expression.
8879 if (!getDerived().AlwaysRebuild() &&
8880 Type == E->getTypeSourceInfo() &&
8884 // Build a new offsetof expression.
8885 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
8886 Components, E->getRParenLoc());
8889 template<typename Derived>
8891 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
8892 assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
8893 "opaque value expression requires transformation");
8897 template<typename Derived>
8899 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
8903 template<typename Derived>
8905 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
8906 // Rebuild the syntactic form. The original syntactic form has
8907 // opaque-value expressions in it, so strip those away and rebuild
8908 // the result. This is a really awful way of doing this, but the
8909 // better solution (rebuilding the semantic expressions and
8910 // rebinding OVEs as necessary) doesn't work; we'd need
8911 // TreeTransform to not strip away implicit conversions.
8912 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
8913 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
8914 if (result.isInvalid()) return ExprError();
8916 // If that gives us a pseudo-object result back, the pseudo-object
8917 // expression must have been an lvalue-to-rvalue conversion which we
8919 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
8920 result = SemaRef.checkPseudoObjectRValue(result.get());
8925 template<typename Derived>
8927 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
8928 UnaryExprOrTypeTraitExpr *E) {
8929 if (E->isArgumentType()) {
8930 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
8932 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
8936 if (!getDerived().AlwaysRebuild() && OldT == NewT)
8939 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
8941 E->getSourceRange());
8944 // C++0x [expr.sizeof]p1:
8945 // The operand is either an expression, which is an unevaluated operand
8947 EnterExpressionEvaluationContext Unevaluated(
8948 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
8949 Sema::ReuseLambdaContextDecl);
8951 // Try to recover if we have something like sizeof(T::X) where X is a type.
8952 // Notably, there must be *exactly* one set of parens if X is a type.
8953 TypeSourceInfo *RecoveryTSI = nullptr;
8955 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
8957 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
8958 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
8959 PE, DRE, false, &RecoveryTSI);
8961 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
8964 return getDerived().RebuildUnaryExprOrTypeTrait(
8965 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
8966 } else if (SubExpr.isInvalid())
8969 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
8972 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
8973 E->getOperatorLoc(),
8975 E->getSourceRange());
8978 template<typename Derived>
8980 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
8981 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
8982 if (LHS.isInvalid())
8985 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
8986 if (RHS.isInvalid())
8990 if (!getDerived().AlwaysRebuild() &&
8991 LHS.get() == E->getLHS() &&
8992 RHS.get() == E->getRHS())
8995 return getDerived().RebuildArraySubscriptExpr(LHS.get(),
8996 /*FIXME:*/E->getLHS()->getLocStart(),
8998 E->getRBracketLoc());
9001 template <typename Derived>
9003 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9004 ExprResult Base = getDerived().TransformExpr(E->getBase());
9005 if (Base.isInvalid())
9008 ExprResult LowerBound;
9009 if (E->getLowerBound()) {
9010 LowerBound = getDerived().TransformExpr(E->getLowerBound());
9011 if (LowerBound.isInvalid())
9016 if (E->getLength()) {
9017 Length = getDerived().TransformExpr(E->getLength());
9018 if (Length.isInvalid())
9022 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9023 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9026 return getDerived().RebuildOMPArraySectionExpr(
9027 Base.get(), E->getBase()->getLocEnd(), LowerBound.get(), E->getColonLoc(),
9028 Length.get(), E->getRBracketLoc());
9031 template<typename Derived>
9033 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9034 // Transform the callee.
9035 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9036 if (Callee.isInvalid())
9039 // Transform arguments.
9040 bool ArgChanged = false;
9041 SmallVector<Expr*, 8> Args;
9042 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9046 if (!getDerived().AlwaysRebuild() &&
9047 Callee.get() == E->getCallee() &&
9049 return SemaRef.MaybeBindToTemporary(E);
9051 // FIXME: Wrong source location information for the '('.
9052 SourceLocation FakeLParenLoc
9053 = ((Expr *)Callee.get())->getSourceRange().getBegin();
9054 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9059 template<typename Derived>
9061 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9062 ExprResult Base = getDerived().TransformExpr(E->getBase());
9063 if (Base.isInvalid())
9066 NestedNameSpecifierLoc QualifierLoc;
9067 if (E->hasQualifier()) {
9069 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9074 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9077 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9078 E->getMemberDecl()));
9082 NamedDecl *FoundDecl = E->getFoundDecl();
9083 if (FoundDecl == E->getMemberDecl()) {
9086 FoundDecl = cast_or_null<NamedDecl>(
9087 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9092 if (!getDerived().AlwaysRebuild() &&
9093 Base.get() == E->getBase() &&
9094 QualifierLoc == E->getQualifierLoc() &&
9095 Member == E->getMemberDecl() &&
9096 FoundDecl == E->getFoundDecl() &&
9097 !E->hasExplicitTemplateArgs()) {
9099 // Mark it referenced in the new context regardless.
9100 // FIXME: this is a bit instantiation-specific.
9101 SemaRef.MarkMemberReferenced(E);
9106 TemplateArgumentListInfo TransArgs;
9107 if (E->hasExplicitTemplateArgs()) {
9108 TransArgs.setLAngleLoc(E->getLAngleLoc());
9109 TransArgs.setRAngleLoc(E->getRAngleLoc());
9110 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9111 E->getNumTemplateArgs(),
9116 // FIXME: Bogus source location for the operator
9117 SourceLocation FakeOperatorLoc =
9118 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9120 // FIXME: to do this check properly, we will need to preserve the
9121 // first-qualifier-in-scope here, just in case we had a dependent
9122 // base (and therefore couldn't do the check) and a
9123 // nested-name-qualifier (and therefore could do the lookup).
9124 NamedDecl *FirstQualifierInScope = nullptr;
9125 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9126 if (MemberNameInfo.getName()) {
9127 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9128 if (!MemberNameInfo.getName())
9132 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9139 (E->hasExplicitTemplateArgs()
9140 ? &TransArgs : nullptr),
9141 FirstQualifierInScope);
9144 template<typename Derived>
9146 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9147 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9148 if (LHS.isInvalid())
9151 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9152 if (RHS.isInvalid())
9155 if (!getDerived().AlwaysRebuild() &&
9156 LHS.get() == E->getLHS() &&
9157 RHS.get() == E->getRHS())
9160 Sema::FPContractStateRAII FPContractState(getSema());
9161 getSema().FPFeatures = E->getFPFeatures();
9163 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9164 LHS.get(), RHS.get());
9167 template<typename Derived>
9169 TreeTransform<Derived>::TransformCompoundAssignOperator(
9170 CompoundAssignOperator *E) {
9171 return getDerived().TransformBinaryOperator(E);
9174 template<typename Derived>
9175 ExprResult TreeTransform<Derived>::
9176 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9177 // Just rebuild the common and RHS expressions and see whether we
9180 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9181 if (commonExpr.isInvalid())
9184 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9185 if (rhs.isInvalid())
9188 if (!getDerived().AlwaysRebuild() &&
9189 commonExpr.get() == e->getCommon() &&
9190 rhs.get() == e->getFalseExpr())
9193 return getDerived().RebuildConditionalOperator(commonExpr.get(),
9194 e->getQuestionLoc(),
9200 template<typename Derived>
9202 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9203 ExprResult Cond = getDerived().TransformExpr(E->getCond());
9204 if (Cond.isInvalid())
9207 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9208 if (LHS.isInvalid())
9211 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9212 if (RHS.isInvalid())
9215 if (!getDerived().AlwaysRebuild() &&
9216 Cond.get() == E->getCond() &&
9217 LHS.get() == E->getLHS() &&
9218 RHS.get() == E->getRHS())
9221 return getDerived().RebuildConditionalOperator(Cond.get(),
9222 E->getQuestionLoc(),
9228 template<typename Derived>
9230 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9231 // Implicit casts are eliminated during transformation, since they
9232 // will be recomputed by semantic analysis after transformation.
9233 return getDerived().TransformExpr(E->getSubExprAsWritten());
9236 template<typename Derived>
9238 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9239 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9244 = getDerived().TransformExpr(E->getSubExprAsWritten());
9245 if (SubExpr.isInvalid())
9248 if (!getDerived().AlwaysRebuild() &&
9249 Type == E->getTypeInfoAsWritten() &&
9250 SubExpr.get() == E->getSubExpr())
9253 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9259 template<typename Derived>
9261 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9262 TypeSourceInfo *OldT = E->getTypeSourceInfo();
9263 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9267 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9268 if (Init.isInvalid())
9271 if (!getDerived().AlwaysRebuild() &&
9273 Init.get() == E->getInitializer())
9274 return SemaRef.MaybeBindToTemporary(E);
9276 // Note: the expression type doesn't necessarily match the
9277 // type-as-written, but that's okay, because it should always be
9278 // derivable from the initializer.
9280 return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
9281 /*FIXME:*/E->getInitializer()->getLocEnd(),
9285 template<typename Derived>
9287 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9288 ExprResult Base = getDerived().TransformExpr(E->getBase());
9289 if (Base.isInvalid())
9292 if (!getDerived().AlwaysRebuild() &&
9293 Base.get() == E->getBase())
9296 // FIXME: Bad source location
9297 SourceLocation FakeOperatorLoc =
9298 SemaRef.getLocForEndOfToken(E->getBase()->getLocEnd());
9299 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9300 E->getAccessorLoc(),
9304 template<typename Derived>
9306 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9307 if (InitListExpr *Syntactic = E->getSyntacticForm())
9310 bool InitChanged = false;
9312 SmallVector<Expr*, 4> Inits;
9313 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
9314 Inits, &InitChanged))
9317 if (!getDerived().AlwaysRebuild() && !InitChanged) {
9318 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
9319 // in some cases. We can't reuse it in general, because the syntactic and
9320 // semantic forms are linked, and we can't know that semantic form will
9321 // match even if the syntactic form does.
9324 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
9325 E->getRBraceLoc(), E->getType());
9328 template<typename Derived>
9330 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
9333 // transform the initializer value
9334 ExprResult Init = getDerived().TransformExpr(E->getInit());
9335 if (Init.isInvalid())
9338 // transform the designators.
9339 SmallVector<Expr*, 4> ArrayExprs;
9340 bool ExprChanged = false;
9341 for (const DesignatedInitExpr::Designator &D : E->designators()) {
9342 if (D.isFieldDesignator()) {
9343 Desig.AddDesignator(Designator::getField(D.getFieldName(),
9347 FieldDecl *Field = cast_or_null<FieldDecl>(
9348 getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
9349 if (Field != D.getField())
9350 // Rebuild the expression when the transformed FieldDecl is
9351 // different to the already assigned FieldDecl.
9354 // Ensure that the designator expression is rebuilt when there isn't
9355 // a resolved FieldDecl in the designator as we don't want to assign
9356 // a FieldDecl to a pattern designator that will be instantiated again.
9362 if (D.isArrayDesignator()) {
9363 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
9364 if (Index.isInvalid())
9367 Desig.AddDesignator(
9368 Designator::getArray(Index.get(), D.getLBracketLoc()));
9370 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
9371 ArrayExprs.push_back(Index.get());
9375 assert(D.isArrayRangeDesignator() && "New kind of designator?");
9377 = getDerived().TransformExpr(E->getArrayRangeStart(D));
9378 if (Start.isInvalid())
9381 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
9382 if (End.isInvalid())
9385 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
9388 D.getEllipsisLoc()));
9390 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
9391 End.get() != E->getArrayRangeEnd(D);
9393 ArrayExprs.push_back(Start.get());
9394 ArrayExprs.push_back(End.get());
9397 if (!getDerived().AlwaysRebuild() &&
9398 Init.get() == E->getInit() &&
9402 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
9403 E->getEqualOrColonLoc(),
9404 E->usesGNUSyntax(), Init.get());
9407 // Seems that if TransformInitListExpr() only works on the syntactic form of an
9408 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
9409 template<typename Derived>
9411 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
9412 DesignatedInitUpdateExpr *E) {
9413 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
9418 template<typename Derived>
9420 TreeTransform<Derived>::TransformNoInitExpr(
9422 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
9426 template<typename Derived>
9428 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
9429 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
9433 template<typename Derived>
9435 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
9436 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
9440 template<typename Derived>
9442 TreeTransform<Derived>::TransformImplicitValueInitExpr(
9443 ImplicitValueInitExpr *E) {
9444 TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
9446 // FIXME: Will we ever have proper type location here? Will we actually
9447 // need to transform the type?
9448 QualType T = getDerived().TransformType(E->getType());
9452 if (!getDerived().AlwaysRebuild() &&
9456 return getDerived().RebuildImplicitValueInitExpr(T);
9459 template<typename Derived>
9461 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
9462 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
9466 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9467 if (SubExpr.isInvalid())
9470 if (!getDerived().AlwaysRebuild() &&
9471 TInfo == E->getWrittenTypeInfo() &&
9472 SubExpr.get() == E->getSubExpr())
9475 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
9476 TInfo, E->getRParenLoc());
9479 template<typename Derived>
9481 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
9482 bool ArgumentChanged = false;
9483 SmallVector<Expr*, 4> Inits;
9484 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
9488 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
9493 /// \brief Transform an address-of-label expression.
9495 /// By default, the transformation of an address-of-label expression always
9496 /// rebuilds the expression, so that the label identifier can be resolved to
9497 /// the corresponding label statement by semantic analysis.
9498 template<typename Derived>
9500 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
9501 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
9506 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
9507 cast<LabelDecl>(LD));
9510 template<typename Derived>
9512 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
9513 SemaRef.ActOnStartStmtExpr();
9515 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
9516 if (SubStmt.isInvalid()) {
9517 SemaRef.ActOnStmtExprError();
9521 if (!getDerived().AlwaysRebuild() &&
9522 SubStmt.get() == E->getSubStmt()) {
9523 // Calling this an 'error' is unintuitive, but it does the right thing.
9524 SemaRef.ActOnStmtExprError();
9525 return SemaRef.MaybeBindToTemporary(E);
9528 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
9533 template<typename Derived>
9535 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
9536 ExprResult Cond = getDerived().TransformExpr(E->getCond());
9537 if (Cond.isInvalid())
9540 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9541 if (LHS.isInvalid())
9544 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9545 if (RHS.isInvalid())
9548 if (!getDerived().AlwaysRebuild() &&
9549 Cond.get() == E->getCond() &&
9550 LHS.get() == E->getLHS() &&
9551 RHS.get() == E->getRHS())
9554 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
9555 Cond.get(), LHS.get(), RHS.get(),
9559 template<typename Derived>
9561 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
9565 template<typename Derived>
9567 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9568 switch (E->getOperator()) {
9572 case OO_Array_Delete:
9573 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
9576 // This is a call to an object's operator().
9577 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
9579 // Transform the object itself.
9580 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
9581 if (Object.isInvalid())
9584 // FIXME: Poor location information
9585 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
9586 static_cast<Expr *>(Object.get())->getLocEnd());
9588 // Transform the call arguments.
9589 SmallVector<Expr*, 8> Args;
9590 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
9594 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
9599 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9601 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
9602 #include "clang/Basic/OperatorKinds.def"
9607 case OO_Conditional:
9608 llvm_unreachable("conditional operator is not actually overloadable");
9611 case NUM_OVERLOADED_OPERATORS:
9612 llvm_unreachable("not an overloaded operator?");
9615 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9616 if (Callee.isInvalid())
9620 if (E->getOperator() == OO_Amp)
9621 First = getDerived().TransformAddressOfOperand(E->getArg(0));
9623 First = getDerived().TransformExpr(E->getArg(0));
9624 if (First.isInvalid())
9628 if (E->getNumArgs() == 2) {
9629 Second = getDerived().TransformExpr(E->getArg(1));
9630 if (Second.isInvalid())
9634 if (!getDerived().AlwaysRebuild() &&
9635 Callee.get() == E->getCallee() &&
9636 First.get() == E->getArg(0) &&
9637 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
9638 return SemaRef.MaybeBindToTemporary(E);
9640 Sema::FPContractStateRAII FPContractState(getSema());
9641 getSema().FPFeatures = E->getFPFeatures();
9643 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
9644 E->getOperatorLoc(),
9650 template<typename Derived>
9652 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
9653 return getDerived().TransformCallExpr(E);
9656 template<typename Derived>
9658 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
9659 // Transform the callee.
9660 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9661 if (Callee.isInvalid())
9664 // Transform exec config.
9665 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
9669 // Transform arguments.
9670 bool ArgChanged = false;
9671 SmallVector<Expr*, 8> Args;
9672 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9676 if (!getDerived().AlwaysRebuild() &&
9677 Callee.get() == E->getCallee() &&
9679 return SemaRef.MaybeBindToTemporary(E);
9681 // FIXME: Wrong source location information for the '('.
9682 SourceLocation FakeLParenLoc
9683 = ((Expr *)Callee.get())->getSourceRange().getBegin();
9684 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9686 E->getRParenLoc(), EC.get());
9689 template<typename Derived>
9691 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
9692 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9697 = getDerived().TransformExpr(E->getSubExprAsWritten());
9698 if (SubExpr.isInvalid())
9701 if (!getDerived().AlwaysRebuild() &&
9702 Type == E->getTypeInfoAsWritten() &&
9703 SubExpr.get() == E->getSubExpr())
9705 return getDerived().RebuildCXXNamedCastExpr(
9706 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
9707 Type, E->getAngleBrackets().getEnd(),
9708 // FIXME. this should be '(' location
9709 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
9712 template<typename Derived>
9714 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
9715 return getDerived().TransformCXXNamedCastExpr(E);
9718 template<typename Derived>
9720 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
9721 return getDerived().TransformCXXNamedCastExpr(E);
9724 template<typename Derived>
9726 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
9727 CXXReinterpretCastExpr *E) {
9728 return getDerived().TransformCXXNamedCastExpr(E);
9731 template<typename Derived>
9733 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
9734 return getDerived().TransformCXXNamedCastExpr(E);
9737 template<typename Derived>
9739 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
9740 CXXFunctionalCastExpr *E) {
9741 TypeSourceInfo *Type =
9742 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
9747 = getDerived().TransformExpr(E->getSubExprAsWritten());
9748 if (SubExpr.isInvalid())
9751 if (!getDerived().AlwaysRebuild() &&
9752 Type == E->getTypeInfoAsWritten() &&
9753 SubExpr.get() == E->getSubExpr())
9756 return getDerived().RebuildCXXFunctionalCastExpr(Type,
9762 template<typename Derived>
9764 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
9765 if (E->isTypeOperand()) {
9766 TypeSourceInfo *TInfo
9767 = getDerived().TransformType(E->getTypeOperandSourceInfo());
9771 if (!getDerived().AlwaysRebuild() &&
9772 TInfo == E->getTypeOperandSourceInfo())
9775 return getDerived().RebuildCXXTypeidExpr(E->getType(),
9781 // We don't know whether the subexpression is potentially evaluated until
9782 // after we perform semantic analysis. We speculatively assume it is
9783 // unevaluated; it will get fixed later if the subexpression is in fact
9784 // potentially evaluated.
9785 EnterExpressionEvaluationContext Unevaluated(
9786 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9787 Sema::ReuseLambdaContextDecl);
9789 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
9790 if (SubExpr.isInvalid())
9793 if (!getDerived().AlwaysRebuild() &&
9794 SubExpr.get() == E->getExprOperand())
9797 return getDerived().RebuildCXXTypeidExpr(E->getType(),
9803 template<typename Derived>
9805 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
9806 if (E->isTypeOperand()) {
9807 TypeSourceInfo *TInfo
9808 = getDerived().TransformType(E->getTypeOperandSourceInfo());
9812 if (!getDerived().AlwaysRebuild() &&
9813 TInfo == E->getTypeOperandSourceInfo())
9816 return getDerived().RebuildCXXUuidofExpr(E->getType(),
9822 EnterExpressionEvaluationContext Unevaluated(
9823 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
9825 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
9826 if (SubExpr.isInvalid())
9829 if (!getDerived().AlwaysRebuild() &&
9830 SubExpr.get() == E->getExprOperand())
9833 return getDerived().RebuildCXXUuidofExpr(E->getType(),
9839 template<typename Derived>
9841 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
9845 template<typename Derived>
9847 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
9848 CXXNullPtrLiteralExpr *E) {
9852 template<typename Derived>
9854 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
9855 QualType T = getSema().getCurrentThisType();
9857 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
9858 // Make sure that we capture 'this'.
9859 getSema().CheckCXXThisCapture(E->getLocStart());
9863 return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
9866 template<typename Derived>
9868 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
9869 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9870 if (SubExpr.isInvalid())
9873 if (!getDerived().AlwaysRebuild() &&
9874 SubExpr.get() == E->getSubExpr())
9877 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
9878 E->isThrownVariableInScope());
9881 template<typename Derived>
9883 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9885 = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
9890 if (!getDerived().AlwaysRebuild() &&
9891 Param == E->getParam())
9894 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
9897 template<typename Derived>
9899 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
9901 = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
9906 if (!getDerived().AlwaysRebuild() && Field == E->getField())
9909 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
9912 template<typename Derived>
9914 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
9915 CXXScalarValueInitExpr *E) {
9916 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
9920 if (!getDerived().AlwaysRebuild() &&
9921 T == E->getTypeSourceInfo())
9924 return getDerived().RebuildCXXScalarValueInitExpr(T,
9925 /*FIXME:*/T->getTypeLoc().getEndLoc(),
9929 template<typename Derived>
9931 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
9932 // Transform the type that we're allocating
9933 TypeSourceInfo *AllocTypeInfo =
9934 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
9938 // Transform the size of the array we're allocating (if any).
9939 ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
9940 if (ArraySize.isInvalid())
9943 // Transform the placement arguments (if any).
9944 bool ArgumentChanged = false;
9945 SmallVector<Expr*, 8> PlacementArgs;
9946 if (getDerived().TransformExprs(E->getPlacementArgs(),
9947 E->getNumPlacementArgs(), true,
9948 PlacementArgs, &ArgumentChanged))
9951 // Transform the initializer (if any).
9952 Expr *OldInit = E->getInitializer();
9955 NewInit = getDerived().TransformInitializer(OldInit, true);
9956 if (NewInit.isInvalid())
9959 // Transform new operator and delete operator.
9960 FunctionDecl *OperatorNew = nullptr;
9961 if (E->getOperatorNew()) {
9962 OperatorNew = cast_or_null<FunctionDecl>(
9963 getDerived().TransformDecl(E->getLocStart(),
9964 E->getOperatorNew()));
9969 FunctionDecl *OperatorDelete = nullptr;
9970 if (E->getOperatorDelete()) {
9971 OperatorDelete = cast_or_null<FunctionDecl>(
9972 getDerived().TransformDecl(E->getLocStart(),
9973 E->getOperatorDelete()));
9974 if (!OperatorDelete)
9978 if (!getDerived().AlwaysRebuild() &&
9979 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
9980 ArraySize.get() == E->getArraySize() &&
9981 NewInit.get() == OldInit &&
9982 OperatorNew == E->getOperatorNew() &&
9983 OperatorDelete == E->getOperatorDelete() &&
9985 // Mark any declarations we need as referenced.
9986 // FIXME: instantiation-specific.
9988 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
9990 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
9992 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
9993 QualType ElementType
9994 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
9995 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
9996 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
9997 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
9998 SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
10006 QualType AllocType = AllocTypeInfo->getType();
10007 if (!ArraySize.get()) {
10008 // If no array size was specified, but the new expression was
10009 // instantiated with an array type (e.g., "new T" where T is
10010 // instantiated with "int[4]"), extract the outer bound from the
10011 // array type as our array size. We do this with constant and
10012 // dependently-sized array types.
10013 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10016 } else if (const ConstantArrayType *ConsArrayT
10017 = dyn_cast<ConstantArrayType>(ArrayT)) {
10018 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10019 SemaRef.Context.getSizeType(),
10020 /*FIXME:*/ E->getLocStart());
10021 AllocType = ConsArrayT->getElementType();
10022 } else if (const DependentSizedArrayType *DepArrayT
10023 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10024 if (DepArrayT->getSizeExpr()) {
10025 ArraySize = DepArrayT->getSizeExpr();
10026 AllocType = DepArrayT->getElementType();
10031 return getDerived().RebuildCXXNewExpr(E->getLocStart(),
10033 /*FIXME:*/E->getLocStart(),
10035 /*FIXME:*/E->getLocStart(),
10036 E->getTypeIdParens(),
10040 E->getDirectInitRange(),
10044 template<typename Derived>
10046 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10047 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10048 if (Operand.isInvalid())
10049 return ExprError();
10051 // Transform the delete operator, if known.
10052 FunctionDecl *OperatorDelete = nullptr;
10053 if (E->getOperatorDelete()) {
10054 OperatorDelete = cast_or_null<FunctionDecl>(
10055 getDerived().TransformDecl(E->getLocStart(),
10056 E->getOperatorDelete()));
10057 if (!OperatorDelete)
10058 return ExprError();
10061 if (!getDerived().AlwaysRebuild() &&
10062 Operand.get() == E->getArgument() &&
10063 OperatorDelete == E->getOperatorDelete()) {
10064 // Mark any declarations we need as referenced.
10065 // FIXME: instantiation-specific.
10066 if (OperatorDelete)
10067 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
10069 if (!E->getArgument()->isTypeDependent()) {
10070 QualType Destroyed = SemaRef.Context.getBaseElementType(
10071 E->getDestroyedType());
10072 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10073 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10074 SemaRef.MarkFunctionReferenced(E->getLocStart(),
10075 SemaRef.LookupDestructor(Record));
10082 return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
10083 E->isGlobalDelete(),
10088 template<typename Derived>
10090 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10091 CXXPseudoDestructorExpr *E) {
10092 ExprResult Base = getDerived().TransformExpr(E->getBase());
10093 if (Base.isInvalid())
10094 return ExprError();
10096 ParsedType ObjectTypePtr;
10097 bool MayBePseudoDestructor = false;
10098 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10099 E->getOperatorLoc(),
10100 E->isArrow()? tok::arrow : tok::period,
10102 MayBePseudoDestructor);
10103 if (Base.isInvalid())
10104 return ExprError();
10106 QualType ObjectType = ObjectTypePtr.get();
10107 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10108 if (QualifierLoc) {
10110 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10112 return ExprError();
10115 SS.Adopt(QualifierLoc);
10117 PseudoDestructorTypeStorage Destroyed;
10118 if (E->getDestroyedTypeInfo()) {
10119 TypeSourceInfo *DestroyedTypeInfo
10120 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10121 ObjectType, nullptr, SS);
10122 if (!DestroyedTypeInfo)
10123 return ExprError();
10124 Destroyed = DestroyedTypeInfo;
10125 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10126 // We aren't likely to be able to resolve the identifier down to a type
10127 // now anyway, so just retain the identifier.
10128 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10129 E->getDestroyedTypeLoc());
10131 // Look for a destructor known with the given name.
10132 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10133 *E->getDestroyedTypeIdentifier(),
10134 E->getDestroyedTypeLoc(),
10139 return ExprError();
10142 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10143 E->getDestroyedTypeLoc());
10146 TypeSourceInfo *ScopeTypeInfo = nullptr;
10147 if (E->getScopeTypeInfo()) {
10148 CXXScopeSpec EmptySS;
10149 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10150 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10151 if (!ScopeTypeInfo)
10152 return ExprError();
10155 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10156 E->getOperatorLoc(),
10160 E->getColonColonLoc(),
10165 template <typename Derived>
10166 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10169 // Transform all the decls.
10170 bool AllEmptyPacks = true;
10171 for (auto *OldD : Old->decls()) {
10172 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10174 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10175 // This can happen because of dependent hiding.
10176 if (isa<UsingShadowDecl>(OldD))
10184 // Expand using pack declarations.
10185 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10186 ArrayRef<NamedDecl*> Decls = SingleDecl;
10187 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10188 Decls = UPD->expansions();
10190 // Expand using declarations.
10191 for (auto *D : Decls) {
10192 if (auto *UD = dyn_cast<UsingDecl>(D)) {
10193 for (auto *SD : UD->shadows())
10200 AllEmptyPacks &= Decls.empty();
10203 // C++ [temp.res]/8.4.2:
10204 // The program is ill-formed, no diagnostic required, if [...] lookup for
10205 // a name in the template definition found a using-declaration, but the
10206 // lookup in the corresponding scope in the instantiation odoes not find
10207 // any declarations because the using-declaration was a pack expansion and
10208 // the corresponding pack is empty
10209 if (AllEmptyPacks && !RequiresADL) {
10210 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10211 << isa<UnresolvedMemberExpr>(Old) << Old->getNameInfo().getName();
10215 // Resolve a kind, but don't do any further analysis. If it's
10216 // ambiguous, the callee needs to deal with it.
10221 template<typename Derived>
10223 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10224 UnresolvedLookupExpr *Old) {
10225 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10226 Sema::LookupOrdinaryName);
10228 // Transform the declaration set.
10229 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10230 return ExprError();
10232 // Rebuild the nested-name qualifier, if present.
10234 if (Old->getQualifierLoc()) {
10235 NestedNameSpecifierLoc QualifierLoc
10236 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10238 return ExprError();
10240 SS.Adopt(QualifierLoc);
10243 if (Old->getNamingClass()) {
10244 CXXRecordDecl *NamingClass
10245 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10247 Old->getNamingClass()));
10248 if (!NamingClass) {
10250 return ExprError();
10253 R.setNamingClass(NamingClass);
10256 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10258 // If we have neither explicit template arguments, nor the template keyword,
10259 // it's a normal declaration name or member reference.
10260 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10261 NamedDecl *D = R.getAsSingle<NamedDecl>();
10262 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10263 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10264 // give a good diagnostic.
10265 if (D && D->isCXXInstanceMember()) {
10266 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10267 /*TemplateArgs=*/nullptr,
10268 /*Scope=*/nullptr);
10271 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10274 // If we have template arguments, rebuild them, then rebuild the
10275 // templateid expression.
10276 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10277 if (Old->hasExplicitTemplateArgs() &&
10278 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10279 Old->getNumTemplateArgs(),
10282 return ExprError();
10285 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10286 Old->requiresADL(), &TransArgs);
10289 template<typename Derived>
10291 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
10292 bool ArgChanged = false;
10293 SmallVector<TypeSourceInfo *, 4> Args;
10294 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
10295 TypeSourceInfo *From = E->getArg(I);
10296 TypeLoc FromTL = From->getTypeLoc();
10297 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
10298 TypeLocBuilder TLB;
10299 TLB.reserve(FromTL.getFullDataSize());
10300 QualType To = getDerived().TransformType(TLB, FromTL);
10302 return ExprError();
10304 if (To == From->getType())
10305 Args.push_back(From);
10307 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10315 // We have a pack expansion. Instantiate it.
10316 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
10317 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
10318 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10319 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
10321 // Determine whether the set of unexpanded parameter packs can and should
10323 bool Expand = true;
10324 bool RetainExpansion = false;
10325 Optional<unsigned> OrigNumExpansions =
10326 ExpansionTL.getTypePtr()->getNumExpansions();
10327 Optional<unsigned> NumExpansions = OrigNumExpansions;
10328 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
10329 PatternTL.getSourceRange(),
10331 Expand, RetainExpansion,
10333 return ExprError();
10336 // The transform has determined that we should perform a simple
10337 // transformation on the pack expansion, producing another pack
10339 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
10341 TypeLocBuilder TLB;
10342 TLB.reserve(From->getTypeLoc().getFullDataSize());
10344 QualType To = getDerived().TransformType(TLB, PatternTL);
10346 return ExprError();
10348 To = getDerived().RebuildPackExpansionType(To,
10349 PatternTL.getSourceRange(),
10350 ExpansionTL.getEllipsisLoc(),
10353 return ExprError();
10355 PackExpansionTypeLoc ToExpansionTL
10356 = TLB.push<PackExpansionTypeLoc>(To);
10357 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10358 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10362 // Expand the pack expansion by substituting for each argument in the
10364 for (unsigned I = 0; I != *NumExpansions; ++I) {
10365 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
10366 TypeLocBuilder TLB;
10367 TLB.reserve(PatternTL.getFullDataSize());
10368 QualType To = getDerived().TransformType(TLB, PatternTL);
10370 return ExprError();
10372 if (To->containsUnexpandedParameterPack()) {
10373 To = getDerived().RebuildPackExpansionType(To,
10374 PatternTL.getSourceRange(),
10375 ExpansionTL.getEllipsisLoc(),
10378 return ExprError();
10380 PackExpansionTypeLoc ToExpansionTL
10381 = TLB.push<PackExpansionTypeLoc>(To);
10382 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10385 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10388 if (!RetainExpansion)
10391 // If we're supposed to retain a pack expansion, do so by temporarily
10392 // forgetting the partially-substituted parameter pack.
10393 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
10395 TypeLocBuilder TLB;
10396 TLB.reserve(From->getTypeLoc().getFullDataSize());
10398 QualType To = getDerived().TransformType(TLB, PatternTL);
10400 return ExprError();
10402 To = getDerived().RebuildPackExpansionType(To,
10403 PatternTL.getSourceRange(),
10404 ExpansionTL.getEllipsisLoc(),
10407 return ExprError();
10409 PackExpansionTypeLoc ToExpansionTL
10410 = TLB.push<PackExpansionTypeLoc>(To);
10411 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10412 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10415 if (!getDerived().AlwaysRebuild() && !ArgChanged)
10418 return getDerived().RebuildTypeTrait(E->getTrait(),
10424 template<typename Derived>
10426 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
10427 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
10429 return ExprError();
10431 if (!getDerived().AlwaysRebuild() &&
10432 T == E->getQueriedTypeSourceInfo())
10435 ExprResult SubExpr;
10437 EnterExpressionEvaluationContext Unevaluated(
10438 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10439 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
10440 if (SubExpr.isInvalid())
10441 return ExprError();
10443 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
10447 return getDerived().RebuildArrayTypeTrait(E->getTrait(),
10454 template<typename Derived>
10456 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
10457 ExprResult SubExpr;
10459 EnterExpressionEvaluationContext Unevaluated(
10460 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10461 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
10462 if (SubExpr.isInvalid())
10463 return ExprError();
10465 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
10469 return getDerived().RebuildExpressionTrait(
10470 E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
10473 template <typename Derived>
10474 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
10475 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
10476 TypeSourceInfo **RecoveryTSI) {
10477 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
10478 DRE, AddrTaken, RecoveryTSI);
10480 // Propagate both errors and recovered types, which return ExprEmpty.
10481 if (!NewDRE.isUsable())
10484 // We got an expr, wrap it up in parens.
10485 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
10487 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
10491 template <typename Derived>
10492 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
10493 DependentScopeDeclRefExpr *E) {
10494 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
10498 template<typename Derived>
10500 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
10501 DependentScopeDeclRefExpr *E,
10502 bool IsAddressOfOperand,
10503 TypeSourceInfo **RecoveryTSI) {
10504 assert(E->getQualifierLoc());
10505 NestedNameSpecifierLoc QualifierLoc
10506 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10508 return ExprError();
10509 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
10511 // TODO: If this is a conversion-function-id, verify that the
10512 // destination type name (if present) resolves the same way after
10513 // instantiation as it did in the local scope.
10515 DeclarationNameInfo NameInfo
10516 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
10517 if (!NameInfo.getName())
10518 return ExprError();
10520 if (!E->hasExplicitTemplateArgs()) {
10521 if (!getDerived().AlwaysRebuild() &&
10522 QualifierLoc == E->getQualifierLoc() &&
10523 // Note: it is sufficient to compare the Name component of NameInfo:
10524 // if name has not changed, DNLoc has not changed either.
10525 NameInfo.getName() == E->getDeclName())
10528 return getDerived().RebuildDependentScopeDeclRefExpr(
10529 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
10530 IsAddressOfOperand, RecoveryTSI);
10533 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
10534 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10535 E->getNumTemplateArgs(),
10537 return ExprError();
10539 return getDerived().RebuildDependentScopeDeclRefExpr(
10540 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
10544 template<typename Derived>
10546 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
10547 // CXXConstructExprs other than for list-initialization and
10548 // CXXTemporaryObjectExpr are always implicit, so when we have
10549 // a 1-argument construction we just transform that argument.
10550 if ((E->getNumArgs() == 1 ||
10551 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
10552 (!getDerived().DropCallArgument(E->getArg(0))) &&
10553 !E->isListInitialization())
10554 return getDerived().TransformExpr(E->getArg(0));
10556 TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
10558 QualType T = getDerived().TransformType(E->getType());
10560 return ExprError();
10562 CXXConstructorDecl *Constructor
10563 = cast_or_null<CXXConstructorDecl>(
10564 getDerived().TransformDecl(E->getLocStart(),
10565 E->getConstructor()));
10567 return ExprError();
10569 bool ArgumentChanged = false;
10570 SmallVector<Expr*, 8> Args;
10571 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10573 return ExprError();
10575 if (!getDerived().AlwaysRebuild() &&
10576 T == E->getType() &&
10577 Constructor == E->getConstructor() &&
10578 !ArgumentChanged) {
10579 // Mark the constructor as referenced.
10580 // FIXME: Instantiation-specific
10581 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
10585 return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
10587 E->isElidable(), Args,
10588 E->hadMultipleCandidates(),
10589 E->isListInitialization(),
10590 E->isStdInitListInitialization(),
10591 E->requiresZeroInitialization(),
10592 E->getConstructionKind(),
10593 E->getParenOrBraceRange());
10596 template<typename Derived>
10597 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
10598 CXXInheritedCtorInitExpr *E) {
10599 QualType T = getDerived().TransformType(E->getType());
10601 return ExprError();
10603 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
10604 getDerived().TransformDecl(E->getLocStart(), E->getConstructor()));
10606 return ExprError();
10608 if (!getDerived().AlwaysRebuild() &&
10609 T == E->getType() &&
10610 Constructor == E->getConstructor()) {
10611 // Mark the constructor as referenced.
10612 // FIXME: Instantiation-specific
10613 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
10617 return getDerived().RebuildCXXInheritedCtorInitExpr(
10618 T, E->getLocation(), Constructor,
10619 E->constructsVBase(), E->inheritedFromVBase());
10622 /// \brief Transform a C++ temporary-binding expression.
10624 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
10625 /// transform the subexpression and return that.
10626 template<typename Derived>
10628 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
10629 return getDerived().TransformExpr(E->getSubExpr());
10632 /// \brief Transform a C++ expression that contains cleanups that should
10633 /// be run after the expression is evaluated.
10635 /// Since ExprWithCleanups nodes are implicitly generated, we
10636 /// just transform the subexpression and return that.
10637 template<typename Derived>
10639 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
10640 return getDerived().TransformExpr(E->getSubExpr());
10643 template<typename Derived>
10645 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
10646 CXXTemporaryObjectExpr *E) {
10647 TypeSourceInfo *T =
10648 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
10650 return ExprError();
10652 CXXConstructorDecl *Constructor
10653 = cast_or_null<CXXConstructorDecl>(
10654 getDerived().TransformDecl(E->getLocStart(),
10655 E->getConstructor()));
10657 return ExprError();
10659 bool ArgumentChanged = false;
10660 SmallVector<Expr*, 8> Args;
10661 Args.reserve(E->getNumArgs());
10662 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10664 return ExprError();
10666 if (!getDerived().AlwaysRebuild() &&
10667 T == E->getTypeSourceInfo() &&
10668 Constructor == E->getConstructor() &&
10669 !ArgumentChanged) {
10670 // FIXME: Instantiation-specific
10671 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
10672 return SemaRef.MaybeBindToTemporary(E);
10675 // FIXME: Pass in E->isListInitialization().
10676 return getDerived().RebuildCXXTemporaryObjectExpr(T,
10677 /*FIXME:*/T->getTypeLoc().getEndLoc(),
10682 template<typename Derived>
10684 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
10685 // Transform any init-capture expressions before entering the scope of the
10686 // lambda body, because they are not semantically within that scope.
10687 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
10688 SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
10689 InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
10690 E->explicit_capture_begin());
10691 for (LambdaExpr::capture_iterator C = E->capture_begin(),
10692 CEnd = E->capture_end();
10694 if (!E->isInitCapture(C))
10696 EnterExpressionEvaluationContext EEEC(
10697 getSema(), Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
10698 ExprResult NewExprInitResult = getDerived().TransformInitializer(
10699 C->getCapturedVar()->getInit(),
10700 C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
10702 if (NewExprInitResult.isInvalid())
10703 return ExprError();
10704 Expr *NewExprInit = NewExprInitResult.get();
10706 VarDecl *OldVD = C->getCapturedVar();
10707 QualType NewInitCaptureType =
10708 getSema().buildLambdaInitCaptureInitialization(
10709 C->getLocation(), OldVD->getType()->isReferenceType(),
10710 OldVD->getIdentifier(),
10711 C->getCapturedVar()->getInitStyle() != VarDecl::CInit, NewExprInit);
10712 NewExprInitResult = NewExprInit;
10713 InitCaptureExprsAndTypes[C - E->capture_begin()] =
10714 std::make_pair(NewExprInitResult, NewInitCaptureType);
10717 // Transform the template parameters, and add them to the current
10718 // instantiation scope. The null case is handled correctly.
10719 auto TPL = getDerived().TransformTemplateParameterList(
10720 E->getTemplateParameterList());
10722 // Transform the type of the original lambda's call operator.
10723 // The transformation MUST be done in the CurrentInstantiationScope since
10724 // it introduces a mapping of the original to the newly created
10725 // transformed parameters.
10726 TypeSourceInfo *NewCallOpTSI = nullptr;
10728 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
10729 FunctionProtoTypeLoc OldCallOpFPTL =
10730 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
10732 TypeLocBuilder NewCallOpTLBuilder;
10733 SmallVector<QualType, 4> ExceptionStorage;
10734 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
10735 QualType NewCallOpType = TransformFunctionProtoType(
10736 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, 0,
10737 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
10738 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
10739 ExceptionStorage, Changed);
10741 if (NewCallOpType.isNull())
10742 return ExprError();
10743 NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
10747 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
10748 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
10749 LSI->GLTemplateParameterList = TPL;
10751 // Create the local class that will describe the lambda.
10752 CXXRecordDecl *Class
10753 = getSema().createLambdaClosureType(E->getIntroducerRange(),
10755 /*KnownDependent=*/false,
10756 E->getCaptureDefault());
10757 getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
10759 // Build the call operator.
10760 CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
10761 Class, E->getIntroducerRange(), NewCallOpTSI,
10762 E->getCallOperator()->getLocEnd(),
10763 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
10764 E->getCallOperator()->isConstexpr());
10766 LSI->CallOperator = NewCallOperator;
10768 for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
10769 I != NumParams; ++I) {
10770 auto *P = NewCallOperator->getParamDecl(I);
10771 if (P->hasUninstantiatedDefaultArg()) {
10772 EnterExpressionEvaluationContext Eval(
10774 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
10775 ExprResult R = getDerived().TransformExpr(
10776 E->getCallOperator()->getParamDecl(I)->getDefaultArg());
10777 P->setDefaultArg(R.get());
10781 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
10782 getDerived().transformedLocalDecl(E->getCallOperator(), NewCallOperator);
10784 // Introduce the context of the call operator.
10785 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
10786 /*NewThisContext*/false);
10788 // Enter the scope of the lambda.
10789 getSema().buildLambdaScope(LSI, NewCallOperator,
10790 E->getIntroducerRange(),
10791 E->getCaptureDefault(),
10792 E->getCaptureDefaultLoc(),
10793 E->hasExplicitParameters(),
10794 E->hasExplicitResultType(),
10797 bool Invalid = false;
10799 // Transform captures.
10800 bool FinishedExplicitCaptures = false;
10801 for (LambdaExpr::capture_iterator C = E->capture_begin(),
10802 CEnd = E->capture_end();
10804 // When we hit the first implicit capture, tell Sema that we've finished
10805 // the list of explicit captures.
10806 if (!FinishedExplicitCaptures && C->isImplicit()) {
10807 getSema().finishLambdaExplicitCaptures(LSI);
10808 FinishedExplicitCaptures = true;
10811 // Capturing 'this' is trivial.
10812 if (C->capturesThis()) {
10813 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
10814 /*BuildAndDiagnose*/ true, nullptr,
10815 C->getCaptureKind() == LCK_StarThis);
10818 // Captured expression will be recaptured during captured variables
10820 if (C->capturesVLAType())
10823 // Rebuild init-captures, including the implied field declaration.
10824 if (E->isInitCapture(C)) {
10825 InitCaptureInfoTy InitExprTypePair =
10826 InitCaptureExprsAndTypes[C - E->capture_begin()];
10827 ExprResult Init = InitExprTypePair.first;
10828 QualType InitQualType = InitExprTypePair.second;
10829 if (Init.isInvalid() || InitQualType.isNull()) {
10833 VarDecl *OldVD = C->getCapturedVar();
10834 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
10835 OldVD->getLocation(), InitExprTypePair.second, OldVD->getIdentifier(),
10836 OldVD->getInitStyle(), Init.get());
10840 getDerived().transformedLocalDecl(OldVD, NewVD);
10842 getSema().buildInitCaptureField(LSI, NewVD);
10846 assert(C->capturesVariable() && "unexpected kind of lambda capture");
10848 // Determine the capture kind for Sema.
10849 Sema::TryCaptureKind Kind
10850 = C->isImplicit()? Sema::TryCapture_Implicit
10851 : C->getCaptureKind() == LCK_ByCopy
10852 ? Sema::TryCapture_ExplicitByVal
10853 : Sema::TryCapture_ExplicitByRef;
10854 SourceLocation EllipsisLoc;
10855 if (C->isPackExpansion()) {
10856 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
10857 bool ShouldExpand = false;
10858 bool RetainExpansion = false;
10859 Optional<unsigned> NumExpansions;
10860 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
10863 ShouldExpand, RetainExpansion,
10869 if (ShouldExpand) {
10870 // The transform has determined that we should perform an expansion;
10871 // transform and capture each of the arguments.
10872 // expansion of the pattern. Do so.
10873 VarDecl *Pack = C->getCapturedVar();
10874 for (unsigned I = 0; I != *NumExpansions; ++I) {
10875 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
10876 VarDecl *CapturedVar
10877 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
10879 if (!CapturedVar) {
10884 // Capture the transformed variable.
10885 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
10888 // FIXME: Retain a pack expansion if RetainExpansion is true.
10893 EllipsisLoc = C->getEllipsisLoc();
10896 // Transform the captured variable.
10897 VarDecl *CapturedVar
10898 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
10899 C->getCapturedVar()));
10900 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
10905 // Capture the transformed variable.
10906 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
10909 if (!FinishedExplicitCaptures)
10910 getSema().finishLambdaExplicitCaptures(LSI);
10912 // Enter a new evaluation context to insulate the lambda from any
10913 // cleanups from the enclosing full-expression.
10914 getSema().PushExpressionEvaluationContext(
10915 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
10917 // Instantiate the body of the lambda expression.
10919 Invalid ? StmtError() : getDerived().TransformStmt(E->getBody());
10921 // ActOnLambda* will pop the function scope for us.
10922 FuncScopeCleanup.disable();
10924 if (Body.isInvalid()) {
10925 SavedContext.pop();
10926 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
10927 /*IsInstantiation=*/true);
10928 return ExprError();
10931 // Copy the LSI before ActOnFinishFunctionBody removes it.
10932 // FIXME: This is dumb. Store the lambda information somewhere that outlives
10933 // the call operator.
10934 auto LSICopy = *LSI;
10935 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
10936 /*IsInstantiation*/ true);
10937 SavedContext.pop();
10939 return getSema().BuildLambdaExpr(E->getLocStart(), Body.get()->getLocEnd(),
10943 template<typename Derived>
10945 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
10946 CXXUnresolvedConstructExpr *E) {
10947 TypeSourceInfo *T =
10948 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
10950 return ExprError();
10952 bool ArgumentChanged = false;
10953 SmallVector<Expr*, 8> Args;
10954 Args.reserve(E->arg_size());
10955 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
10957 return ExprError();
10959 if (!getDerived().AlwaysRebuild() &&
10960 T == E->getTypeSourceInfo() &&
10964 // FIXME: we're faking the locations of the commas
10965 return getDerived().RebuildCXXUnresolvedConstructExpr(T,
10968 E->getRParenLoc());
10971 template<typename Derived>
10973 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
10974 CXXDependentScopeMemberExpr *E) {
10975 // Transform the base of the expression.
10976 ExprResult Base((Expr*) nullptr);
10979 QualType ObjectType;
10980 if (!E->isImplicitAccess()) {
10981 OldBase = E->getBase();
10982 Base = getDerived().TransformExpr(OldBase);
10983 if (Base.isInvalid())
10984 return ExprError();
10986 // Start the member reference and compute the object's type.
10987 ParsedType ObjectTy;
10988 bool MayBePseudoDestructor = false;
10989 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10990 E->getOperatorLoc(),
10991 E->isArrow()? tok::arrow : tok::period,
10993 MayBePseudoDestructor);
10994 if (Base.isInvalid())
10995 return ExprError();
10997 ObjectType = ObjectTy.get();
10998 BaseType = ((Expr*) Base.get())->getType();
11001 BaseType = getDerived().TransformType(E->getBaseType());
11002 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
11005 // Transform the first part of the nested-name-specifier that qualifies
11006 // the member name.
11007 NamedDecl *FirstQualifierInScope
11008 = getDerived().TransformFirstQualifierInScope(
11009 E->getFirstQualifierFoundInScope(),
11010 E->getQualifierLoc().getBeginLoc());
11012 NestedNameSpecifierLoc QualifierLoc;
11013 if (E->getQualifier()) {
11015 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11017 FirstQualifierInScope);
11019 return ExprError();
11022 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11024 // TODO: If this is a conversion-function-id, verify that the
11025 // destination type name (if present) resolves the same way after
11026 // instantiation as it did in the local scope.
11028 DeclarationNameInfo NameInfo
11029 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11030 if (!NameInfo.getName())
11031 return ExprError();
11033 if (!E->hasExplicitTemplateArgs()) {
11034 // This is a reference to a member without an explicitly-specified
11035 // template argument list. Optimize for this common case.
11036 if (!getDerived().AlwaysRebuild() &&
11037 Base.get() == OldBase &&
11038 BaseType == E->getBaseType() &&
11039 QualifierLoc == E->getQualifierLoc() &&
11040 NameInfo.getName() == E->getMember() &&
11041 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11044 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11047 E->getOperatorLoc(),
11050 FirstQualifierInScope,
11052 /*TemplateArgs*/nullptr);
11055 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11056 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11057 E->getNumTemplateArgs(),
11059 return ExprError();
11061 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11064 E->getOperatorLoc(),
11067 FirstQualifierInScope,
11072 template<typename Derived>
11074 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11075 // Transform the base of the expression.
11076 ExprResult Base((Expr*) nullptr);
11078 if (!Old->isImplicitAccess()) {
11079 Base = getDerived().TransformExpr(Old->getBase());
11080 if (Base.isInvalid())
11081 return ExprError();
11082 Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11084 if (Base.isInvalid())
11085 return ExprError();
11086 BaseType = Base.get()->getType();
11088 BaseType = getDerived().TransformType(Old->getBaseType());
11091 NestedNameSpecifierLoc QualifierLoc;
11092 if (Old->getQualifierLoc()) {
11094 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11096 return ExprError();
11099 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11101 LookupResult R(SemaRef, Old->getMemberNameInfo(),
11102 Sema::LookupOrdinaryName);
11104 // Transform the declaration set.
11105 if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11106 return ExprError();
11108 // Determine the naming class.
11109 if (Old->getNamingClass()) {
11110 CXXRecordDecl *NamingClass
11111 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11112 Old->getMemberLoc(),
11113 Old->getNamingClass()));
11115 return ExprError();
11117 R.setNamingClass(NamingClass);
11120 TemplateArgumentListInfo TransArgs;
11121 if (Old->hasExplicitTemplateArgs()) {
11122 TransArgs.setLAngleLoc(Old->getLAngleLoc());
11123 TransArgs.setRAngleLoc(Old->getRAngleLoc());
11124 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11125 Old->getNumTemplateArgs(),
11127 return ExprError();
11130 // FIXME: to do this check properly, we will need to preserve the
11131 // first-qualifier-in-scope here, just in case we had a dependent
11132 // base (and therefore couldn't do the check) and a
11133 // nested-name-qualifier (and therefore could do the lookup).
11134 NamedDecl *FirstQualifierInScope = nullptr;
11136 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11138 Old->getOperatorLoc(),
11142 FirstQualifierInScope,
11144 (Old->hasExplicitTemplateArgs()
11145 ? &TransArgs : nullptr));
11148 template<typename Derived>
11150 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11151 EnterExpressionEvaluationContext Unevaluated(
11152 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11153 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11154 if (SubExpr.isInvalid())
11155 return ExprError();
11157 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11160 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11163 template<typename Derived>
11165 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
11166 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
11167 if (Pattern.isInvalid())
11168 return ExprError();
11170 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
11173 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
11174 E->getNumExpansions());
11177 template<typename Derived>
11179 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
11180 // If E is not value-dependent, then nothing will change when we transform it.
11181 // Note: This is an instantiation-centric view.
11182 if (!E->isValueDependent())
11185 EnterExpressionEvaluationContext Unevaluated(
11186 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
11188 ArrayRef<TemplateArgument> PackArgs;
11189 TemplateArgument ArgStorage;
11191 // Find the argument list to transform.
11192 if (E->isPartiallySubstituted()) {
11193 PackArgs = E->getPartialArguments();
11194 } else if (E->isValueDependent()) {
11195 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
11196 bool ShouldExpand = false;
11197 bool RetainExpansion = false;
11198 Optional<unsigned> NumExpansions;
11199 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
11201 ShouldExpand, RetainExpansion,
11203 return ExprError();
11205 // If we need to expand the pack, build a template argument from it and
11207 if (ShouldExpand) {
11208 auto *Pack = E->getPack();
11209 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
11210 ArgStorage = getSema().Context.getPackExpansionType(
11211 getSema().Context.getTypeDeclType(TTPD), None);
11212 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
11213 ArgStorage = TemplateArgument(TemplateName(TTPD), None);
11215 auto *VD = cast<ValueDecl>(Pack);
11216 ExprResult DRE = getSema().BuildDeclRefExpr(VD, VD->getType(),
11217 VK_RValue, E->getPackLoc());
11218 if (DRE.isInvalid())
11219 return ExprError();
11220 ArgStorage = new (getSema().Context) PackExpansionExpr(
11221 getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
11223 PackArgs = ArgStorage;
11227 // If we're not expanding the pack, just transform the decl.
11228 if (!PackArgs.size()) {
11229 auto *Pack = cast_or_null<NamedDecl>(
11230 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
11232 return ExprError();
11233 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
11235 E->getRParenLoc(), None, None);
11238 // Try to compute the result without performing a partial substitution.
11239 Optional<unsigned> Result = 0;
11240 for (const TemplateArgument &Arg : PackArgs) {
11241 if (!Arg.isPackExpansion()) {
11242 Result = *Result + 1;
11246 TemplateArgumentLoc ArgLoc;
11247 InventTemplateArgumentLoc(Arg, ArgLoc);
11249 // Find the pattern of the pack expansion.
11250 SourceLocation Ellipsis;
11251 Optional<unsigned> OrigNumExpansions;
11252 TemplateArgumentLoc Pattern =
11253 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
11254 OrigNumExpansions);
11256 // Substitute under the pack expansion. Do not expand the pack (yet).
11257 TemplateArgumentLoc OutPattern;
11258 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11259 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
11263 // See if we can determine the number of arguments from the result.
11264 Optional<unsigned> NumExpansions =
11265 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
11266 if (!NumExpansions) {
11267 // No: we must be in an alias template expansion, and we're going to need
11268 // to actually expand the packs.
11273 Result = *Result + *NumExpansions;
11276 // Common case: we could determine the number of expansions without
11279 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11281 E->getRParenLoc(), *Result, None);
11283 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
11286 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
11287 typedef TemplateArgumentLocInventIterator<
11288 Derived, const TemplateArgument*> PackLocIterator;
11289 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
11290 PackLocIterator(*this, PackArgs.end()),
11291 TransformedPackArgs, /*Uneval*/true))
11292 return ExprError();
11295 // Check whether we managed to fully-expand the pack.
11296 // FIXME: Is it possible for us to do so and not hit the early exit path?
11297 SmallVector<TemplateArgument, 8> Args;
11298 bool PartialSubstitution = false;
11299 for (auto &Loc : TransformedPackArgs.arguments()) {
11300 Args.push_back(Loc.getArgument());
11301 if (Loc.getArgument().isPackExpansion())
11302 PartialSubstitution = true;
11305 if (PartialSubstitution)
11306 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11308 E->getRParenLoc(), None, Args);
11310 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11311 E->getPackLoc(), E->getRParenLoc(),
11312 Args.size(), None);
11315 template<typename Derived>
11317 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
11318 SubstNonTypeTemplateParmPackExpr *E) {
11319 // Default behavior is to do nothing with this transformation.
11323 template<typename Derived>
11325 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
11326 SubstNonTypeTemplateParmExpr *E) {
11327 // Default behavior is to do nothing with this transformation.
11331 template<typename Derived>
11333 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
11334 // Default behavior is to do nothing with this transformation.
11338 template<typename Derived>
11340 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
11341 MaterializeTemporaryExpr *E) {
11342 return getDerived().TransformExpr(E->GetTemporaryExpr());
11345 template<typename Derived>
11347 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
11348 Expr *Pattern = E->getPattern();
11350 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11351 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
11352 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
11354 // Determine whether the set of unexpanded parameter packs can and should
11356 bool Expand = true;
11357 bool RetainExpansion = false;
11358 Optional<unsigned> NumExpansions;
11359 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
11360 Pattern->getSourceRange(),
11362 Expand, RetainExpansion,
11367 // Do not expand any packs here, just transform and rebuild a fold
11369 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11372 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
11373 if (LHS.isInvalid())
11377 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
11378 if (RHS.isInvalid())
11381 if (!getDerived().AlwaysRebuild() &&
11382 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
11385 return getDerived().RebuildCXXFoldExpr(
11386 E->getLocStart(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
11387 RHS.get(), E->getLocEnd());
11390 // The transform has determined that we should perform an elementwise
11391 // expansion of the pattern. Do so.
11392 ExprResult Result = getDerived().TransformExpr(E->getInit());
11393 if (Result.isInvalid())
11395 bool LeftFold = E->isLeftFold();
11397 // If we're retaining an expansion for a right fold, it is the innermost
11398 // component and takes the init (if any).
11399 if (!LeftFold && RetainExpansion) {
11400 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11402 ExprResult Out = getDerived().TransformExpr(Pattern);
11403 if (Out.isInvalid())
11406 Result = getDerived().RebuildCXXFoldExpr(
11407 E->getLocStart(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
11408 Result.get(), E->getLocEnd());
11409 if (Result.isInvalid())
11413 for (unsigned I = 0; I != *NumExpansions; ++I) {
11414 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
11415 getSema(), LeftFold ? I : *NumExpansions - I - 1);
11416 ExprResult Out = getDerived().TransformExpr(Pattern);
11417 if (Out.isInvalid())
11420 if (Out.get()->containsUnexpandedParameterPack()) {
11421 // We still have a pack; retain a pack expansion for this slice.
11422 Result = getDerived().RebuildCXXFoldExpr(
11424 LeftFold ? Result.get() : Out.get(),
11425 E->getOperator(), E->getEllipsisLoc(),
11426 LeftFold ? Out.get() : Result.get(),
11428 } else if (Result.isUsable()) {
11429 // We've got down to a single element; build a binary operator.
11430 Result = getDerived().RebuildBinaryOperator(
11431 E->getEllipsisLoc(), E->getOperator(),
11432 LeftFold ? Result.get() : Out.get(),
11433 LeftFold ? Out.get() : Result.get());
11437 if (Result.isInvalid())
11441 // If we're retaining an expansion for a left fold, it is the outermost
11442 // component and takes the complete expansion so far as its init (if any).
11443 if (LeftFold && RetainExpansion) {
11444 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11446 ExprResult Out = getDerived().TransformExpr(Pattern);
11447 if (Out.isInvalid())
11450 Result = getDerived().RebuildCXXFoldExpr(
11451 E->getLocStart(), Result.get(),
11452 E->getOperator(), E->getEllipsisLoc(),
11453 Out.get(), E->getLocEnd());
11454 if (Result.isInvalid())
11458 // If we had no init and an empty pack, and we're not retaining an expansion,
11459 // then produce a fallback value or error.
11460 if (Result.isUnset())
11461 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
11467 template<typename Derived>
11469 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
11470 CXXStdInitializerListExpr *E) {
11471 return getDerived().TransformExpr(E->getSubExpr());
11474 template<typename Derived>
11476 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
11477 return SemaRef.MaybeBindToTemporary(E);
11480 template<typename Derived>
11482 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
11486 template<typename Derived>
11488 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
11489 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11490 if (SubExpr.isInvalid())
11491 return ExprError();
11493 if (!getDerived().AlwaysRebuild() &&
11494 SubExpr.get() == E->getSubExpr())
11497 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
11500 template<typename Derived>
11502 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
11503 // Transform each of the elements.
11504 SmallVector<Expr *, 8> Elements;
11505 bool ArgChanged = false;
11506 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
11507 /*IsCall=*/false, Elements, &ArgChanged))
11508 return ExprError();
11510 if (!getDerived().AlwaysRebuild() && !ArgChanged)
11511 return SemaRef.MaybeBindToTemporary(E);
11513 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
11518 template<typename Derived>
11520 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
11521 ObjCDictionaryLiteral *E) {
11522 // Transform each of the elements.
11523 SmallVector<ObjCDictionaryElement, 8> Elements;
11524 bool ArgChanged = false;
11525 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
11526 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
11528 if (OrigElement.isPackExpansion()) {
11529 // This key/value element is a pack expansion.
11530 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11531 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
11532 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
11533 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
11535 // Determine whether the set of unexpanded parameter packs can
11536 // and should be expanded.
11537 bool Expand = true;
11538 bool RetainExpansion = false;
11539 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
11540 Optional<unsigned> NumExpansions = OrigNumExpansions;
11541 SourceRange PatternRange(OrigElement.Key->getLocStart(),
11542 OrigElement.Value->getLocEnd());
11543 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
11546 Expand, RetainExpansion,
11548 return ExprError();
11551 // The transform has determined that we should perform a simple
11552 // transformation on the pack expansion, producing another pack
11554 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11555 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11556 if (Key.isInvalid())
11557 return ExprError();
11559 if (Key.get() != OrigElement.Key)
11562 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
11563 if (Value.isInvalid())
11564 return ExprError();
11566 if (Value.get() != OrigElement.Value)
11569 ObjCDictionaryElement Expansion = {
11570 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
11572 Elements.push_back(Expansion);
11576 // Record right away that the argument was changed. This needs
11577 // to happen even if the array expands to nothing.
11580 // The transform has determined that we should perform an elementwise
11581 // expansion of the pattern. Do so.
11582 for (unsigned I = 0; I != *NumExpansions; ++I) {
11583 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11584 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11585 if (Key.isInvalid())
11586 return ExprError();
11588 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
11589 if (Value.isInvalid())
11590 return ExprError();
11592 ObjCDictionaryElement Element = {
11593 Key.get(), Value.get(), SourceLocation(), NumExpansions
11596 // If any unexpanded parameter packs remain, we still have a
11598 // FIXME: Can this really happen?
11599 if (Key.get()->containsUnexpandedParameterPack() ||
11600 Value.get()->containsUnexpandedParameterPack())
11601 Element.EllipsisLoc = OrigElement.EllipsisLoc;
11603 Elements.push_back(Element);
11606 // FIXME: Retain a pack expansion if RetainExpansion is true.
11608 // We've finished with this pack expansion.
11612 // Transform and check key.
11613 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11614 if (Key.isInvalid())
11615 return ExprError();
11617 if (Key.get() != OrigElement.Key)
11620 // Transform and check value.
11622 = getDerived().TransformExpr(OrigElement.Value);
11623 if (Value.isInvalid())
11624 return ExprError();
11626 if (Value.get() != OrigElement.Value)
11629 ObjCDictionaryElement Element = {
11630 Key.get(), Value.get(), SourceLocation(), None
11632 Elements.push_back(Element);
11635 if (!getDerived().AlwaysRebuild() && !ArgChanged)
11636 return SemaRef.MaybeBindToTemporary(E);
11638 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
11642 template<typename Derived>
11644 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
11645 TypeSourceInfo *EncodedTypeInfo
11646 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
11647 if (!EncodedTypeInfo)
11648 return ExprError();
11650 if (!getDerived().AlwaysRebuild() &&
11651 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
11654 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
11656 E->getRParenLoc());
11659 template<typename Derived>
11660 ExprResult TreeTransform<Derived>::
11661 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
11662 // This is a kind of implicit conversion, and it needs to get dropped
11663 // and recomputed for the same general reasons that ImplicitCastExprs
11664 // do, as well a more specific one: this expression is only valid when
11665 // it appears *immediately* as an argument expression.
11666 return getDerived().TransformExpr(E->getSubExpr());
11669 template<typename Derived>
11670 ExprResult TreeTransform<Derived>::
11671 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
11672 TypeSourceInfo *TSInfo
11673 = getDerived().TransformType(E->getTypeInfoAsWritten());
11675 return ExprError();
11677 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
11678 if (Result.isInvalid())
11679 return ExprError();
11681 if (!getDerived().AlwaysRebuild() &&
11682 TSInfo == E->getTypeInfoAsWritten() &&
11683 Result.get() == E->getSubExpr())
11686 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
11687 E->getBridgeKeywordLoc(), TSInfo,
11691 template <typename Derived>
11692 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
11693 ObjCAvailabilityCheckExpr *E) {
11697 template<typename Derived>
11699 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
11700 // Transform arguments.
11701 bool ArgChanged = false;
11702 SmallVector<Expr*, 8> Args;
11703 Args.reserve(E->getNumArgs());
11704 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
11706 return ExprError();
11708 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
11709 // Class message: transform the receiver type.
11710 TypeSourceInfo *ReceiverTypeInfo
11711 = getDerived().TransformType(E->getClassReceiverTypeInfo());
11712 if (!ReceiverTypeInfo)
11713 return ExprError();
11715 // If nothing changed, just retain the existing message send.
11716 if (!getDerived().AlwaysRebuild() &&
11717 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
11718 return SemaRef.MaybeBindToTemporary(E);
11720 // Build a new class message send.
11721 SmallVector<SourceLocation, 16> SelLocs;
11722 E->getSelectorLocs(SelLocs);
11723 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
11726 E->getMethodDecl(),
11731 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
11732 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11733 if (!E->getMethodDecl())
11734 return ExprError();
11736 // Build a new class message send to 'super'.
11737 SmallVector<SourceLocation, 16> SelLocs;
11738 E->getSelectorLocs(SelLocs);
11739 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
11742 E->getReceiverType(),
11743 E->getMethodDecl(),
11749 // Instance message: transform the receiver
11750 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
11751 "Only class and instance messages may be instantiated");
11752 ExprResult Receiver
11753 = getDerived().TransformExpr(E->getInstanceReceiver());
11754 if (Receiver.isInvalid())
11755 return ExprError();
11757 // If nothing changed, just retain the existing message send.
11758 if (!getDerived().AlwaysRebuild() &&
11759 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
11760 return SemaRef.MaybeBindToTemporary(E);
11762 // Build a new instance message send.
11763 SmallVector<SourceLocation, 16> SelLocs;
11764 E->getSelectorLocs(SelLocs);
11765 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
11768 E->getMethodDecl(),
11774 template<typename Derived>
11776 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
11780 template<typename Derived>
11782 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
11786 template<typename Derived>
11788 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
11789 // Transform the base expression.
11790 ExprResult Base = getDerived().TransformExpr(E->getBase());
11791 if (Base.isInvalid())
11792 return ExprError();
11794 // We don't need to transform the ivar; it will never change.
11796 // If nothing changed, just retain the existing expression.
11797 if (!getDerived().AlwaysRebuild() &&
11798 Base.get() == E->getBase())
11801 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
11803 E->isArrow(), E->isFreeIvar());
11806 template<typename Derived>
11808 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
11809 // 'super' and types never change. Property never changes. Just
11810 // retain the existing expression.
11811 if (!E->isObjectReceiver())
11814 // Transform the base expression.
11815 ExprResult Base = getDerived().TransformExpr(E->getBase());
11816 if (Base.isInvalid())
11817 return ExprError();
11819 // We don't need to transform the property; it will never change.
11821 // If nothing changed, just retain the existing expression.
11822 if (!getDerived().AlwaysRebuild() &&
11823 Base.get() == E->getBase())
11826 if (E->isExplicitProperty())
11827 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
11828 E->getExplicitProperty(),
11831 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
11832 SemaRef.Context.PseudoObjectTy,
11833 E->getImplicitPropertyGetter(),
11834 E->getImplicitPropertySetter(),
11838 template<typename Derived>
11840 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
11841 // Transform the base expression.
11842 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
11843 if (Base.isInvalid())
11844 return ExprError();
11846 // Transform the key expression.
11847 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
11848 if (Key.isInvalid())
11849 return ExprError();
11851 // If nothing changed, just retain the existing expression.
11852 if (!getDerived().AlwaysRebuild() &&
11853 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
11856 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
11857 Base.get(), Key.get(),
11858 E->getAtIndexMethodDecl(),
11859 E->setAtIndexMethodDecl());
11862 template<typename Derived>
11864 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
11865 // Transform the base expression.
11866 ExprResult Base = getDerived().TransformExpr(E->getBase());
11867 if (Base.isInvalid())
11868 return ExprError();
11870 // If nothing changed, just retain the existing expression.
11871 if (!getDerived().AlwaysRebuild() &&
11872 Base.get() == E->getBase())
11875 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
11880 template<typename Derived>
11882 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
11883 bool ArgumentChanged = false;
11884 SmallVector<Expr*, 8> SubExprs;
11885 SubExprs.reserve(E->getNumSubExprs());
11886 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
11887 SubExprs, &ArgumentChanged))
11888 return ExprError();
11890 if (!getDerived().AlwaysRebuild() &&
11894 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
11896 E->getRParenLoc());
11899 template<typename Derived>
11901 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
11902 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
11903 if (SrcExpr.isInvalid())
11904 return ExprError();
11906 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
11908 return ExprError();
11910 if (!getDerived().AlwaysRebuild() &&
11911 Type == E->getTypeSourceInfo() &&
11912 SrcExpr.get() == E->getSrcExpr())
11915 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
11916 SrcExpr.get(), Type,
11917 E->getRParenLoc());
11920 template<typename Derived>
11922 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
11923 BlockDecl *oldBlock = E->getBlockDecl();
11925 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
11926 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
11928 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
11929 blockScope->TheDecl->setBlockMissingReturnType(
11930 oldBlock->blockMissingReturnType());
11932 SmallVector<ParmVarDecl*, 4> params;
11933 SmallVector<QualType, 4> paramTypes;
11935 const FunctionProtoType *exprFunctionType = E->getFunctionType();
11937 // Parameter substitution.
11938 Sema::ExtParameterInfoBuilder extParamInfos;
11939 if (getDerived().TransformFunctionTypeParams(
11940 E->getCaretLocation(), oldBlock->parameters(), nullptr,
11941 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, ¶ms,
11943 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
11944 return ExprError();
11947 QualType exprResultType =
11948 getDerived().TransformType(exprFunctionType->getReturnType());
11950 auto epi = exprFunctionType->getExtProtoInfo();
11951 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
11953 QualType functionType =
11954 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
11955 blockScope->FunctionType = functionType;
11957 // Set the parameters on the block decl.
11958 if (!params.empty())
11959 blockScope->TheDecl->setParams(params);
11961 if (!oldBlock->blockMissingReturnType()) {
11962 blockScope->HasImplicitReturnType = false;
11963 blockScope->ReturnType = exprResultType;
11966 // Transform the body
11967 StmtResult body = getDerived().TransformStmt(E->getBody());
11968 if (body.isInvalid()) {
11969 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
11970 return ExprError();
11974 // In builds with assertions, make sure that we captured everything we
11975 // captured before.
11976 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
11977 for (const auto &I : oldBlock->captures()) {
11978 VarDecl *oldCapture = I.getVariable();
11980 // Ignore parameter packs.
11981 if (isa<ParmVarDecl>(oldCapture) &&
11982 cast<ParmVarDecl>(oldCapture)->isParameterPack())
11985 VarDecl *newCapture =
11986 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
11988 assert(blockScope->CaptureMap.count(newCapture));
11990 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
11994 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
11995 /*Scope=*/nullptr);
11998 template<typename Derived>
12000 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12001 llvm_unreachable("Cannot transform asType expressions yet");
12004 template<typename Derived>
12006 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12007 QualType RetTy = getDerived().TransformType(E->getType());
12008 bool ArgumentChanged = false;
12009 SmallVector<Expr*, 8> SubExprs;
12010 SubExprs.reserve(E->getNumSubExprs());
12011 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12012 SubExprs, &ArgumentChanged))
12013 return ExprError();
12015 if (!getDerived().AlwaysRebuild() &&
12019 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12020 RetTy, E->getOp(), E->getRParenLoc());
12023 //===----------------------------------------------------------------------===//
12024 // Type reconstruction
12025 //===----------------------------------------------------------------------===//
12027 template<typename Derived>
12028 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12029 SourceLocation Star) {
12030 return SemaRef.BuildPointerType(PointeeType, Star,
12031 getDerived().getBaseEntity());
12034 template<typename Derived>
12035 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12036 SourceLocation Star) {
12037 return SemaRef.BuildBlockPointerType(PointeeType, Star,
12038 getDerived().getBaseEntity());
12041 template<typename Derived>
12043 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12044 bool WrittenAsLValue,
12045 SourceLocation Sigil) {
12046 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12047 Sigil, getDerived().getBaseEntity());
12050 template<typename Derived>
12052 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12053 QualType ClassType,
12054 SourceLocation Sigil) {
12055 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12056 getDerived().getBaseEntity());
12059 template<typename Derived>
12060 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12061 const ObjCTypeParamDecl *Decl,
12062 SourceLocation ProtocolLAngleLoc,
12063 ArrayRef<ObjCProtocolDecl *> Protocols,
12064 ArrayRef<SourceLocation> ProtocolLocs,
12065 SourceLocation ProtocolRAngleLoc) {
12066 return SemaRef.BuildObjCTypeParamType(Decl,
12067 ProtocolLAngleLoc, Protocols,
12068 ProtocolLocs, ProtocolRAngleLoc,
12069 /*FailOnError=*/true);
12072 template<typename Derived>
12073 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12075 SourceLocation Loc,
12076 SourceLocation TypeArgsLAngleLoc,
12077 ArrayRef<TypeSourceInfo *> TypeArgs,
12078 SourceLocation TypeArgsRAngleLoc,
12079 SourceLocation ProtocolLAngleLoc,
12080 ArrayRef<ObjCProtocolDecl *> Protocols,
12081 ArrayRef<SourceLocation> ProtocolLocs,
12082 SourceLocation ProtocolRAngleLoc) {
12083 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12084 TypeArgs, TypeArgsRAngleLoc,
12085 ProtocolLAngleLoc, Protocols, ProtocolLocs,
12087 /*FailOnError=*/true);
12090 template<typename Derived>
12091 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12092 QualType PointeeType,
12093 SourceLocation Star) {
12094 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12097 template<typename Derived>
12099 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12100 ArrayType::ArraySizeModifier SizeMod,
12101 const llvm::APInt *Size,
12103 unsigned IndexTypeQuals,
12104 SourceRange BracketsRange) {
12105 if (SizeExpr || !Size)
12106 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12107 IndexTypeQuals, BracketsRange,
12108 getDerived().getBaseEntity());
12110 QualType Types[] = {
12111 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12112 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12113 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12115 const unsigned NumTypes = llvm::array_lengthof(Types);
12117 for (unsigned I = 0; I != NumTypes; ++I)
12118 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12119 SizeType = Types[I];
12123 // Note that we can return a VariableArrayType here in the case where
12124 // the element type was a dependent VariableArrayType.
12125 IntegerLiteral *ArraySize
12126 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12127 /*FIXME*/BracketsRange.getBegin());
12128 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12129 IndexTypeQuals, BracketsRange,
12130 getDerived().getBaseEntity());
12133 template<typename Derived>
12135 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12136 ArrayType::ArraySizeModifier SizeMod,
12137 const llvm::APInt &Size,
12138 unsigned IndexTypeQuals,
12139 SourceRange BracketsRange) {
12140 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
12141 IndexTypeQuals, BracketsRange);
12144 template<typename Derived>
12146 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12147 ArrayType::ArraySizeModifier SizeMod,
12148 unsigned IndexTypeQuals,
12149 SourceRange BracketsRange) {
12150 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12151 IndexTypeQuals, BracketsRange);
12154 template<typename Derived>
12156 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12157 ArrayType::ArraySizeModifier SizeMod,
12159 unsigned IndexTypeQuals,
12160 SourceRange BracketsRange) {
12161 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12163 IndexTypeQuals, BracketsRange);
12166 template<typename Derived>
12168 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
12169 ArrayType::ArraySizeModifier SizeMod,
12171 unsigned IndexTypeQuals,
12172 SourceRange BracketsRange) {
12173 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12175 IndexTypeQuals, BracketsRange);
12178 template<typename Derived>
12179 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
12180 unsigned NumElements,
12181 VectorType::VectorKind VecKind) {
12182 // FIXME: semantic checking!
12183 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
12186 template<typename Derived>
12187 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
12188 unsigned NumElements,
12189 SourceLocation AttributeLoc) {
12190 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
12191 NumElements, true);
12192 IntegerLiteral *VectorSize
12193 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
12195 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
12198 template<typename Derived>
12200 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
12202 SourceLocation AttributeLoc) {
12203 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
12206 template<typename Derived>
12207 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
12209 MutableArrayRef<QualType> ParamTypes,
12210 const FunctionProtoType::ExtProtoInfo &EPI) {
12211 return SemaRef.BuildFunctionType(T, ParamTypes,
12212 getDerived().getBaseLocation(),
12213 getDerived().getBaseEntity(),
12217 template<typename Derived>
12218 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
12219 return SemaRef.Context.getFunctionNoProtoType(T);
12222 template<typename Derived>
12223 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
12225 assert(D && "no decl found");
12226 if (D->isInvalidDecl()) return QualType();
12228 // FIXME: Doesn't account for ObjCInterfaceDecl!
12230 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
12231 // A valid resolved using typename pack expansion decl can have multiple
12232 // UsingDecls, but they must each have exactly one type, and it must be
12233 // the same type in every case. But we must have at least one expansion!
12234 if (UPD->expansions().empty()) {
12235 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
12236 << UPD->isCXXClassMember() << UPD;
12240 // We might still have some unresolved types. Try to pick a resolved type
12241 // if we can. The final instantiation will check that the remaining
12242 // unresolved types instantiate to the type we pick.
12243 QualType FallbackT;
12245 for (auto *E : UPD->expansions()) {
12246 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
12247 if (ThisT.isNull())
12249 else if (ThisT->getAs<UnresolvedUsingType>())
12251 else if (T.isNull())
12254 assert(getSema().Context.hasSameType(ThisT, T) &&
12255 "mismatched resolved types in using pack expansion");
12257 return T.isNull() ? FallbackT : T;
12258 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
12259 assert(Using->hasTypename() &&
12260 "UnresolvedUsingTypenameDecl transformed to non-typename using");
12262 // A valid resolved using typename decl points to exactly one type decl.
12263 assert(++Using->shadow_begin() == Using->shadow_end());
12264 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
12266 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
12267 "UnresolvedUsingTypenameDecl transformed to non-using decl");
12268 Ty = cast<UnresolvedUsingTypenameDecl>(D);
12271 return SemaRef.Context.getTypeDeclType(Ty);
12274 template<typename Derived>
12275 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
12276 SourceLocation Loc) {
12277 return SemaRef.BuildTypeofExprType(E, Loc);
12280 template<typename Derived>
12281 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
12282 return SemaRef.Context.getTypeOfType(Underlying);
12285 template<typename Derived>
12286 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
12287 SourceLocation Loc) {
12288 return SemaRef.BuildDecltypeType(E, Loc);
12291 template<typename Derived>
12292 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
12293 UnaryTransformType::UTTKind UKind,
12294 SourceLocation Loc) {
12295 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
12298 template<typename Derived>
12299 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
12300 TemplateName Template,
12301 SourceLocation TemplateNameLoc,
12302 TemplateArgumentListInfo &TemplateArgs) {
12303 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
12306 template<typename Derived>
12307 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
12308 SourceLocation KWLoc) {
12309 return SemaRef.BuildAtomicType(ValueType, KWLoc);
12312 template<typename Derived>
12313 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
12314 SourceLocation KWLoc,
12316 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
12317 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
12320 template<typename Derived>
12322 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12324 TemplateDecl *Template) {
12325 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
12329 template<typename Derived>
12331 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12332 const IdentifierInfo &Name,
12333 SourceLocation NameLoc,
12334 QualType ObjectType,
12335 NamedDecl *FirstQualifierInScope,
12336 bool AllowInjectedClassName) {
12337 UnqualifiedId TemplateName;
12338 TemplateName.setIdentifier(&Name, NameLoc);
12339 Sema::TemplateTy Template;
12340 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12341 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
12342 SS, TemplateKWLoc, TemplateName,
12343 ParsedType::make(ObjectType),
12344 /*EnteringContext=*/false,
12345 Template, AllowInjectedClassName);
12346 return Template.get();
12349 template<typename Derived>
12351 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12352 OverloadedOperatorKind Operator,
12353 SourceLocation NameLoc,
12354 QualType ObjectType,
12355 bool AllowInjectedClassName) {
12356 UnqualifiedId Name;
12357 // FIXME: Bogus location information.
12358 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
12359 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
12360 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12361 Sema::TemplateTy Template;
12362 getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
12363 SS, TemplateKWLoc, Name,
12364 ParsedType::make(ObjectType),
12365 /*EnteringContext=*/false,
12366 Template, AllowInjectedClassName);
12367 return Template.get();
12370 template<typename Derived>
12372 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
12373 SourceLocation OpLoc,
12377 Expr *Callee = OrigCallee->IgnoreParenCasts();
12378 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
12380 if (First->getObjectKind() == OK_ObjCProperty) {
12381 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12382 if (BinaryOperator::isAssignmentOp(Opc))
12383 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
12385 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
12386 if (Result.isInvalid())
12387 return ExprError();
12388 First = Result.get();
12391 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
12392 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
12393 if (Result.isInvalid())
12394 return ExprError();
12395 Second = Result.get();
12398 // Determine whether this should be a builtin operation.
12399 if (Op == OO_Subscript) {
12400 if (!First->getType()->isOverloadableType() &&
12401 !Second->getType()->isOverloadableType())
12402 return getSema().CreateBuiltinArraySubscriptExpr(First,
12403 Callee->getLocStart(),
12405 } else if (Op == OO_Arrow) {
12406 // -> is never a builtin operation.
12407 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
12408 } else if (Second == nullptr || isPostIncDec) {
12409 if (!First->getType()->isOverloadableType()) {
12410 // The argument is not of overloadable type, so try to create a
12411 // built-in unary operation.
12412 UnaryOperatorKind Opc
12413 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
12415 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
12418 if (!First->getType()->isOverloadableType() &&
12419 !Second->getType()->isOverloadableType()) {
12420 // Neither of the arguments is an overloadable type, so try to
12421 // create a built-in binary operation.
12422 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12424 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
12425 if (Result.isInvalid())
12426 return ExprError();
12432 // Compute the transformed set of functions (and function templates) to be
12433 // used during overload resolution.
12434 UnresolvedSet<16> Functions;
12436 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
12437 assert(ULE->requiresADL());
12438 Functions.append(ULE->decls_begin(), ULE->decls_end());
12440 // If we've resolved this to a particular non-member function, just call
12441 // that function. If we resolved it to a member function,
12442 // CreateOverloaded* will find that function for us.
12443 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
12444 if (!isa<CXXMethodDecl>(ND))
12445 Functions.addDecl(ND);
12448 // Add any functions found via argument-dependent lookup.
12449 Expr *Args[2] = { First, Second };
12450 unsigned NumArgs = 1 + (Second != nullptr);
12452 // Create the overloaded operator invocation for unary operators.
12453 if (NumArgs == 1 || isPostIncDec) {
12454 UnaryOperatorKind Opc
12455 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
12456 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
12459 if (Op == OO_Subscript) {
12460 SourceLocation LBrace;
12461 SourceLocation RBrace;
12463 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
12464 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
12465 LBrace = SourceLocation::getFromRawEncoding(
12466 NameLoc.CXXOperatorName.BeginOpNameLoc);
12467 RBrace = SourceLocation::getFromRawEncoding(
12468 NameLoc.CXXOperatorName.EndOpNameLoc);
12470 LBrace = Callee->getLocStart();
12474 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
12478 // Create the overloaded operator invocation for binary operators.
12479 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12481 = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
12482 if (Result.isInvalid())
12483 return ExprError();
12488 template<typename Derived>
12490 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
12491 SourceLocation OperatorLoc,
12494 TypeSourceInfo *ScopeType,
12495 SourceLocation CCLoc,
12496 SourceLocation TildeLoc,
12497 PseudoDestructorTypeStorage Destroyed) {
12498 QualType BaseType = Base->getType();
12499 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
12500 (!isArrow && !BaseType->getAs<RecordType>()) ||
12501 (isArrow && BaseType->getAs<PointerType>() &&
12502 !BaseType->getAs<PointerType>()->getPointeeType()
12503 ->template getAs<RecordType>())){
12504 // This pseudo-destructor expression is still a pseudo-destructor.
12505 return SemaRef.BuildPseudoDestructorExpr(
12506 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
12507 CCLoc, TildeLoc, Destroyed);
12510 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
12511 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
12512 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
12513 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
12514 NameInfo.setNamedTypeInfo(DestroyedType);
12516 // The scope type is now known to be a valid nested name specifier
12517 // component. Tack it on to the end of the nested name specifier.
12519 if (!ScopeType->getType()->getAs<TagType>()) {
12520 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
12521 diag::err_expected_class_or_namespace)
12522 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
12523 return ExprError();
12525 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
12529 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12530 return getSema().BuildMemberReferenceExpr(Base, BaseType,
12531 OperatorLoc, isArrow,
12533 /*FIXME: FirstQualifier*/ nullptr,
12535 /*TemplateArgs*/ nullptr,
12539 template<typename Derived>
12541 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
12542 SourceLocation Loc = S->getLocStart();
12543 CapturedDecl *CD = S->getCapturedDecl();
12544 unsigned NumParams = CD->getNumParams();
12545 unsigned ContextParamPos = CD->getContextParamPosition();
12546 SmallVector<Sema::CapturedParamNameType, 4> Params;
12547 for (unsigned I = 0; I < NumParams; ++I) {
12548 if (I != ContextParamPos) {
12551 CD->getParam(I)->getName(),
12552 getDerived().TransformType(CD->getParam(I)->getType())));
12554 Params.push_back(std::make_pair(StringRef(), QualType()));
12557 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
12558 S->getCapturedRegionKind(), Params);
12561 Sema::CompoundScopeRAII CompoundScope(getSema());
12562 Body = getDerived().TransformStmt(S->getCapturedStmt());
12565 if (Body.isInvalid()) {
12566 getSema().ActOnCapturedRegionError();
12567 return StmtError();
12570 return getSema().ActOnCapturedRegionEnd(Body.get());
12573 } // end namespace clang
12575 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H