1 //===- DeclTemplate.h - Classes for representing C++ templates --*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Defines the C++ template declaration subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
15 #define LLVM_CLANG_AST_DECLTEMPLATE_H
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/Redeclarable.h"
22 #include "clang/AST/TemplateBase.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Basic/LLVM.h"
25 #include "clang/Basic/SourceLocation.h"
26 #include "clang/Basic/Specifiers.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/FoldingSet.h"
29 #include "llvm/ADT/PointerIntPair.h"
30 #include "llvm/ADT/PointerUnion.h"
31 #include "llvm/ADT/iterator.h"
32 #include "llvm/ADT/iterator_range.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/TrailingObjects.h"
44 enum BuiltinTemplateKind : int;
45 class ClassTemplateDecl;
46 class ClassTemplatePartialSpecializationDecl;
48 class FunctionTemplateDecl;
50 class NonTypeTemplateParmDecl;
52 class TemplateTemplateParmDecl;
53 class TemplateTypeParmDecl;
54 class UnresolvedSetImpl;
55 class VarTemplateDecl;
56 class VarTemplatePartialSpecializationDecl;
58 /// Stores a template parameter of any kind.
59 using TemplateParameter =
60 llvm::PointerUnion3<TemplateTypeParmDecl *, NonTypeTemplateParmDecl *,
61 TemplateTemplateParmDecl *>;
63 NamedDecl *getAsNamedDecl(TemplateParameter P);
65 /// Stores a list of template parameters for a TemplateDecl and its
67 class TemplateParameterList final
68 : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
70 /// The location of the 'template' keyword.
71 SourceLocation TemplateLoc;
73 /// The locations of the '<' and '>' angle brackets.
74 SourceLocation LAngleLoc, RAngleLoc;
76 /// The number of template parameters in this template
78 unsigned NumParams : 30;
80 /// Whether this template parameter list contains an unexpanded parameter
82 unsigned ContainsUnexpandedParameterPack : 1;
84 /// Whether this template parameter list has an associated requires-clause
85 unsigned HasRequiresClause : 1;
88 TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
89 ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc,
90 Expr *RequiresClause);
92 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
96 size_t numTrailingObjects(OverloadToken<Expr *>) const {
97 return HasRequiresClause;
101 template <size_t N, bool HasRequiresClause>
102 friend class FixedSizeTemplateParameterListStorage;
103 friend TrailingObjects;
105 static TemplateParameterList *Create(const ASTContext &C,
106 SourceLocation TemplateLoc,
107 SourceLocation LAngleLoc,
108 ArrayRef<NamedDecl *> Params,
109 SourceLocation RAngleLoc,
110 Expr *RequiresClause);
112 /// Iterates through the template parameters in this list.
113 using iterator = NamedDecl **;
115 /// Iterates through the template parameters in this list.
116 using const_iterator = NamedDecl * const *;
118 iterator begin() { return getTrailingObjects<NamedDecl *>(); }
119 const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
120 iterator end() { return begin() + NumParams; }
121 const_iterator end() const { return begin() + NumParams; }
123 unsigned size() const { return NumParams; }
125 ArrayRef<NamedDecl*> asArray() {
126 return llvm::makeArrayRef(begin(), end());
128 ArrayRef<const NamedDecl*> asArray() const {
129 return llvm::makeArrayRef(begin(), size());
132 NamedDecl* getParam(unsigned Idx) {
133 assert(Idx < size() && "Template parameter index out-of-range");
136 const NamedDecl* getParam(unsigned Idx) const {
137 assert(Idx < size() && "Template parameter index out-of-range");
141 /// Returns the minimum number of arguments needed to form a
142 /// template specialization.
144 /// This may be fewer than the number of template parameters, if some of
145 /// the parameters have default arguments or if there is a parameter pack.
146 unsigned getMinRequiredArguments() const;
148 /// Get the depth of this template parameter list in the set of
149 /// template parameter lists.
151 /// The first template parameter list in a declaration will have depth 0,
152 /// the second template parameter list will have depth 1, etc.
153 unsigned getDepth() const;
155 /// Determine whether this template parameter list contains an
156 /// unexpanded parameter pack.
157 bool containsUnexpandedParameterPack() const {
158 return ContainsUnexpandedParameterPack;
161 /// The constraint-expression of the associated requires-clause.
162 Expr *getRequiresClause() {
163 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
166 /// The constraint-expression of the associated requires-clause.
167 const Expr *getRequiresClause() const {
168 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
171 /// \brief All associated constraints derived from this template parameter
172 /// list, including the requires clause and any constraints derived from
173 /// constrained-parameters.
175 /// The constraints in the resulting list are to be treated as if in a
176 /// conjunction ("and").
177 void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const;
179 bool hasAssociatedConstraints() const;
181 SourceLocation getTemplateLoc() const { return TemplateLoc; }
182 SourceLocation getLAngleLoc() const { return LAngleLoc; }
183 SourceLocation getRAngleLoc() const { return RAngleLoc; }
185 SourceRange getSourceRange() const LLVM_READONLY {
186 return SourceRange(TemplateLoc, RAngleLoc);
189 void print(raw_ostream &Out, const ASTContext &Context,
190 bool OmitTemplateKW = false) const;
191 void print(raw_ostream &Out, const ASTContext &Context,
192 const PrintingPolicy &Policy, bool OmitTemplateKW = false) const;
195 // FIXME: workaround for MSVC 2013; remove when no longer needed
196 using FixedSizeStorageOwner = TrailingObjects::FixedSizeStorageOwner;
199 /// Stores a list of template parameters and the associated
200 /// requires-clause (if any) for a TemplateDecl and its derived classes.
201 /// Suitable for creating on the stack.
202 template <size_t N, bool HasRequiresClause>
203 class FixedSizeTemplateParameterListStorage
204 : public TemplateParameterList::FixedSizeStorageOwner {
205 typename TemplateParameterList::FixedSizeStorage<
206 NamedDecl *, Expr *>::with_counts<
207 N, HasRequiresClause ? 1u : 0u
211 FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
212 SourceLocation LAngleLoc,
213 ArrayRef<NamedDecl *> Params,
214 SourceLocation RAngleLoc,
215 Expr *RequiresClause)
216 : FixedSizeStorageOwner(
217 (assert(N == Params.size()),
218 assert(HasRequiresClause == static_cast<bool>(RequiresClause)),
219 new (static_cast<void *>(&storage)) TemplateParameterList(
220 TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
223 /// A template argument list.
224 class TemplateArgumentList final
225 : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
226 /// The template argument list.
227 const TemplateArgument *Arguments;
229 /// The number of template arguments in this template
231 unsigned NumArguments;
233 // Constructs an instance with an internal Argument list, containing
234 // a copy of the Args array. (Called by CreateCopy)
235 TemplateArgumentList(ArrayRef<TemplateArgument> Args);
238 friend TrailingObjects;
240 TemplateArgumentList(const TemplateArgumentList &) = delete;
241 TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
243 /// Type used to indicate that the template argument list itself is a
244 /// stack object. It does not own its template arguments.
245 enum OnStackType { OnStack };
247 /// Create a new template argument list that copies the given set of
248 /// template arguments.
249 static TemplateArgumentList *CreateCopy(ASTContext &Context,
250 ArrayRef<TemplateArgument> Args);
252 /// Construct a new, temporary template argument list on the stack.
254 /// The template argument list does not own the template arguments
256 explicit TemplateArgumentList(OnStackType, ArrayRef<TemplateArgument> Args)
257 : Arguments(Args.data()), NumArguments(Args.size()) {}
259 /// Produces a shallow copy of the given template argument list.
261 /// This operation assumes that the input argument list outlives it.
262 /// This takes the list as a pointer to avoid looking like a copy
263 /// constructor, since this really really isn't safe to use that
265 explicit TemplateArgumentList(const TemplateArgumentList *Other)
266 : Arguments(Other->data()), NumArguments(Other->size()) {}
268 /// Retrieve the template argument at a given index.
269 const TemplateArgument &get(unsigned Idx) const {
270 assert(Idx < NumArguments && "Invalid template argument index");
274 /// Retrieve the template argument at a given index.
275 const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
277 /// Produce this as an array ref.
278 ArrayRef<TemplateArgument> asArray() const {
279 return llvm::makeArrayRef(data(), size());
282 /// Retrieve the number of template arguments in this
283 /// template argument list.
284 unsigned size() const { return NumArguments; }
286 /// Retrieve a pointer to the template argument list.
287 const TemplateArgument *data() const { return Arguments; }
290 void *allocateDefaultArgStorageChain(const ASTContext &C);
292 /// Storage for a default argument. This is conceptually either empty, or an
293 /// argument value, or a pointer to a previous declaration that had a default
296 /// However, this is complicated by modules: while we require all the default
297 /// arguments for a template to be equivalent, there may be more than one, and
298 /// we need to track all the originating parameters to determine if the default
299 /// argument is visible.
300 template<typename ParmDecl, typename ArgType>
301 class DefaultArgStorage {
302 /// Storage for both the value *and* another parameter from which we inherit
303 /// the default argument. This is used when multiple default arguments for a
304 /// parameter are merged together from different modules.
306 ParmDecl *PrevDeclWithDefaultArg;
309 static_assert(sizeof(Chain) == sizeof(void *) * 2,
310 "non-pointer argument type?");
312 llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
314 static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
315 const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
316 if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl *>())
318 assert(!Parm->getDefaultArgStorage()
319 .ValueOrInherited.template is<ParmDecl *>() &&
320 "should only be one level of indirection");
325 DefaultArgStorage() : ValueOrInherited(ArgType()) {}
327 /// Determine whether there is a default argument for this parameter.
328 bool isSet() const { return !ValueOrInherited.isNull(); }
330 /// Determine whether the default argument for this parameter was inherited
331 /// from a previous declaration of the same entity.
332 bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
334 /// Get the default argument's value. This does not consider whether the
335 /// default argument is visible.
336 ArgType get() const {
337 const DefaultArgStorage *Storage = this;
338 if (const auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl *>())
339 Storage = &Prev->getDefaultArgStorage();
340 if (const auto *C = Storage->ValueOrInherited.template dyn_cast<Chain *>())
342 return Storage->ValueOrInherited.template get<ArgType>();
345 /// Get the parameter from which we inherit the default argument, if any.
346 /// This is the parameter on which the default argument was actually written.
347 const ParmDecl *getInheritedFrom() const {
348 if (const auto *D = ValueOrInherited.template dyn_cast<ParmDecl *>())
350 if (const auto *C = ValueOrInherited.template dyn_cast<Chain *>())
351 return C->PrevDeclWithDefaultArg;
355 /// Set the default argument.
356 void set(ArgType Arg) {
357 assert(!isSet() && "default argument already set");
358 ValueOrInherited = Arg;
361 /// Set that the default argument was inherited from another parameter.
362 void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
363 assert(!isInherited() && "default argument already inherited");
364 InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
366 ValueOrInherited = InheritedFrom;
368 ValueOrInherited = new (allocateDefaultArgStorageChain(C))
369 Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
372 /// Remove the default argument, even if it was inherited.
374 ValueOrInherited = ArgType();
378 //===----------------------------------------------------------------------===//
379 // Kinds of Templates
380 //===----------------------------------------------------------------------===//
382 /// \brief The base class of all kinds of template declarations (e.g.,
383 /// class, function, etc.).
385 /// The TemplateDecl class stores the list of template parameters and a
386 /// reference to the templated scoped declaration: the underlying AST node.
387 class TemplateDecl : public NamedDecl {
388 void anchor() override;
391 // Construct a template decl with name, parameters, and templated element.
392 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
393 TemplateParameterList *Params, NamedDecl *Decl);
395 // Construct a template decl with the given name and parameters.
396 // Used when there is no templated element (e.g., for tt-params).
397 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
398 TemplateParameterList *Params)
399 : TemplateDecl(DK, DC, L, Name, Params, nullptr) {}
402 friend class ASTDeclReader;
403 friend class ASTDeclWriter;
405 /// Get the list of template parameters
406 TemplateParameterList *getTemplateParameters() const {
407 return TemplateParams;
410 /// \brief Get the total constraint-expression associated with this template,
411 /// including constraint-expressions derived from the requires-clause,
412 /// trailing requires-clause (for functions and methods) and constrained
413 /// template parameters.
414 void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const;
416 bool hasAssociatedConstraints() const;
418 /// Get the underlying, templated declaration.
419 NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
421 // Implement isa/cast/dyncast/etc.
422 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
424 static bool classofKind(Kind K) {
425 return K >= firstTemplate && K <= lastTemplate;
428 SourceRange getSourceRange() const override LLVM_READONLY {
429 return SourceRange(getTemplateParameters()->getTemplateLoc(),
430 TemplatedDecl->getSourceRange().getEnd());
434 NamedDecl *TemplatedDecl;
435 TemplateParameterList *TemplateParams;
437 void setTemplateParameters(TemplateParameterList *TParams) {
438 TemplateParams = TParams;
442 /// Initialize the underlying templated declaration and
443 /// template parameters.
444 void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
445 assert(!TemplatedDecl && "TemplatedDecl already set!");
446 assert(!TemplateParams && "TemplateParams already set!");
447 TemplatedDecl = templatedDecl;
448 TemplateParams = templateParams;
452 /// Provides information about a function template specialization,
453 /// which is a FunctionDecl that has been explicitly specialization or
454 /// instantiated from a function template.
455 class FunctionTemplateSpecializationInfo final
456 : public llvm::FoldingSetNode,
457 private llvm::TrailingObjects<FunctionTemplateSpecializationInfo,
458 MemberSpecializationInfo *> {
459 /// The function template specialization that this structure describes and a
460 /// flag indicating if the function is a member specialization.
461 llvm::PointerIntPair<FunctionDecl *, 1, bool> Function;
463 /// The function template from which this function template
464 /// specialization was generated.
466 /// The two bits contain the top 4 values of TemplateSpecializationKind.
467 llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
470 /// The template arguments used to produce the function template
471 /// specialization from the function template.
472 const TemplateArgumentList *TemplateArguments;
474 /// The template arguments as written in the sources, if provided.
475 /// FIXME: Normally null; tail-allocate this.
476 const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
478 /// The point at which this function template specialization was
479 /// first instantiated.
480 SourceLocation PointOfInstantiation;
483 FunctionTemplateSpecializationInfo(
484 FunctionDecl *FD, FunctionTemplateDecl *Template,
485 TemplateSpecializationKind TSK, const TemplateArgumentList *TemplateArgs,
486 const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
487 SourceLocation POI, MemberSpecializationInfo *MSInfo)
488 : Function(FD, MSInfo ? 1 : 0), Template(Template, TSK - 1),
489 TemplateArguments(TemplateArgs),
490 TemplateArgumentsAsWritten(TemplateArgsAsWritten),
491 PointOfInstantiation(POI) {
493 getTrailingObjects<MemberSpecializationInfo *>()[0] = MSInfo;
496 size_t numTrailingObjects(OverloadToken<MemberSpecializationInfo*>) const {
497 return Function.getInt();
501 friend TrailingObjects;
503 static FunctionTemplateSpecializationInfo *
504 Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
505 TemplateSpecializationKind TSK,
506 const TemplateArgumentList *TemplateArgs,
507 const TemplateArgumentListInfo *TemplateArgsAsWritten,
508 SourceLocation POI, MemberSpecializationInfo *MSInfo);
510 /// Retrieve the declaration of the function template specialization.
511 FunctionDecl *getFunction() const { return Function.getPointer(); }
513 /// Retrieve the template from which this function was specialized.
514 FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
516 /// Determine what kind of template specialization this is.
517 TemplateSpecializationKind getTemplateSpecializationKind() const {
518 return (TemplateSpecializationKind)(Template.getInt() + 1);
521 bool isExplicitSpecialization() const {
522 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
525 /// True if this declaration is an explicit specialization,
526 /// explicit instantiation declaration, or explicit instantiation
528 bool isExplicitInstantiationOrSpecialization() const {
529 return isTemplateExplicitInstantiationOrSpecialization(
530 getTemplateSpecializationKind());
533 /// Set the template specialization kind.
534 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
535 assert(TSK != TSK_Undeclared &&
536 "Cannot encode TSK_Undeclared for a function template specialization");
537 Template.setInt(TSK - 1);
540 /// Retrieve the first point of instantiation of this function
541 /// template specialization.
543 /// The point of instantiation may be an invalid source location if this
544 /// function has yet to be instantiated.
545 SourceLocation getPointOfInstantiation() const {
546 return PointOfInstantiation;
549 /// Set the (first) point of instantiation of this function template
551 void setPointOfInstantiation(SourceLocation POI) {
552 PointOfInstantiation = POI;
555 /// Get the specialization info if this function template specialization is
556 /// also a member specialization:
559 /// template<typename> struct A {
560 /// template<typename> void f();
561 /// template<> void f<int>(); // ClassScopeFunctionSpecializationDecl
565 /// Here, A<int>::f<int> is a function template specialization that is
566 /// an explicit specialization of A<int>::f, but it's also a member
567 /// specialization (an implicit instantiation in this case) of A::f<int>.
571 /// template<> template<> void A<int>::f<int>() {}
574 /// ... declares a function template specialization that is an explicit
575 /// specialization of A<int>::f, and is also an explicit member
576 /// specialization of A::f<int>.
578 /// Note that the TemplateSpecializationKind of the MemberSpecializationInfo
579 /// need not be the same as that returned by getTemplateSpecializationKind(),
580 /// and represents the relationship between the function and the class-scope
581 /// explicit specialization in the original templated class -- whereas our
582 /// TemplateSpecializationKind represents the relationship between the
583 /// function and the function template, and should always be
584 /// TSK_ExplicitSpecialization whenever we have MemberSpecializationInfo.
585 MemberSpecializationInfo *getMemberSpecializationInfo() const {
586 return numTrailingObjects(OverloadToken<MemberSpecializationInfo *>())
587 ? getTrailingObjects<MemberSpecializationInfo *>()[0]
591 void Profile(llvm::FoldingSetNodeID &ID) {
592 Profile(ID, TemplateArguments->asArray(), getFunction()->getASTContext());
596 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
597 ASTContext &Context) {
598 ID.AddInteger(TemplateArgs.size());
599 for (const TemplateArgument &TemplateArg : TemplateArgs)
600 TemplateArg.Profile(ID, Context);
604 /// Provides information a specialization of a member of a class
605 /// template, which may be a member function, static data member,
606 /// member class or member enumeration.
607 class MemberSpecializationInfo {
608 // The member declaration from which this member was instantiated, and the
609 // manner in which the instantiation occurred (in the lower two bits).
610 llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
612 // The point at which this member was first instantiated.
613 SourceLocation PointOfInstantiation;
617 MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
618 SourceLocation POI = SourceLocation())
619 : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
620 assert(TSK != TSK_Undeclared &&
621 "Cannot encode undeclared template specializations for members");
624 /// Retrieve the member declaration from which this member was
626 NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
628 /// Determine what kind of template specialization this is.
629 TemplateSpecializationKind getTemplateSpecializationKind() const {
630 return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
633 bool isExplicitSpecialization() const {
634 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
637 /// Set the template specialization kind.
638 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
639 assert(TSK != TSK_Undeclared &&
640 "Cannot encode undeclared template specializations for members");
641 MemberAndTSK.setInt(TSK - 1);
644 /// Retrieve the first point of instantiation of this member.
645 /// If the point of instantiation is an invalid location, then this member
646 /// has not yet been instantiated.
647 SourceLocation getPointOfInstantiation() const {
648 return PointOfInstantiation;
651 /// Set the first point of instantiation.
652 void setPointOfInstantiation(SourceLocation POI) {
653 PointOfInstantiation = POI;
657 /// Provides information about a dependent function-template
658 /// specialization declaration.
660 /// Since explicit function template specialization and instantiation
661 /// declarations can only appear in namespace scope, and you can only
662 /// specialize a member of a fully-specialized class, the only way to
663 /// get one of these is in a friend declaration like the following:
666 /// template \<class T> void foo(T);
667 /// template \<class T> class A {
668 /// friend void foo<>(T);
671 class DependentFunctionTemplateSpecializationInfo final
672 : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
674 FunctionTemplateDecl *> {
675 /// The number of potential template candidates.
676 unsigned NumTemplates;
678 /// The number of template arguments.
681 /// The locations of the left and right angle brackets.
682 SourceRange AngleLocs;
684 size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
687 size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
691 DependentFunctionTemplateSpecializationInfo(
692 const UnresolvedSetImpl &Templates,
693 const TemplateArgumentListInfo &TemplateArgs);
696 friend TrailingObjects;
698 static DependentFunctionTemplateSpecializationInfo *
699 Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
700 const TemplateArgumentListInfo &TemplateArgs);
702 /// Returns the number of function templates that this might
703 /// be a specialization of.
704 unsigned getNumTemplates() const { return NumTemplates; }
706 /// Returns the i'th template candidate.
707 FunctionTemplateDecl *getTemplate(unsigned I) const {
708 assert(I < getNumTemplates() && "template index out of range");
709 return getTrailingObjects<FunctionTemplateDecl *>()[I];
712 /// Returns the explicit template arguments that were given.
713 const TemplateArgumentLoc *getTemplateArgs() const {
714 return getTrailingObjects<TemplateArgumentLoc>();
717 /// Returns the number of explicit template arguments that were given.
718 unsigned getNumTemplateArgs() const { return NumArgs; }
720 /// Returns the nth template argument.
721 const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
722 assert(I < getNumTemplateArgs() && "template arg index out of range");
723 return getTemplateArgs()[I];
726 SourceLocation getLAngleLoc() const {
727 return AngleLocs.getBegin();
730 SourceLocation getRAngleLoc() const {
731 return AngleLocs.getEnd();
735 /// Declaration of a redeclarable template.
736 class RedeclarableTemplateDecl : public TemplateDecl,
737 public Redeclarable<RedeclarableTemplateDecl>
739 using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>;
741 RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
742 return getNextRedeclaration();
745 RedeclarableTemplateDecl *getPreviousDeclImpl() override {
746 return getPreviousDecl();
749 RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
750 return getMostRecentDecl();
753 void anchor() override;
755 template <typename EntryType> struct SpecEntryTraits {
756 using DeclType = EntryType;
758 static DeclType *getDecl(EntryType *D) {
762 static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
763 return D->getTemplateArgs().asArray();
767 template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
768 typename DeclType = typename SETraits::DeclType>
770 : llvm::iterator_adaptor_base<
771 SpecIterator<EntryType, SETraits, DeclType>,
772 typename llvm::FoldingSetVector<EntryType>::iterator,
773 typename std::iterator_traits<typename llvm::FoldingSetVector<
774 EntryType>::iterator>::iterator_category,
775 DeclType *, ptrdiff_t, DeclType *, DeclType *> {
776 SpecIterator() = default;
777 explicit SpecIterator(
778 typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
779 : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
781 DeclType *operator*() const {
782 return SETraits::getDecl(&*this->I)->getMostRecentDecl();
785 DeclType *operator->() const { return **this; }
788 template <typename EntryType>
789 static SpecIterator<EntryType>
790 makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
791 return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
794 void loadLazySpecializationsImpl() const;
796 template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
797 findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
798 ArrayRef<TemplateArgument> Args, void *&InsertPos);
800 template <class Derived, class EntryType>
801 void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
802 EntryType *Entry, void *InsertPos);
805 CommonBase() : InstantiatedFromMember(nullptr, false) {}
807 /// The template from which this was most
808 /// directly instantiated (or null).
810 /// The boolean value indicates whether this template
811 /// was explicitly specialized.
812 llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
813 InstantiatedFromMember;
815 /// If non-null, points to an array of specializations (including
816 /// partial specializations) known only by their external declaration IDs.
818 /// The first value in the array is the number of specializations/partial
819 /// specializations that follow.
820 uint32_t *LazySpecializations = nullptr;
823 /// Pointer to the common data shared by all declarations of this
825 mutable CommonBase *Common = nullptr;
827 /// Retrieves the "common" pointer shared by all (re-)declarations of
828 /// the same template. Calling this routine may implicitly allocate memory
829 /// for the common pointer.
830 CommonBase *getCommonPtr() const;
832 virtual CommonBase *newCommon(ASTContext &C) const = 0;
834 // Construct a template decl with name, parameters, and templated element.
835 RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
836 SourceLocation L, DeclarationName Name,
837 TemplateParameterList *Params, NamedDecl *Decl)
838 : TemplateDecl(DK, DC, L, Name, Params, Decl), redeclarable_base(C) {}
841 friend class ASTDeclReader;
842 friend class ASTDeclWriter;
843 friend class ASTReader;
844 template <class decl_type> friend class RedeclarableTemplate;
846 /// Retrieves the canonical declaration of this template.
847 RedeclarableTemplateDecl *getCanonicalDecl() override {
848 return getFirstDecl();
850 const RedeclarableTemplateDecl *getCanonicalDecl() const {
851 return getFirstDecl();
854 /// Determines whether this template was a specialization of a
857 /// In the following example, the function template \c X<int>::f and the
858 /// member template \c X<int>::Inner are member specializations.
861 /// template<typename T>
863 /// template<typename U> void f(T, U);
864 /// template<typename U> struct Inner;
867 /// template<> template<typename T>
868 /// void X<int>::f(int, T);
869 /// template<> template<typename T>
870 /// struct X<int>::Inner { /* ... */ };
872 bool isMemberSpecialization() const {
873 return getCommonPtr()->InstantiatedFromMember.getInt();
876 /// Note that this member template is a specialization.
877 void setMemberSpecialization() {
878 assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
879 "Only member templates can be member template specializations");
880 getCommonPtr()->InstantiatedFromMember.setInt(true);
883 /// Retrieve the member template from which this template was
884 /// instantiated, or nullptr if this template was not instantiated from a
887 /// A template is instantiated from a member template when the member
888 /// template itself is part of a class template (or member thereof). For
892 /// template<typename T>
894 /// template<typename U> void f(T, U);
897 /// void test(X<int> x) {
902 /// \c X<int>::f is a FunctionTemplateDecl that describes the function
906 /// template<typename U> void X<int>::f(int, U);
909 /// which was itself created during the instantiation of \c X<int>. Calling
910 /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
911 /// retrieve the FunctionTemplateDecl for the original template \c f within
912 /// the class template \c X<T>, i.e.,
915 /// template<typename T>
916 /// template<typename U>
917 /// void X<T>::f(T, U);
919 RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
920 return getCommonPtr()->InstantiatedFromMember.getPointer();
923 void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
924 assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
925 getCommonPtr()->InstantiatedFromMember.setPointer(TD);
928 using redecl_range = redeclarable_base::redecl_range;
929 using redecl_iterator = redeclarable_base::redecl_iterator;
931 using redeclarable_base::redecls_begin;
932 using redeclarable_base::redecls_end;
933 using redeclarable_base::redecls;
934 using redeclarable_base::getPreviousDecl;
935 using redeclarable_base::getMostRecentDecl;
936 using redeclarable_base::isFirstDecl;
938 // Implement isa/cast/dyncast/etc.
939 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
941 static bool classofKind(Kind K) {
942 return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
946 template <> struct RedeclarableTemplateDecl::
947 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
948 using DeclType = FunctionDecl;
950 static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
951 return I->getFunction();
954 static ArrayRef<TemplateArgument>
955 getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
956 return I->TemplateArguments->asArray();
960 /// Declaration of a template function.
961 class FunctionTemplateDecl : public RedeclarableTemplateDecl {
963 friend class FunctionDecl;
965 /// Data that is common to all of the declarations of a given
966 /// function template.
967 struct Common : CommonBase {
968 /// The function template specializations for this function
969 /// template, including explicit specializations and instantiations.
970 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
972 /// The set of "injected" template arguments used within this
973 /// function template.
975 /// This pointer refers to the template arguments (there are as
976 /// many template arguments as template parameaters) for the function
977 /// template, and is allocated lazily, since most function templates do not
978 /// require the use of this information.
979 TemplateArgument *InjectedArgs = nullptr;
984 FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
985 DeclarationName Name, TemplateParameterList *Params,
987 : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
990 CommonBase *newCommon(ASTContext &C) const override;
992 Common *getCommonPtr() const {
993 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
996 /// Retrieve the set of function template specializations of this
997 /// function template.
998 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
999 getSpecializations() const;
1001 /// Add a specialization of this function template.
1003 /// \param InsertPos Insert position in the FoldingSetVector, must have been
1004 /// retrieved by an earlier call to findSpecialization().
1005 void addSpecialization(FunctionTemplateSpecializationInfo* Info,
1009 friend class ASTDeclReader;
1010 friend class ASTDeclWriter;
1012 /// Load any lazily-loaded specializations from the external source.
1013 void LoadLazySpecializations() const;
1015 /// Get the underlying function declaration of the template.
1016 FunctionDecl *getTemplatedDecl() const {
1017 return static_cast<FunctionDecl *>(TemplatedDecl);
1020 /// Returns whether this template declaration defines the primary
1022 bool isThisDeclarationADefinition() const {
1023 return getTemplatedDecl()->isThisDeclarationADefinition();
1026 /// Return the specialization with the provided arguments if it exists,
1027 /// otherwise return the insertion point.
1028 FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
1031 FunctionTemplateDecl *getCanonicalDecl() override {
1032 return cast<FunctionTemplateDecl>(
1033 RedeclarableTemplateDecl::getCanonicalDecl());
1035 const FunctionTemplateDecl *getCanonicalDecl() const {
1036 return cast<FunctionTemplateDecl>(
1037 RedeclarableTemplateDecl::getCanonicalDecl());
1040 /// Retrieve the previous declaration of this function template, or
1041 /// nullptr if no such declaration exists.
1042 FunctionTemplateDecl *getPreviousDecl() {
1043 return cast_or_null<FunctionTemplateDecl>(
1044 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1046 const FunctionTemplateDecl *getPreviousDecl() const {
1047 return cast_or_null<FunctionTemplateDecl>(
1048 static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1051 FunctionTemplateDecl *getMostRecentDecl() {
1052 return cast<FunctionTemplateDecl>(
1053 static_cast<RedeclarableTemplateDecl *>(this)
1054 ->getMostRecentDecl());
1056 const FunctionTemplateDecl *getMostRecentDecl() const {
1057 return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
1060 FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
1061 return cast_or_null<FunctionTemplateDecl>(
1062 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1065 using spec_iterator = SpecIterator<FunctionTemplateSpecializationInfo>;
1066 using spec_range = llvm::iterator_range<spec_iterator>;
1068 spec_range specializations() const {
1069 return spec_range(spec_begin(), spec_end());
1072 spec_iterator spec_begin() const {
1073 return makeSpecIterator(getSpecializations(), false);
1076 spec_iterator spec_end() const {
1077 return makeSpecIterator(getSpecializations(), true);
1080 /// Retrieve the "injected" template arguments that correspond to the
1081 /// template parameters of this function template.
1083 /// Although the C++ standard has no notion of the "injected" template
1084 /// arguments for a function template, the notion is convenient when
1085 /// we need to perform substitutions inside the definition of a function
1087 ArrayRef<TemplateArgument> getInjectedTemplateArgs();
1089 /// Merge \p Prev with our RedeclarableTemplateDecl::Common.
1090 void mergePrevDecl(FunctionTemplateDecl *Prev);
1092 /// Create a function template node.
1093 static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1095 DeclarationName Name,
1096 TemplateParameterList *Params,
1099 /// Create an empty function template node.
1100 static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1102 // Implement isa/cast/dyncast support
1103 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1104 static bool classofKind(Kind K) { return K == FunctionTemplate; }
1107 //===----------------------------------------------------------------------===//
1108 // Kinds of Template Parameters
1109 //===----------------------------------------------------------------------===//
1111 /// Defines the position of a template parameter within a template
1114 /// Because template parameter can be listed
1115 /// sequentially for out-of-line template members, each template parameter is
1116 /// given a Depth - the nesting of template parameter scopes - and a Position -
1117 /// the occurrence within the parameter list.
1118 /// This class is inheritedly privately by different kinds of template
1119 /// parameters and is not part of the Decl hierarchy. Just a facility.
1120 class TemplateParmPosition {
1122 // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
1127 TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
1130 TemplateParmPosition() = delete;
1132 /// Get the nesting depth of the template parameter.
1133 unsigned getDepth() const { return Depth; }
1134 void setDepth(unsigned D) { Depth = D; }
1136 /// Get the position of the template parameter within its parameter list.
1137 unsigned getPosition() const { return Position; }
1138 void setPosition(unsigned P) { Position = P; }
1140 /// Get the index of the template parameter within its parameter list.
1141 unsigned getIndex() const { return Position; }
1144 /// Declaration of a template type parameter.
1146 /// For example, "T" in
1148 /// template<typename T> class vector;
1150 class TemplateTypeParmDecl : public TypeDecl {
1151 /// Sema creates these on the stack during auto type deduction.
1154 /// Whether this template type parameter was declaration with
1155 /// the 'typename' keyword.
1157 /// If false, it was declared with the 'class' keyword.
1160 /// The default template argument, if any.
1161 using DefArgStorage =
1162 DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>;
1163 DefArgStorage DefaultArgument;
1165 TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
1166 SourceLocation IdLoc, IdentifierInfo *Id,
1168 : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename) {}
1171 static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
1172 SourceLocation KeyLoc,
1173 SourceLocation NameLoc,
1174 unsigned D, unsigned P,
1175 IdentifierInfo *Id, bool Typename,
1176 bool ParameterPack);
1177 static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
1180 /// Whether this template type parameter was declared with
1181 /// the 'typename' keyword.
1183 /// If not, it was declared with the 'class' keyword.
1184 bool wasDeclaredWithTypename() const { return Typename; }
1186 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1188 /// Determine whether this template parameter has a default
1190 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1192 /// Retrieve the default argument, if any.
1193 QualType getDefaultArgument() const {
1194 return DefaultArgument.get()->getType();
1197 /// Retrieves the default argument's source information, if any.
1198 TypeSourceInfo *getDefaultArgumentInfo() const {
1199 return DefaultArgument.get();
1202 /// Retrieves the location of the default argument declaration.
1203 SourceLocation getDefaultArgumentLoc() const;
1205 /// Determines whether the default argument was inherited
1206 /// from a previous declaration of this template.
1207 bool defaultArgumentWasInherited() const {
1208 return DefaultArgument.isInherited();
1211 /// Set the default argument for this template parameter.
1212 void setDefaultArgument(TypeSourceInfo *DefArg) {
1213 DefaultArgument.set(DefArg);
1216 /// Set that this default argument was inherited from another
1218 void setInheritedDefaultArgument(const ASTContext &C,
1219 TemplateTypeParmDecl *Prev) {
1220 DefaultArgument.setInherited(C, Prev);
1223 /// Removes the default argument of this template parameter.
1224 void removeDefaultArgument() {
1225 DefaultArgument.clear();
1228 /// Set whether this template type parameter was declared with
1229 /// the 'typename' or 'class' keyword.
1230 void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1232 /// Retrieve the depth of the template parameter.
1233 unsigned getDepth() const;
1235 /// Retrieve the index of the template parameter.
1236 unsigned getIndex() const;
1238 /// Returns whether this is a parameter pack.
1239 bool isParameterPack() const;
1241 SourceRange getSourceRange() const override LLVM_READONLY;
1243 // Implement isa/cast/dyncast/etc.
1244 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1245 static bool classofKind(Kind K) { return K == TemplateTypeParm; }
1248 /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
1251 /// template<int Size> class array { };
1253 class NonTypeTemplateParmDecl final
1254 : public DeclaratorDecl,
1255 protected TemplateParmPosition,
1256 private llvm::TrailingObjects<NonTypeTemplateParmDecl,
1257 std::pair<QualType, TypeSourceInfo *>> {
1258 friend class ASTDeclReader;
1259 friend TrailingObjects;
1261 /// The default template argument, if any, and whether or not
1262 /// it was inherited.
1263 using DefArgStorage = DefaultArgStorage<NonTypeTemplateParmDecl, Expr *>;
1264 DefArgStorage DefaultArgument;
1266 // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
1267 // down here to save memory.
1269 /// Whether this non-type template parameter is a parameter pack.
1272 /// Whether this non-type template parameter is an "expanded"
1273 /// parameter pack, meaning that its type is a pack expansion and we
1274 /// already know the set of types that expansion expands to.
1275 bool ExpandedParameterPack = false;
1277 /// The number of types in an expanded parameter pack.
1278 unsigned NumExpandedTypes = 0;
1280 size_t numTrailingObjects(
1281 OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
1282 return NumExpandedTypes;
1285 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1286 SourceLocation IdLoc, unsigned D, unsigned P,
1287 IdentifierInfo *Id, QualType T,
1288 bool ParameterPack, TypeSourceInfo *TInfo)
1289 : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
1290 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1292 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1293 SourceLocation IdLoc, unsigned D, unsigned P,
1294 IdentifierInfo *Id, QualType T,
1295 TypeSourceInfo *TInfo,
1296 ArrayRef<QualType> ExpandedTypes,
1297 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1300 static NonTypeTemplateParmDecl *
1301 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1302 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1303 QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
1305 static NonTypeTemplateParmDecl *
1306 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1307 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1308 QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
1309 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1311 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1313 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1315 unsigned NumExpandedTypes);
1317 using TemplateParmPosition::getDepth;
1318 using TemplateParmPosition::setDepth;
1319 using TemplateParmPosition::getPosition;
1320 using TemplateParmPosition::setPosition;
1321 using TemplateParmPosition::getIndex;
1323 SourceRange getSourceRange() const override LLVM_READONLY;
1325 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1327 /// Determine whether this template parameter has a default
1329 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1331 /// Retrieve the default argument, if any.
1332 Expr *getDefaultArgument() const { return DefaultArgument.get(); }
1334 /// Retrieve the location of the default argument, if any.
1335 SourceLocation getDefaultArgumentLoc() const;
1337 /// Determines whether the default argument was inherited
1338 /// from a previous declaration of this template.
1339 bool defaultArgumentWasInherited() const {
1340 return DefaultArgument.isInherited();
1343 /// Set the default argument for this template parameter, and
1344 /// whether that default argument was inherited from another
1346 void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
1347 void setInheritedDefaultArgument(const ASTContext &C,
1348 NonTypeTemplateParmDecl *Parm) {
1349 DefaultArgument.setInherited(C, Parm);
1352 /// Removes the default argument of this template parameter.
1353 void removeDefaultArgument() { DefaultArgument.clear(); }
1355 /// Whether this parameter is a non-type template parameter pack.
1357 /// If the parameter is a parameter pack, the type may be a
1358 /// \c PackExpansionType. In the following example, the \c Dims parameter
1359 /// is a parameter pack (whose type is 'unsigned').
1362 /// template<typename T, unsigned ...Dims> struct multi_array;
1364 bool isParameterPack() const { return ParameterPack; }
1366 /// Whether this parameter pack is a pack expansion.
1368 /// A non-type template parameter pack is a pack expansion if its type
1369 /// contains an unexpanded parameter pack. In this case, we will have
1370 /// built a PackExpansionType wrapping the type.
1371 bool isPackExpansion() const {
1372 return ParameterPack && getType()->getAs<PackExpansionType>();
1375 /// Whether this parameter is a non-type template parameter pack
1376 /// that has a known list of different types at different positions.
1378 /// A parameter pack is an expanded parameter pack when the original
1379 /// parameter pack's type was itself a pack expansion, and that expansion
1380 /// has already been expanded. For example, given:
1383 /// template<typename ...Types>
1385 /// template<Types ...Values>
1386 /// struct Y { /* ... */ };
1390 /// The parameter pack \c Values has a \c PackExpansionType as its type,
1391 /// which expands \c Types. When \c Types is supplied with template arguments
1392 /// by instantiating \c X, the instantiation of \c Values becomes an
1393 /// expanded parameter pack. For example, instantiating
1394 /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1395 /// pack with expansion types \c int and \c unsigned int.
1397 /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1398 /// return the expansion types.
1399 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1401 /// Retrieves the number of expansion types in an expanded parameter
1403 unsigned getNumExpansionTypes() const {
1404 assert(ExpandedParameterPack && "Not an expansion parameter pack");
1405 return NumExpandedTypes;
1408 /// Retrieve a particular expansion type within an expanded parameter
1410 QualType getExpansionType(unsigned I) const {
1411 assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1412 auto TypesAndInfos =
1413 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1414 return TypesAndInfos[I].first;
1417 /// Retrieve a particular expansion type source info within an
1418 /// expanded parameter pack.
1419 TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1420 assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1421 auto TypesAndInfos =
1422 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1423 return TypesAndInfos[I].second;
1426 // Implement isa/cast/dyncast/etc.
1427 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1428 static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1431 /// TemplateTemplateParmDecl - Declares a template template parameter,
1434 /// template <template <typename> class T> class container { };
1436 /// A template template parameter is a TemplateDecl because it defines the
1437 /// name of a template and the template parameters allowable for substitution.
1438 class TemplateTemplateParmDecl final
1439 : public TemplateDecl,
1440 protected TemplateParmPosition,
1441 private llvm::TrailingObjects<TemplateTemplateParmDecl,
1442 TemplateParameterList *> {
1443 /// The default template argument, if any.
1444 using DefArgStorage =
1445 DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>;
1446 DefArgStorage DefaultArgument;
1448 /// Whether this parameter is a parameter pack.
1451 /// Whether this template template parameter is an "expanded"
1452 /// parameter pack, meaning that it is a pack expansion and we
1453 /// already know the set of template parameters that expansion expands to.
1454 bool ExpandedParameterPack = false;
1456 /// The number of parameters in an expanded parameter pack.
1457 unsigned NumExpandedParams = 0;
1459 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1460 unsigned D, unsigned P, bool ParameterPack,
1461 IdentifierInfo *Id, TemplateParameterList *Params)
1462 : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1463 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1465 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1466 unsigned D, unsigned P,
1467 IdentifierInfo *Id, TemplateParameterList *Params,
1468 ArrayRef<TemplateParameterList *> Expansions);
1470 void anchor() override;
1473 friend class ASTDeclReader;
1474 friend class ASTDeclWriter;
1475 friend TrailingObjects;
1477 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1478 SourceLocation L, unsigned D,
1479 unsigned P, bool ParameterPack,
1481 TemplateParameterList *Params);
1482 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1483 SourceLocation L, unsigned D,
1486 TemplateParameterList *Params,
1487 ArrayRef<TemplateParameterList *> Expansions);
1489 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1491 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1493 unsigned NumExpansions);
1495 using TemplateParmPosition::getDepth;
1496 using TemplateParmPosition::setDepth;
1497 using TemplateParmPosition::getPosition;
1498 using TemplateParmPosition::setPosition;
1499 using TemplateParmPosition::getIndex;
1501 /// Whether this template template parameter is a template
1505 /// template<template <class T> ...MetaFunctions> struct Apply;
1507 bool isParameterPack() const { return ParameterPack; }
1509 /// Whether this parameter pack is a pack expansion.
1511 /// A template template parameter pack is a pack expansion if its template
1512 /// parameter list contains an unexpanded parameter pack.
1513 bool isPackExpansion() const {
1514 return ParameterPack &&
1515 getTemplateParameters()->containsUnexpandedParameterPack();
1518 /// Whether this parameter is a template template parameter pack that
1519 /// has a known list of different template parameter lists at different
1522 /// A parameter pack is an expanded parameter pack when the original parameter
1523 /// pack's template parameter list was itself a pack expansion, and that
1524 /// expansion has already been expanded. For exampe, given:
1527 /// template<typename...Types> struct Outer {
1528 /// template<template<Types> class...Templates> struct Inner;
1532 /// The parameter pack \c Templates is a pack expansion, which expands the
1533 /// pack \c Types. When \c Types is supplied with template arguments by
1534 /// instantiating \c Outer, the instantiation of \c Templates is an expanded
1536 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1538 /// Retrieves the number of expansion template parameters in
1539 /// an expanded parameter pack.
1540 unsigned getNumExpansionTemplateParameters() const {
1541 assert(ExpandedParameterPack && "Not an expansion parameter pack");
1542 return NumExpandedParams;
1545 /// Retrieve a particular expansion type within an expanded parameter
1547 TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
1548 assert(I < NumExpandedParams && "Out-of-range expansion type index");
1549 return getTrailingObjects<TemplateParameterList *>()[I];
1552 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1554 /// Determine whether this template parameter has a default
1556 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1558 /// Retrieve the default argument, if any.
1559 const TemplateArgumentLoc &getDefaultArgument() const {
1560 static const TemplateArgumentLoc None;
1561 return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
1564 /// Retrieve the location of the default argument, if any.
1565 SourceLocation getDefaultArgumentLoc() const;
1567 /// Determines whether the default argument was inherited
1568 /// from a previous declaration of this template.
1569 bool defaultArgumentWasInherited() const {
1570 return DefaultArgument.isInherited();
1573 /// Set the default argument for this template parameter, and
1574 /// whether that default argument was inherited from another
1576 void setDefaultArgument(const ASTContext &C,
1577 const TemplateArgumentLoc &DefArg);
1578 void setInheritedDefaultArgument(const ASTContext &C,
1579 TemplateTemplateParmDecl *Prev) {
1580 DefaultArgument.setInherited(C, Prev);
1583 /// Removes the default argument of this template parameter.
1584 void removeDefaultArgument() { DefaultArgument.clear(); }
1586 SourceRange getSourceRange() const override LLVM_READONLY {
1587 SourceLocation End = getLocation();
1588 if (hasDefaultArgument() && !defaultArgumentWasInherited())
1589 End = getDefaultArgument().getSourceRange().getEnd();
1590 return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1593 // Implement isa/cast/dyncast/etc.
1594 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1595 static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1598 /// Represents the builtin template declaration which is used to
1599 /// implement __make_integer_seq and other builtin templates. It serves
1600 /// no real purpose beyond existing as a place to hold template parameters.
1601 class BuiltinTemplateDecl : public TemplateDecl {
1602 BuiltinTemplateKind BTK;
1604 BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
1605 DeclarationName Name, BuiltinTemplateKind BTK);
1607 void anchor() override;
1610 // Implement isa/cast/dyncast support
1611 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1612 static bool classofKind(Kind K) { return K == BuiltinTemplate; }
1614 static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
1615 DeclarationName Name,
1616 BuiltinTemplateKind BTK) {
1617 return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
1620 SourceRange getSourceRange() const override LLVM_READONLY {
1624 BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
1627 /// Represents a class template specialization, which refers to
1628 /// a class template with a given set of template arguments.
1630 /// Class template specializations represent both explicit
1631 /// specialization of class templates, as in the example below, and
1632 /// implicit instantiations of class templates.
1635 /// template<typename T> class array;
1638 /// class array<bool> { }; // class template specialization array<bool>
1640 class ClassTemplateSpecializationDecl
1641 : public CXXRecordDecl, public llvm::FoldingSetNode {
1642 /// Structure that stores information about a class template
1643 /// specialization that was instantiated from a class template partial
1645 struct SpecializedPartialSpecialization {
1646 /// The class template partial specialization from which this
1647 /// class template specialization was instantiated.
1648 ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1650 /// The template argument list deduced for the class template
1651 /// partial specialization itself.
1652 const TemplateArgumentList *TemplateArgs;
1655 /// The template that this specialization specializes
1656 llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1657 SpecializedTemplate;
1659 /// Further info for explicit template specialization/instantiation.
1660 struct ExplicitSpecializationInfo {
1661 /// The type-as-written.
1662 TypeSourceInfo *TypeAsWritten = nullptr;
1664 /// The location of the extern keyword.
1665 SourceLocation ExternLoc;
1667 /// The location of the template keyword.
1668 SourceLocation TemplateKeywordLoc;
1670 ExplicitSpecializationInfo() = default;
1673 /// Further info for explicit template specialization/instantiation.
1674 /// Does not apply to implicit specializations.
1675 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
1677 /// The template arguments used to describe this specialization.
1678 const TemplateArgumentList *TemplateArgs;
1680 /// The point where this template was instantiated (if any)
1681 SourceLocation PointOfInstantiation;
1683 /// The kind of specialization this declaration refers to.
1684 /// Really a value of type TemplateSpecializationKind.
1685 unsigned SpecializationKind : 3;
1688 ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1689 DeclContext *DC, SourceLocation StartLoc,
1690 SourceLocation IdLoc,
1691 ClassTemplateDecl *SpecializedTemplate,
1692 ArrayRef<TemplateArgument> Args,
1693 ClassTemplateSpecializationDecl *PrevDecl);
1695 explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
1698 friend class ASTDeclReader;
1699 friend class ASTDeclWriter;
1701 static ClassTemplateSpecializationDecl *
1702 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1703 SourceLocation StartLoc, SourceLocation IdLoc,
1704 ClassTemplateDecl *SpecializedTemplate,
1705 ArrayRef<TemplateArgument> Args,
1706 ClassTemplateSpecializationDecl *PrevDecl);
1707 static ClassTemplateSpecializationDecl *
1708 CreateDeserialized(ASTContext &C, unsigned ID);
1710 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1711 bool Qualified) const override;
1713 // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
1714 // different "most recent" declaration from this function for the same
1715 // declaration, because we don't override getMostRecentDeclImpl(). But
1716 // it's not clear that we should override that, because the most recent
1717 // declaration as a CXXRecordDecl sometimes is the injected-class-name.
1718 ClassTemplateSpecializationDecl *getMostRecentDecl() {
1719 return cast<ClassTemplateSpecializationDecl>(
1720 getMostRecentNonInjectedDecl());
1723 /// Retrieve the template that this specialization specializes.
1724 ClassTemplateDecl *getSpecializedTemplate() const;
1726 /// Retrieve the template arguments of the class template
1728 const TemplateArgumentList &getTemplateArgs() const {
1729 return *TemplateArgs;
1732 /// Determine the kind of specialization that this
1733 /// declaration represents.
1734 TemplateSpecializationKind getSpecializationKind() const {
1735 return static_cast<TemplateSpecializationKind>(SpecializationKind);
1738 bool isExplicitSpecialization() const {
1739 return getSpecializationKind() == TSK_ExplicitSpecialization;
1742 /// Is this an explicit specialization at class scope (within the class that
1743 /// owns the primary template)? For example:
1746 /// template<typename T> struct Outer {
1747 /// template<typename U> struct Inner;
1748 /// template<> struct Inner; // class-scope explicit specialization
1751 bool isClassScopeExplicitSpecialization() const {
1752 return isExplicitSpecialization() &&
1753 isa<CXXRecordDecl>(getLexicalDeclContext());
1756 /// True if this declaration is an explicit specialization,
1757 /// explicit instantiation declaration, or explicit instantiation
1759 bool isExplicitInstantiationOrSpecialization() const {
1760 return isTemplateExplicitInstantiationOrSpecialization(
1761 getTemplateSpecializationKind());
1764 void setSpecializationKind(TemplateSpecializationKind TSK) {
1765 SpecializationKind = TSK;
1768 /// Get the point of instantiation (if any), or null if none.
1769 SourceLocation getPointOfInstantiation() const {
1770 return PointOfInstantiation;
1773 void setPointOfInstantiation(SourceLocation Loc) {
1774 assert(Loc.isValid() && "point of instantiation must be valid!");
1775 PointOfInstantiation = Loc;
1778 /// If this class template specialization is an instantiation of
1779 /// a template (rather than an explicit specialization), return the
1780 /// class template or class template partial specialization from which it
1781 /// was instantiated.
1782 llvm::PointerUnion<ClassTemplateDecl *,
1783 ClassTemplatePartialSpecializationDecl *>
1784 getInstantiatedFrom() const {
1785 if (!isTemplateInstantiation(getSpecializationKind()))
1786 return llvm::PointerUnion<ClassTemplateDecl *,
1787 ClassTemplatePartialSpecializationDecl *>();
1789 return getSpecializedTemplateOrPartial();
1792 /// Retrieve the class template or class template partial
1793 /// specialization which was specialized by this.
1794 llvm::PointerUnion<ClassTemplateDecl *,
1795 ClassTemplatePartialSpecializationDecl *>
1796 getSpecializedTemplateOrPartial() const {
1797 if (const auto *PartialSpec =
1798 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
1799 return PartialSpec->PartialSpecialization;
1801 return SpecializedTemplate.get<ClassTemplateDecl*>();
1804 /// Retrieve the set of template arguments that should be used
1805 /// to instantiate members of the class template or class template partial
1806 /// specialization from which this class template specialization was
1809 /// \returns For a class template specialization instantiated from the primary
1810 /// template, this function will return the same template arguments as
1811 /// getTemplateArgs(). For a class template specialization instantiated from
1812 /// a class template partial specialization, this function will return the
1813 /// deduced template arguments for the class template partial specialization
1815 const TemplateArgumentList &getTemplateInstantiationArgs() const {
1816 if (const auto *PartialSpec =
1817 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
1818 return *PartialSpec->TemplateArgs;
1820 return getTemplateArgs();
1823 /// Note that this class template specialization is actually an
1824 /// instantiation of the given class template partial specialization whose
1825 /// template arguments have been deduced.
1826 void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1827 const TemplateArgumentList *TemplateArgs) {
1828 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1829 "Already set to a class template partial specialization!");
1830 auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
1831 PS->PartialSpecialization = PartialSpec;
1832 PS->TemplateArgs = TemplateArgs;
1833 SpecializedTemplate = PS;
1836 /// Note that this class template specialization is an instantiation
1837 /// of the given class template.
1838 void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1839 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1840 "Previously set to a class template partial specialization!");
1841 SpecializedTemplate = TemplDecl;
1844 /// Sets the type of this specialization as it was written by
1845 /// the user. This will be a class template specialization type.
1846 void setTypeAsWritten(TypeSourceInfo *T) {
1848 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1849 ExplicitInfo->TypeAsWritten = T;
1852 /// Gets the type of this specialization as it was written by
1853 /// the user, if it was so written.
1854 TypeSourceInfo *getTypeAsWritten() const {
1855 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
1858 /// Gets the location of the extern keyword, if present.
1859 SourceLocation getExternLoc() const {
1860 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1863 /// Sets the location of the extern keyword.
1864 void setExternLoc(SourceLocation Loc) {
1866 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1867 ExplicitInfo->ExternLoc = Loc;
1870 /// Sets the location of the template keyword.
1871 void setTemplateKeywordLoc(SourceLocation Loc) {
1873 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1874 ExplicitInfo->TemplateKeywordLoc = Loc;
1877 /// Gets the location of the template keyword, if present.
1878 SourceLocation getTemplateKeywordLoc() const {
1879 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1882 SourceRange getSourceRange() const override LLVM_READONLY;
1884 void Profile(llvm::FoldingSetNodeID &ID) const {
1885 Profile(ID, TemplateArgs->asArray(), getASTContext());
1889 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
1890 ASTContext &Context) {
1891 ID.AddInteger(TemplateArgs.size());
1892 for (const TemplateArgument &TemplateArg : TemplateArgs)
1893 TemplateArg.Profile(ID, Context);
1896 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1898 static bool classofKind(Kind K) {
1899 return K >= firstClassTemplateSpecialization &&
1900 K <= lastClassTemplateSpecialization;
1904 class ClassTemplatePartialSpecializationDecl
1905 : public ClassTemplateSpecializationDecl {
1906 /// The list of template parameters
1907 TemplateParameterList* TemplateParams = nullptr;
1909 /// The source info for the template arguments as written.
1910 /// FIXME: redundant with TypeAsWritten?
1911 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
1913 /// The class template partial specialization from which this
1914 /// class template partial specialization was instantiated.
1916 /// The boolean value will be true to indicate that this class template
1917 /// partial specialization was specialized at this level.
1918 llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1919 InstantiatedFromMember;
1921 ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1923 SourceLocation StartLoc,
1924 SourceLocation IdLoc,
1925 TemplateParameterList *Params,
1926 ClassTemplateDecl *SpecializedTemplate,
1927 ArrayRef<TemplateArgument> Args,
1928 const ASTTemplateArgumentListInfo *ArgsAsWritten,
1929 ClassTemplatePartialSpecializationDecl *PrevDecl);
1931 ClassTemplatePartialSpecializationDecl(ASTContext &C)
1932 : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
1933 InstantiatedFromMember(nullptr, false) {}
1935 void anchor() override;
1938 friend class ASTDeclReader;
1939 friend class ASTDeclWriter;
1941 static ClassTemplatePartialSpecializationDecl *
1942 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1943 SourceLocation StartLoc, SourceLocation IdLoc,
1944 TemplateParameterList *Params,
1945 ClassTemplateDecl *SpecializedTemplate,
1946 ArrayRef<TemplateArgument> Args,
1947 const TemplateArgumentListInfo &ArgInfos,
1948 QualType CanonInjectedType,
1949 ClassTemplatePartialSpecializationDecl *PrevDecl);
1951 static ClassTemplatePartialSpecializationDecl *
1952 CreateDeserialized(ASTContext &C, unsigned ID);
1954 ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
1955 return cast<ClassTemplatePartialSpecializationDecl>(
1956 static_cast<ClassTemplateSpecializationDecl *>(
1957 this)->getMostRecentDecl());
1960 /// Get the list of template parameters
1961 TemplateParameterList *getTemplateParameters() const {
1962 return TemplateParams;
1965 /// \brief All associated constraints of this partial specialization,
1966 /// including the requires clause and any constraints derived from
1967 /// constrained-parameters.
1969 /// The constraints in the resulting list are to be treated as if in a
1970 /// conjunction ("and").
1971 void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
1972 TemplateParams->getAssociatedConstraints(AC);
1975 bool hasAssociatedConstraints() const {
1976 return TemplateParams->hasAssociatedConstraints();
1979 /// Get the template arguments as written.
1980 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
1981 return ArgsAsWritten;
1984 /// Retrieve the member class template partial specialization from
1985 /// which this particular class template partial specialization was
1989 /// template<typename T>
1991 /// template<typename U> struct Inner;
1992 /// template<typename U> struct Inner<U*> { }; // #1
1995 /// Outer<float>::Inner<int*> ii;
1998 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
1999 /// end up instantiating the partial specialization
2000 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
2001 /// template partial specialization \c Outer<T>::Inner<U*>. Given
2002 /// \c Outer<float>::Inner<U*>, this function would return
2003 /// \c Outer<T>::Inner<U*>.
2004 ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2006 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2007 return First->InstantiatedFromMember.getPointer();
2009 ClassTemplatePartialSpecializationDecl *
2010 getInstantiatedFromMemberTemplate() const {
2011 return getInstantiatedFromMember();
2014 void setInstantiatedFromMember(
2015 ClassTemplatePartialSpecializationDecl *PartialSpec) {
2016 auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2017 First->InstantiatedFromMember.setPointer(PartialSpec);
2020 /// Determines whether this class template partial specialization
2021 /// template was a specialization of a member partial specialization.
2023 /// In the following example, the member template partial specialization
2024 /// \c X<int>::Inner<T*> is a member specialization.
2027 /// template<typename T>
2029 /// template<typename U> struct Inner;
2030 /// template<typename U> struct Inner<U*>;
2033 /// template<> template<typename T>
2034 /// struct X<int>::Inner<T*> { /* ... */ };
2036 bool isMemberSpecialization() {
2038 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2039 return First->InstantiatedFromMember.getInt();
2042 /// Note that this member template is a specialization.
2043 void setMemberSpecialization() {
2044 auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2045 assert(First->InstantiatedFromMember.getPointer() &&
2046 "Only member templates can be member template specializations");
2047 return First->InstantiatedFromMember.setInt(true);
2050 /// Retrieves the injected specialization type for this partial
2051 /// specialization. This is not the same as the type-decl-type for
2052 /// this partial specialization, which is an InjectedClassNameType.
2053 QualType getInjectedSpecializationType() const {
2054 assert(getTypeForDecl() && "partial specialization has no type set!");
2055 return cast<InjectedClassNameType>(getTypeForDecl())
2056 ->getInjectedSpecializationType();
2059 // FIXME: Add Profile support!
2061 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2063 static bool classofKind(Kind K) {
2064 return K == ClassTemplatePartialSpecialization;
2068 /// Declaration of a class template.
2069 class ClassTemplateDecl : public RedeclarableTemplateDecl {
2071 /// Data that is common to all of the declarations of a given
2073 struct Common : CommonBase {
2074 /// The class template specializations for this class
2075 /// template, including explicit specializations and instantiations.
2076 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
2078 /// The class template partial specializations for this class
2080 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
2081 PartialSpecializations;
2083 /// The injected-class-name type for this class template.
2084 QualType InjectedClassNameType;
2089 /// Retrieve the set of specializations of this class template.
2090 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
2091 getSpecializations() const;
2093 /// Retrieve the set of partial specializations of this class
2095 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
2096 getPartialSpecializations();
2098 ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2099 DeclarationName Name, TemplateParameterList *Params,
2101 : RedeclarableTemplateDecl(ClassTemplate, C, DC, L, Name, Params, Decl) {}
2103 CommonBase *newCommon(ASTContext &C) const override;
2105 Common *getCommonPtr() const {
2106 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2110 friend class ASTDeclReader;
2111 friend class ASTDeclWriter;
2113 /// Load any lazily-loaded specializations from the external source.
2114 void LoadLazySpecializations() const;
2116 /// Get the underlying class declarations of the template.
2117 CXXRecordDecl *getTemplatedDecl() const {
2118 return static_cast<CXXRecordDecl *>(TemplatedDecl);
2121 /// Returns whether this template declaration defines the primary
2123 bool isThisDeclarationADefinition() const {
2124 return getTemplatedDecl()->isThisDeclarationADefinition();
2127 /// \brief Create a class template node.
2128 static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2130 DeclarationName Name,
2131 TemplateParameterList *Params,
2134 /// Create an empty class template node.
2135 static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2137 /// Return the specialization with the provided arguments if it exists,
2138 /// otherwise return the insertion point.
2139 ClassTemplateSpecializationDecl *
2140 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2142 /// Insert the specified specialization knowing that it is not already
2143 /// in. InsertPos must be obtained from findSpecialization.
2144 void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
2146 ClassTemplateDecl *getCanonicalDecl() override {
2147 return cast<ClassTemplateDecl>(
2148 RedeclarableTemplateDecl::getCanonicalDecl());
2150 const ClassTemplateDecl *getCanonicalDecl() const {
2151 return cast<ClassTemplateDecl>(
2152 RedeclarableTemplateDecl::getCanonicalDecl());
2155 /// Retrieve the previous declaration of this class template, or
2156 /// nullptr if no such declaration exists.
2157 ClassTemplateDecl *getPreviousDecl() {
2158 return cast_or_null<ClassTemplateDecl>(
2159 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2161 const ClassTemplateDecl *getPreviousDecl() const {
2162 return cast_or_null<ClassTemplateDecl>(
2163 static_cast<const RedeclarableTemplateDecl *>(
2164 this)->getPreviousDecl());
2167 ClassTemplateDecl *getMostRecentDecl() {
2168 return cast<ClassTemplateDecl>(
2169 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2171 const ClassTemplateDecl *getMostRecentDecl() const {
2172 return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
2175 ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
2176 return cast_or_null<ClassTemplateDecl>(
2177 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2180 /// Return the partial specialization with the provided arguments if it
2181 /// exists, otherwise return the insertion point.
2182 ClassTemplatePartialSpecializationDecl *
2183 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2185 /// Insert the specified partial specialization knowing that it is not
2186 /// already in. InsertPos must be obtained from findPartialSpecialization.
2187 void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
2190 /// Retrieve the partial specializations as an ordered list.
2191 void getPartialSpecializations(
2192 SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
2194 /// Find a class template partial specialization with the given
2197 /// \param T a dependent type that names a specialization of this class
2200 /// \returns the class template partial specialization that exactly matches
2201 /// the type \p T, or nullptr if no such partial specialization exists.
2202 ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
2204 /// Find a class template partial specialization which was instantiated
2205 /// from the given member partial specialization.
2207 /// \param D a member class template partial specialization.
2209 /// \returns the class template partial specialization which was instantiated
2210 /// from the given member partial specialization, or nullptr if no such
2211 /// partial specialization exists.
2212 ClassTemplatePartialSpecializationDecl *
2213 findPartialSpecInstantiatedFromMember(
2214 ClassTemplatePartialSpecializationDecl *D);
2216 /// Retrieve the template specialization type of the
2217 /// injected-class-name for this class template.
2219 /// The injected-class-name for a class template \c X is \c
2220 /// X<template-args>, where \c template-args is formed from the
2221 /// template arguments that correspond to the template parameters of
2222 /// \c X. For example:
2225 /// template<typename T, int N>
2227 /// typedef array this_type; // "array" is equivalent to "array<T, N>"
2230 QualType getInjectedClassNameSpecialization();
2232 using spec_iterator = SpecIterator<ClassTemplateSpecializationDecl>;
2233 using spec_range = llvm::iterator_range<spec_iterator>;
2235 spec_range specializations() const {
2236 return spec_range(spec_begin(), spec_end());
2239 spec_iterator spec_begin() const {
2240 return makeSpecIterator(getSpecializations(), false);
2243 spec_iterator spec_end() const {
2244 return makeSpecIterator(getSpecializations(), true);
2247 // Implement isa/cast/dyncast support
2248 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2249 static bool classofKind(Kind K) { return K == ClassTemplate; }
2252 /// Declaration of a friend template.
2256 /// template \<typename T> class A {
2257 /// friend class MyVector<T>; // not a friend template
2258 /// template \<typename U> friend class B; // not a friend template
2259 /// template \<typename U> friend class Foo<T>::Nested; // friend template
2263 /// \note This class is not currently in use. All of the above
2264 /// will yield a FriendDecl, not a FriendTemplateDecl.
2265 class FriendTemplateDecl : public Decl {
2266 virtual void anchor();
2269 using FriendUnion = llvm::PointerUnion<NamedDecl *,TypeSourceInfo *>;
2272 // The number of template parameters; always non-zero.
2273 unsigned NumParams = 0;
2275 // The parameter list.
2276 TemplateParameterList **Params = nullptr;
2278 // The declaration that's a friend of this class.
2281 // Location of the 'friend' specifier.
2282 SourceLocation FriendLoc;
2284 FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
2285 MutableArrayRef<TemplateParameterList *> Params,
2286 FriendUnion Friend, SourceLocation FriendLoc)
2287 : Decl(Decl::FriendTemplate, DC, Loc), NumParams(Params.size()),
2288 Params(Params.data()), Friend(Friend), FriendLoc(FriendLoc) {}
2290 FriendTemplateDecl(EmptyShell Empty) : Decl(Decl::FriendTemplate, Empty) {}
2293 friend class ASTDeclReader;
2295 static FriendTemplateDecl *
2296 Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
2297 MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
2298 SourceLocation FriendLoc);
2300 static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2302 /// If this friend declaration names a templated type (or
2303 /// a dependent member type of a templated type), return that
2304 /// type; otherwise return null.
2305 TypeSourceInfo *getFriendType() const {
2306 return Friend.dyn_cast<TypeSourceInfo*>();
2309 /// If this friend declaration names a templated function (or
2310 /// a member function of a templated type), return that type;
2311 /// otherwise return null.
2312 NamedDecl *getFriendDecl() const {
2313 return Friend.dyn_cast<NamedDecl*>();
2316 /// Retrieves the location of the 'friend' keyword.
2317 SourceLocation getFriendLoc() const {
2321 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2322 assert(i <= NumParams);
2326 unsigned getNumTemplateParameters() const {
2330 // Implement isa/cast/dyncast/etc.
2331 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2332 static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
2335 /// Declaration of an alias template.
2339 /// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
2341 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
2343 using Common = CommonBase;
2345 TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2346 DeclarationName Name, TemplateParameterList *Params,
2348 : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
2351 CommonBase *newCommon(ASTContext &C) const override;
2353 Common *getCommonPtr() {
2354 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2358 friend class ASTDeclReader;
2359 friend class ASTDeclWriter;
2361 /// Get the underlying function declaration of the template.
2362 TypeAliasDecl *getTemplatedDecl() const {
2363 return static_cast<TypeAliasDecl *>(TemplatedDecl);
2367 TypeAliasTemplateDecl *getCanonicalDecl() override {
2368 return cast<TypeAliasTemplateDecl>(
2369 RedeclarableTemplateDecl::getCanonicalDecl());
2371 const TypeAliasTemplateDecl *getCanonicalDecl() const {
2372 return cast<TypeAliasTemplateDecl>(
2373 RedeclarableTemplateDecl::getCanonicalDecl());
2376 /// Retrieve the previous declaration of this function template, or
2377 /// nullptr if no such declaration exists.
2378 TypeAliasTemplateDecl *getPreviousDecl() {
2379 return cast_or_null<TypeAliasTemplateDecl>(
2380 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2382 const TypeAliasTemplateDecl *getPreviousDecl() const {
2383 return cast_or_null<TypeAliasTemplateDecl>(
2384 static_cast<const RedeclarableTemplateDecl *>(
2385 this)->getPreviousDecl());
2388 TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
2389 return cast_or_null<TypeAliasTemplateDecl>(
2390 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2393 /// Create a function template node.
2394 static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2396 DeclarationName Name,
2397 TemplateParameterList *Params,
2400 /// Create an empty alias template node.
2401 static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2403 // Implement isa/cast/dyncast support
2404 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2405 static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2408 /// Declaration of a function specialization at template class scope.
2412 /// template <class T>
2414 /// template <class U> void foo(U a) { }
2415 /// template<> void foo(int a) { }
2419 /// "template<> foo(int a)" will be saved in Specialization as a normal
2420 /// CXXMethodDecl. Then during an instantiation of class A, it will be
2421 /// transformed into an actual function specialization.
2423 /// FIXME: This is redundant; we could store the same information directly on
2424 /// the CXXMethodDecl as a DependentFunctionTemplateSpecializationInfo.
2425 class ClassScopeFunctionSpecializationDecl : public Decl {
2426 CXXMethodDecl *Specialization;
2427 const ASTTemplateArgumentListInfo *TemplateArgs;
2429 ClassScopeFunctionSpecializationDecl(
2430 DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD,
2431 const ASTTemplateArgumentListInfo *TemplArgs)
2432 : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2433 Specialization(FD), TemplateArgs(TemplArgs) {}
2435 ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2436 : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2438 virtual void anchor();
2441 friend class ASTDeclReader;
2442 friend class ASTDeclWriter;
2444 CXXMethodDecl *getSpecialization() const { return Specialization; }
2445 bool hasExplicitTemplateArgs() const { return TemplateArgs; }
2446 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2447 return TemplateArgs;
2450 static ClassScopeFunctionSpecializationDecl *
2451 Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD,
2452 bool HasExplicitTemplateArgs,
2453 const TemplateArgumentListInfo &TemplateArgs) {
2454 return new (C, DC) ClassScopeFunctionSpecializationDecl(
2456 HasExplicitTemplateArgs
2457 ? ASTTemplateArgumentListInfo::Create(C, TemplateArgs)
2461 static ClassScopeFunctionSpecializationDecl *
2462 CreateDeserialized(ASTContext &Context, unsigned ID);
2464 // Implement isa/cast/dyncast/etc.
2465 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2467 static bool classofKind(Kind K) {
2468 return K == Decl::ClassScopeFunctionSpecialization;
2472 /// Represents a variable template specialization, which refers to
2473 /// a variable template with a given set of template arguments.
2475 /// Variable template specializations represent both explicit
2476 /// specializations of variable templates, as in the example below, and
2477 /// implicit instantiations of variable templates.
2480 /// template<typename T> constexpr T pi = T(3.1415926535897932385);
2483 /// constexpr float pi<float>; // variable template specialization pi<float>
2485 class VarTemplateSpecializationDecl : public VarDecl,
2486 public llvm::FoldingSetNode {
2488 /// Structure that stores information about a variable template
2489 /// specialization that was instantiated from a variable template partial
2491 struct SpecializedPartialSpecialization {
2492 /// The variable template partial specialization from which this
2493 /// variable template specialization was instantiated.
2494 VarTemplatePartialSpecializationDecl *PartialSpecialization;
2496 /// The template argument list deduced for the variable template
2497 /// partial specialization itself.
2498 const TemplateArgumentList *TemplateArgs;
2501 /// The template that this specialization specializes.
2502 llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
2503 SpecializedTemplate;
2505 /// Further info for explicit template specialization/instantiation.
2506 struct ExplicitSpecializationInfo {
2507 /// The type-as-written.
2508 TypeSourceInfo *TypeAsWritten = nullptr;
2510 /// The location of the extern keyword.
2511 SourceLocation ExternLoc;
2513 /// The location of the template keyword.
2514 SourceLocation TemplateKeywordLoc;
2516 ExplicitSpecializationInfo() = default;
2519 /// Further info for explicit template specialization/instantiation.
2520 /// Does not apply to implicit specializations.
2521 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
2523 /// The template arguments used to describe this specialization.
2524 const TemplateArgumentList *TemplateArgs;
2525 TemplateArgumentListInfo TemplateArgsInfo;
2527 /// The point where this template was instantiated (if any).
2528 SourceLocation PointOfInstantiation;
2530 /// The kind of specialization this declaration refers to.
2531 /// Really a value of type TemplateSpecializationKind.
2532 unsigned SpecializationKind : 3;
2534 /// Whether this declaration is a complete definition of the
2535 /// variable template specialization. We can't otherwise tell apart
2536 /// an instantiated declaration from an instantiated definition with
2538 unsigned IsCompleteDefinition : 1;
2541 VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
2542 SourceLocation StartLoc, SourceLocation IdLoc,
2543 VarTemplateDecl *SpecializedTemplate,
2544 QualType T, TypeSourceInfo *TInfo,
2546 ArrayRef<TemplateArgument> Args);
2548 explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
2551 friend class ASTDeclReader;
2552 friend class ASTDeclWriter;
2553 friend class VarDecl;
2555 static VarTemplateSpecializationDecl *
2556 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2557 SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
2558 TypeSourceInfo *TInfo, StorageClass S,
2559 ArrayRef<TemplateArgument> Args);
2560 static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
2563 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2564 bool Qualified) const override;
2566 VarTemplateSpecializationDecl *getMostRecentDecl() {
2567 VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
2568 return cast<VarTemplateSpecializationDecl>(Recent);
2571 /// Retrieve the template that this specialization specializes.
2572 VarTemplateDecl *getSpecializedTemplate() const;
2574 /// Retrieve the template arguments of the variable template
2576 const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
2578 // TODO: Always set this when creating the new specialization?
2579 void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
2581 const TemplateArgumentListInfo &getTemplateArgsInfo() const {
2582 return TemplateArgsInfo;
2585 /// Determine the kind of specialization that this
2586 /// declaration represents.
2587 TemplateSpecializationKind getSpecializationKind() const {
2588 return static_cast<TemplateSpecializationKind>(SpecializationKind);
2591 bool isExplicitSpecialization() const {
2592 return getSpecializationKind() == TSK_ExplicitSpecialization;
2595 bool isClassScopeExplicitSpecialization() const {
2596 return isExplicitSpecialization() &&
2597 isa<CXXRecordDecl>(getLexicalDeclContext());
2600 /// True if this declaration is an explicit specialization,
2601 /// explicit instantiation declaration, or explicit instantiation
2603 bool isExplicitInstantiationOrSpecialization() const {
2604 return isTemplateExplicitInstantiationOrSpecialization(
2605 getTemplateSpecializationKind());
2608 void setSpecializationKind(TemplateSpecializationKind TSK) {
2609 SpecializationKind = TSK;
2612 /// Get the point of instantiation (if any), or null if none.
2613 SourceLocation getPointOfInstantiation() const {
2614 return PointOfInstantiation;
2617 void setPointOfInstantiation(SourceLocation Loc) {
2618 assert(Loc.isValid() && "point of instantiation must be valid!");
2619 PointOfInstantiation = Loc;
2622 void setCompleteDefinition() { IsCompleteDefinition = true; }
2624 /// If this variable template specialization is an instantiation of
2625 /// a template (rather than an explicit specialization), return the
2626 /// variable template or variable template partial specialization from which
2627 /// it was instantiated.
2628 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2629 getInstantiatedFrom() const {
2630 if (!isTemplateInstantiation(getSpecializationKind()))
2631 return llvm::PointerUnion<VarTemplateDecl *,
2632 VarTemplatePartialSpecializationDecl *>();
2634 return getSpecializedTemplateOrPartial();
2637 /// Retrieve the variable template or variable template partial
2638 /// specialization which was specialized by this.
2639 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2640 getSpecializedTemplateOrPartial() const {
2641 if (const auto *PartialSpec =
2642 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2643 return PartialSpec->PartialSpecialization;
2645 return SpecializedTemplate.get<VarTemplateDecl *>();
2648 /// Retrieve the set of template arguments that should be used
2649 /// to instantiate the initializer of the variable template or variable
2650 /// template partial specialization from which this variable template
2651 /// specialization was instantiated.
2653 /// \returns For a variable template specialization instantiated from the
2654 /// primary template, this function will return the same template arguments
2655 /// as getTemplateArgs(). For a variable template specialization instantiated
2656 /// from a variable template partial specialization, this function will the
2657 /// return deduced template arguments for the variable template partial
2658 /// specialization itself.
2659 const TemplateArgumentList &getTemplateInstantiationArgs() const {
2660 if (const auto *PartialSpec =
2661 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2662 return *PartialSpec->TemplateArgs;
2664 return getTemplateArgs();
2667 /// Note that this variable template specialization is actually an
2668 /// instantiation of the given variable template partial specialization whose
2669 /// template arguments have been deduced.
2670 void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
2671 const TemplateArgumentList *TemplateArgs) {
2672 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
2673 "Already set to a variable template partial specialization!");
2674 auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
2675 PS->PartialSpecialization = PartialSpec;
2676 PS->TemplateArgs = TemplateArgs;
2677 SpecializedTemplate = PS;
2680 /// Note that this variable template specialization is an instantiation
2681 /// of the given variable template.
2682 void setInstantiationOf(VarTemplateDecl *TemplDecl) {
2683 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
2684 "Previously set to a variable template partial specialization!");
2685 SpecializedTemplate = TemplDecl;
2688 /// Sets the type of this specialization as it was written by
2690 void setTypeAsWritten(TypeSourceInfo *T) {
2692 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2693 ExplicitInfo->TypeAsWritten = T;
2696 /// Gets the type of this specialization as it was written by
2697 /// the user, if it was so written.
2698 TypeSourceInfo *getTypeAsWritten() const {
2699 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
2702 /// Gets the location of the extern keyword, if present.
2703 SourceLocation getExternLoc() const {
2704 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
2707 /// Sets the location of the extern keyword.
2708 void setExternLoc(SourceLocation Loc) {
2710 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2711 ExplicitInfo->ExternLoc = Loc;
2714 /// Sets the location of the template keyword.
2715 void setTemplateKeywordLoc(SourceLocation Loc) {
2717 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2718 ExplicitInfo->TemplateKeywordLoc = Loc;
2721 /// Gets the location of the template keyword, if present.
2722 SourceLocation getTemplateKeywordLoc() const {
2723 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
2726 void Profile(llvm::FoldingSetNodeID &ID) const {
2727 Profile(ID, TemplateArgs->asArray(), getASTContext());
2730 static void Profile(llvm::FoldingSetNodeID &ID,
2731 ArrayRef<TemplateArgument> TemplateArgs,
2732 ASTContext &Context) {
2733 ID.AddInteger(TemplateArgs.size());
2734 for (const TemplateArgument &TemplateArg : TemplateArgs)
2735 TemplateArg.Profile(ID, Context);
2738 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2740 static bool classofKind(Kind K) {
2741 return K >= firstVarTemplateSpecialization &&
2742 K <= lastVarTemplateSpecialization;
2746 class VarTemplatePartialSpecializationDecl
2747 : public VarTemplateSpecializationDecl {
2748 /// The list of template parameters
2749 TemplateParameterList *TemplateParams = nullptr;
2751 /// The source info for the template arguments as written.
2752 /// FIXME: redundant with TypeAsWritten?
2753 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2755 /// The variable template partial specialization from which this
2756 /// variable template partial specialization was instantiated.
2758 /// The boolean value will be true to indicate that this variable template
2759 /// partial specialization was specialized at this level.
2760 llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
2761 InstantiatedFromMember;
2763 VarTemplatePartialSpecializationDecl(
2764 ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2765 SourceLocation IdLoc, TemplateParameterList *Params,
2766 VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
2767 StorageClass S, ArrayRef<TemplateArgument> Args,
2768 const ASTTemplateArgumentListInfo *ArgInfos);
2770 VarTemplatePartialSpecializationDecl(ASTContext &Context)
2771 : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization,
2773 InstantiatedFromMember(nullptr, false) {}
2775 void anchor() override;
2778 friend class ASTDeclReader;
2779 friend class ASTDeclWriter;
2781 static VarTemplatePartialSpecializationDecl *
2782 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2783 SourceLocation IdLoc, TemplateParameterList *Params,
2784 VarTemplateDecl *SpecializedTemplate, QualType T,
2785 TypeSourceInfo *TInfo, StorageClass S, ArrayRef<TemplateArgument> Args,
2786 const TemplateArgumentListInfo &ArgInfos);
2788 static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
2791 VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
2792 return cast<VarTemplatePartialSpecializationDecl>(
2793 static_cast<VarTemplateSpecializationDecl *>(
2794 this)->getMostRecentDecl());
2797 /// Get the list of template parameters
2798 TemplateParameterList *getTemplateParameters() const {
2799 return TemplateParams;
2802 /// Get the template arguments as written.
2803 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2804 return ArgsAsWritten;
2807 /// \brief All associated constraints of this partial specialization,
2808 /// including the requires clause and any constraints derived from
2809 /// constrained-parameters.
2811 /// The constraints in the resulting list are to be treated as if in a
2812 /// conjunction ("and").
2813 void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
2814 TemplateParams->getAssociatedConstraints(AC);
2817 bool hasAssociatedConstraints() const {
2818 return TemplateParams->hasAssociatedConstraints();
2821 /// \brief Retrieve the member variable template partial specialization from
2822 /// which this particular variable template partial specialization was
2826 /// template<typename T>
2828 /// template<typename U> U Inner;
2829 /// template<typename U> U* Inner<U*> = (U*)(0); // #1
2832 /// template int* Outer<float>::Inner<int*>;
2835 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
2836 /// end up instantiating the partial specialization
2837 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
2838 /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
2839 /// \c Outer<float>::Inner<U*>, this function would return
2840 /// \c Outer<T>::Inner<U*>.
2841 VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2843 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2844 return First->InstantiatedFromMember.getPointer();
2848 setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
2849 auto *First = cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2850 First->InstantiatedFromMember.setPointer(PartialSpec);
2853 /// Determines whether this variable template partial specialization
2854 /// was a specialization of a member partial specialization.
2856 /// In the following example, the member template partial specialization
2857 /// \c X<int>::Inner<T*> is a member specialization.
2860 /// template<typename T>
2862 /// template<typename U> U Inner;
2863 /// template<typename U> U* Inner<U*> = (U*)(0);
2866 /// template<> template<typename T>
2867 /// U* X<int>::Inner<T*> = (T*)(0) + 1;
2869 bool isMemberSpecialization() {
2871 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2872 return First->InstantiatedFromMember.getInt();
2875 /// Note that this member template is a specialization.
2876 void setMemberSpecialization() {
2877 auto *First = cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2878 assert(First->InstantiatedFromMember.getPointer() &&
2879 "Only member templates can be member template specializations");
2880 return First->InstantiatedFromMember.setInt(true);
2883 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2885 static bool classofKind(Kind K) {
2886 return K == VarTemplatePartialSpecialization;
2890 /// Declaration of a variable template.
2891 class VarTemplateDecl : public RedeclarableTemplateDecl {
2893 /// Data that is common to all of the declarations of a given
2894 /// variable template.
2895 struct Common : CommonBase {
2896 /// The variable template specializations for this variable
2897 /// template, including explicit specializations and instantiations.
2898 llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
2900 /// The variable template partial specializations for this variable
2902 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
2903 PartialSpecializations;
2908 /// Retrieve the set of specializations of this variable template.
2909 llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
2910 getSpecializations() const;
2912 /// Retrieve the set of partial specializations of this class
2914 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
2915 getPartialSpecializations();
2917 VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2918 DeclarationName Name, TemplateParameterList *Params,
2920 : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
2922 CommonBase *newCommon(ASTContext &C) const override;
2924 Common *getCommonPtr() const {
2925 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2929 friend class ASTDeclReader;
2930 friend class ASTDeclWriter;
2932 /// Load any lazily-loaded specializations from the external source.
2933 void LoadLazySpecializations() const;
2935 /// Get the underlying variable declarations of the template.
2936 VarDecl *getTemplatedDecl() const {
2937 return static_cast<VarDecl *>(TemplatedDecl);
2940 /// Returns whether this template declaration defines the primary
2941 /// variable pattern.
2942 bool isThisDeclarationADefinition() const {
2943 return getTemplatedDecl()->isThisDeclarationADefinition();
2946 VarTemplateDecl *getDefinition();
2948 /// Create a variable template node.
2949 static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2950 SourceLocation L, DeclarationName Name,
2951 TemplateParameterList *Params,
2954 /// Create an empty variable template node.
2955 static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2957 /// Return the specialization with the provided arguments if it exists,
2958 /// otherwise return the insertion point.
2959 VarTemplateSpecializationDecl *
2960 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2962 /// Insert the specified specialization knowing that it is not already
2963 /// in. InsertPos must be obtained from findSpecialization.
2964 void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
2966 VarTemplateDecl *getCanonicalDecl() override {
2967 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2969 const VarTemplateDecl *getCanonicalDecl() const {
2970 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2973 /// Retrieve the previous declaration of this variable template, or
2974 /// nullptr if no such declaration exists.
2975 VarTemplateDecl *getPreviousDecl() {
2976 return cast_or_null<VarTemplateDecl>(
2977 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2979 const VarTemplateDecl *getPreviousDecl() const {
2980 return cast_or_null<VarTemplateDecl>(
2981 static_cast<const RedeclarableTemplateDecl *>(
2982 this)->getPreviousDecl());
2985 VarTemplateDecl *getMostRecentDecl() {
2986 return cast<VarTemplateDecl>(
2987 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2989 const VarTemplateDecl *getMostRecentDecl() const {
2990 return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
2993 VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
2994 return cast_or_null<VarTemplateDecl>(
2995 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2998 /// Return the partial specialization with the provided arguments if it
2999 /// exists, otherwise return the insertion point.
3000 VarTemplatePartialSpecializationDecl *
3001 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
3003 /// Insert the specified partial specialization knowing that it is not
3004 /// already in. InsertPos must be obtained from findPartialSpecialization.
3005 void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
3008 /// Retrieve the partial specializations as an ordered list.
3009 void getPartialSpecializations(
3010 SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
3012 /// Find a variable template partial specialization which was
3014 /// from the given member partial specialization.
3016 /// \param D a member variable template partial specialization.
3018 /// \returns the variable template partial specialization which was
3020 /// from the given member partial specialization, or nullptr if no such
3021 /// partial specialization exists.
3022 VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
3023 VarTemplatePartialSpecializationDecl *D);
3025 using spec_iterator = SpecIterator<VarTemplateSpecializationDecl>;
3026 using spec_range = llvm::iterator_range<spec_iterator>;
3028 spec_range specializations() const {
3029 return spec_range(spec_begin(), spec_end());
3032 spec_iterator spec_begin() const {
3033 return makeSpecIterator(getSpecializations(), false);
3036 spec_iterator spec_end() const {
3037 return makeSpecIterator(getSpecializations(), true);
3040 // Implement isa/cast/dyncast support
3041 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3042 static bool classofKind(Kind K) { return K == VarTemplate; }
3045 // \brief Declaration of a C++2a concept.
3046 class ConceptDecl : public TemplateDecl, public Mergeable<ConceptDecl> {
3048 Expr *ConstraintExpr;
3050 ConceptDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
3051 TemplateParameterList *Params, Expr *ConstraintExpr)
3052 : TemplateDecl(Concept, DC, L, Name, Params),
3053 ConstraintExpr(ConstraintExpr) {};
3055 static ConceptDecl *Create(ASTContext &C, DeclContext *DC,
3056 SourceLocation L, DeclarationName Name,
3057 TemplateParameterList *Params,
3058 Expr *ConstraintExpr);
3059 static ConceptDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3061 Expr *getConstraintExpr() const {
3062 return ConstraintExpr;
3065 SourceRange getSourceRange() const override LLVM_READONLY {
3066 return SourceRange(getTemplateParameters()->getTemplateLoc(),
3067 ConstraintExpr->getEndLoc());
3070 // Implement isa/cast/dyncast/etc.
3071 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3072 static bool classofKind(Kind K) { return K == Concept; }
3074 friend class ASTReader;
3075 friend class ASTDeclReader;
3076 friend class ASTDeclWriter;
3079 inline NamedDecl *getAsNamedDecl(TemplateParameter P) {
3080 if (auto *PD = P.dyn_cast<TemplateTypeParmDecl *>())
3082 if (auto *PD = P.dyn_cast<NonTypeTemplateParmDecl *>())
3084 return P.get<TemplateTemplateParmDecl *>();
3087 inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
3088 auto *TD = dyn_cast<TemplateDecl>(D);
3089 return TD && (isa<ClassTemplateDecl>(TD) ||
3090 isa<ClassTemplatePartialSpecializationDecl>(TD) ||
3091 isa<TypeAliasTemplateDecl>(TD) ||
3092 isa<TemplateTemplateParmDecl>(TD))
3097 } // namespace clang
3099 #endif // LLVM_CLANG_AST_DECLTEMPLATE_H