Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:36:33

0001 //===- DeclTemplate.h - Classes for representing C++ templates --*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 /// \file
0010 /// Defines the C++ template declaration subclasses.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
0015 #define LLVM_CLANG_AST_DECLTEMPLATE_H
0016 
0017 #include "clang/AST/ASTConcept.h"
0018 #include "clang/AST/ASTContext.h"
0019 #include "clang/AST/Decl.h"
0020 #include "clang/AST/DeclBase.h"
0021 #include "clang/AST/DeclCXX.h"
0022 #include "clang/AST/DeclarationName.h"
0023 #include "clang/AST/Redeclarable.h"
0024 #include "clang/AST/TemplateBase.h"
0025 #include "clang/AST/Type.h"
0026 #include "clang/Basic/LLVM.h"
0027 #include "clang/Basic/SourceLocation.h"
0028 #include "clang/Basic/Specifiers.h"
0029 #include "llvm/ADT/ArrayRef.h"
0030 #include "llvm/ADT/FoldingSet.h"
0031 #include "llvm/ADT/PointerIntPair.h"
0032 #include "llvm/ADT/PointerUnion.h"
0033 #include "llvm/ADT/iterator.h"
0034 #include "llvm/ADT/iterator_range.h"
0035 #include "llvm/Support/Casting.h"
0036 #include "llvm/Support/Compiler.h"
0037 #include "llvm/Support/TrailingObjects.h"
0038 #include <cassert>
0039 #include <cstddef>
0040 #include <cstdint>
0041 #include <iterator>
0042 #include <optional>
0043 #include <utility>
0044 
0045 namespace clang {
0046 
0047 enum BuiltinTemplateKind : int;
0048 class ClassTemplateDecl;
0049 class ClassTemplatePartialSpecializationDecl;
0050 class Expr;
0051 class FunctionTemplateDecl;
0052 class IdentifierInfo;
0053 class NonTypeTemplateParmDecl;
0054 class TemplateDecl;
0055 class TemplateTemplateParmDecl;
0056 class TemplateTypeParmDecl;
0057 class ConceptDecl;
0058 class UnresolvedSetImpl;
0059 class VarTemplateDecl;
0060 class VarTemplatePartialSpecializationDecl;
0061 
0062 /// Stores a template parameter of any kind.
0063 using TemplateParameter =
0064     llvm::PointerUnion<TemplateTypeParmDecl *, NonTypeTemplateParmDecl *,
0065                        TemplateTemplateParmDecl *>;
0066 
0067 NamedDecl *getAsNamedDecl(TemplateParameter P);
0068 
0069 /// Stores a list of template parameters for a TemplateDecl and its
0070 /// derived classes.
0071 class TemplateParameterList final
0072     : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
0073                                     Expr *> {
0074   /// The template argument list of the template parameter list.
0075   TemplateArgument *InjectedArgs = nullptr;
0076 
0077   /// The location of the 'template' keyword.
0078   SourceLocation TemplateLoc;
0079 
0080   /// The locations of the '<' and '>' angle brackets.
0081   SourceLocation LAngleLoc, RAngleLoc;
0082 
0083   /// The number of template parameters in this template
0084   /// parameter list.
0085   unsigned NumParams : 29;
0086 
0087   /// Whether this template parameter list contains an unexpanded parameter
0088   /// pack.
0089   LLVM_PREFERRED_TYPE(bool)
0090   unsigned ContainsUnexpandedParameterPack : 1;
0091 
0092   /// Whether this template parameter list has a requires clause.
0093   LLVM_PREFERRED_TYPE(bool)
0094   unsigned HasRequiresClause : 1;
0095 
0096   /// Whether any of the template parameters has constrained-parameter
0097   /// constraint-expression.
0098   LLVM_PREFERRED_TYPE(bool)
0099   unsigned HasConstrainedParameters : 1;
0100 
0101 protected:
0102   TemplateParameterList(const ASTContext& C, SourceLocation TemplateLoc,
0103                         SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
0104                         SourceLocation RAngleLoc, Expr *RequiresClause);
0105 
0106   size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
0107     return NumParams;
0108   }
0109 
0110   size_t numTrailingObjects(OverloadToken<Expr *>) const {
0111     return HasRequiresClause ? 1 : 0;
0112   }
0113 
0114 public:
0115   template <size_t N, bool HasRequiresClause>
0116   friend class FixedSizeTemplateParameterListStorage;
0117   friend TrailingObjects;
0118 
0119   static TemplateParameterList *Create(const ASTContext &C,
0120                                        SourceLocation TemplateLoc,
0121                                        SourceLocation LAngleLoc,
0122                                        ArrayRef<NamedDecl *> Params,
0123                                        SourceLocation RAngleLoc,
0124                                        Expr *RequiresClause);
0125 
0126   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) const;
0127 
0128   /// Iterates through the template parameters in this list.
0129   using iterator = NamedDecl **;
0130 
0131   /// Iterates through the template parameters in this list.
0132   using const_iterator = NamedDecl * const *;
0133 
0134   iterator begin() { return getTrailingObjects<NamedDecl *>(); }
0135   const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
0136   iterator end() { return begin() + NumParams; }
0137   const_iterator end() const { return begin() + NumParams; }
0138 
0139   unsigned size() const { return NumParams; }
0140   bool empty() const { return NumParams == 0; }
0141 
0142   ArrayRef<NamedDecl *> asArray() { return llvm::ArrayRef(begin(), end()); }
0143   ArrayRef<const NamedDecl*> asArray() const {
0144     return llvm::ArrayRef(begin(), size());
0145   }
0146 
0147   NamedDecl* getParam(unsigned Idx) {
0148     assert(Idx < size() && "Template parameter index out-of-range");
0149     return begin()[Idx];
0150   }
0151   const NamedDecl* getParam(unsigned Idx) const {
0152     assert(Idx < size() && "Template parameter index out-of-range");
0153     return begin()[Idx];
0154   }
0155 
0156   /// Returns the minimum number of arguments needed to form a
0157   /// template specialization.
0158   ///
0159   /// This may be fewer than the number of template parameters, if some of
0160   /// the parameters have default arguments or if there is a parameter pack.
0161   unsigned getMinRequiredArguments() const;
0162 
0163   /// Get the depth of this template parameter list in the set of
0164   /// template parameter lists.
0165   ///
0166   /// The first template parameter list in a declaration will have depth 0,
0167   /// the second template parameter list will have depth 1, etc.
0168   unsigned getDepth() const;
0169 
0170   /// Determine whether this template parameter list contains an
0171   /// unexpanded parameter pack.
0172   bool containsUnexpandedParameterPack() const;
0173 
0174   /// Determine whether this template parameter list contains a parameter pack.
0175   bool hasParameterPack() const {
0176     for (const NamedDecl *P : asArray())
0177       if (P->isParameterPack())
0178         return true;
0179     return false;
0180   }
0181 
0182   /// The constraint-expression of the associated requires-clause.
0183   Expr *getRequiresClause() {
0184     return HasRequiresClause ? getTrailingObjects<Expr *>()[0] : nullptr;
0185   }
0186 
0187   /// The constraint-expression of the associated requires-clause.
0188   const Expr *getRequiresClause() const {
0189     return HasRequiresClause ? getTrailingObjects<Expr *>()[0] : nullptr;
0190   }
0191 
0192   /// \brief All associated constraints derived from this template parameter
0193   /// list, including the requires clause and any constraints derived from
0194   /// constrained-parameters.
0195   ///
0196   /// The constraints in the resulting list are to be treated as if in a
0197   /// conjunction ("and").
0198   void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const;
0199 
0200   bool hasAssociatedConstraints() const;
0201 
0202   /// Get the template argument list of the template parameter list.
0203   ArrayRef<TemplateArgument> getInjectedTemplateArgs(const ASTContext &Context);
0204 
0205   SourceLocation getTemplateLoc() const { return TemplateLoc; }
0206   SourceLocation getLAngleLoc() const { return LAngleLoc; }
0207   SourceLocation getRAngleLoc() const { return RAngleLoc; }
0208 
0209   SourceRange getSourceRange() const LLVM_READONLY {
0210     return SourceRange(TemplateLoc, RAngleLoc);
0211   }
0212 
0213   void print(raw_ostream &Out, const ASTContext &Context,
0214              bool OmitTemplateKW = false) const;
0215   void print(raw_ostream &Out, const ASTContext &Context,
0216              const PrintingPolicy &Policy, bool OmitTemplateKW = false) const;
0217 
0218   static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy,
0219                                            const TemplateParameterList *TPL,
0220                                            unsigned Idx);
0221 };
0222 
0223 /// Stores a list of template parameters and the associated
0224 /// requires-clause (if any) for a TemplateDecl and its derived classes.
0225 /// Suitable for creating on the stack.
0226 template <size_t N, bool HasRequiresClause>
0227 class FixedSizeTemplateParameterListStorage
0228     : public TemplateParameterList::FixedSizeStorageOwner {
0229   typename TemplateParameterList::FixedSizeStorage<
0230       NamedDecl *, Expr *>::with_counts<
0231       N, HasRequiresClause ? 1u : 0u
0232       >::type storage;
0233 
0234 public:
0235   FixedSizeTemplateParameterListStorage(const ASTContext &C,
0236                                         SourceLocation TemplateLoc,
0237                                         SourceLocation LAngleLoc,
0238                                         ArrayRef<NamedDecl *> Params,
0239                                         SourceLocation RAngleLoc,
0240                                         Expr *RequiresClause)
0241       : FixedSizeStorageOwner(
0242             (assert(N == Params.size()),
0243              assert(HasRequiresClause == (RequiresClause != nullptr)),
0244              new (static_cast<void *>(&storage)) TemplateParameterList(C,
0245                  TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
0246 };
0247 
0248 /// A template argument list.
0249 class TemplateArgumentList final
0250     : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
0251   /// The number of template arguments in this template
0252   /// argument list.
0253   unsigned NumArguments;
0254 
0255   // Constructs an instance with an internal Argument list, containing
0256   // a copy of the Args array. (Called by CreateCopy)
0257   TemplateArgumentList(ArrayRef<TemplateArgument> Args);
0258 
0259 public:
0260   friend TrailingObjects;
0261 
0262   TemplateArgumentList(const TemplateArgumentList &) = delete;
0263   TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
0264 
0265   /// Create a new template argument list that copies the given set of
0266   /// template arguments.
0267   static TemplateArgumentList *CreateCopy(ASTContext &Context,
0268                                           ArrayRef<TemplateArgument> Args);
0269 
0270   /// Retrieve the template argument at a given index.
0271   const TemplateArgument &get(unsigned Idx) const {
0272     assert(Idx < NumArguments && "Invalid template argument index");
0273     return data()[Idx];
0274   }
0275 
0276   /// Retrieve the template argument at a given index.
0277   const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
0278 
0279   /// Produce this as an array ref.
0280   ArrayRef<TemplateArgument> asArray() const {
0281     return llvm::ArrayRef(data(), size());
0282   }
0283 
0284   /// Retrieve the number of template arguments in this
0285   /// template argument list.
0286   unsigned size() const { return NumArguments; }
0287 
0288   /// Retrieve a pointer to the template argument list.
0289   const TemplateArgument *data() const {
0290     return getTrailingObjects<TemplateArgument>();
0291   }
0292 };
0293 
0294 void *allocateDefaultArgStorageChain(const ASTContext &C);
0295 
0296 /// Storage for a default argument. This is conceptually either empty, or an
0297 /// argument value, or a pointer to a previous declaration that had a default
0298 /// argument.
0299 ///
0300 /// However, this is complicated by modules: while we require all the default
0301 /// arguments for a template to be equivalent, there may be more than one, and
0302 /// we need to track all the originating parameters to determine if the default
0303 /// argument is visible.
0304 template<typename ParmDecl, typename ArgType>
0305 class DefaultArgStorage {
0306   /// Storage for both the value *and* another parameter from which we inherit
0307   /// the default argument. This is used when multiple default arguments for a
0308   /// parameter are merged together from different modules.
0309   struct Chain {
0310     ParmDecl *PrevDeclWithDefaultArg;
0311     ArgType Value;
0312   };
0313   static_assert(sizeof(Chain) == sizeof(void *) * 2,
0314                 "non-pointer argument type?");
0315 
0316   llvm::PointerUnion<ArgType, ParmDecl*, Chain*> ValueOrInherited;
0317 
0318   static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
0319     const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
0320     if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl *>())
0321       Parm = Prev;
0322     assert(!isa<ParmDecl *>(Parm->getDefaultArgStorage().ValueOrInherited) &&
0323            "should only be one level of indirection");
0324     return Parm;
0325   }
0326 
0327 public:
0328   DefaultArgStorage() : ValueOrInherited(ArgType()) {}
0329 
0330   /// Determine whether there is a default argument for this parameter.
0331   bool isSet() const { return !ValueOrInherited.isNull(); }
0332 
0333   /// Determine whether the default argument for this parameter was inherited
0334   /// from a previous declaration of the same entity.
0335   bool isInherited() const { return isa<ParmDecl *>(ValueOrInherited); }
0336 
0337   /// Get the default argument's value. This does not consider whether the
0338   /// default argument is visible.
0339   ArgType get() const {
0340     const DefaultArgStorage *Storage = this;
0341     if (const auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl *>())
0342       Storage = &Prev->getDefaultArgStorage();
0343     if (const auto *C = Storage->ValueOrInherited.template dyn_cast<Chain *>())
0344       return C->Value;
0345     return cast<ArgType>(Storage->ValueOrInherited);
0346   }
0347 
0348   /// Get the parameter from which we inherit the default argument, if any.
0349   /// This is the parameter on which the default argument was actually written.
0350   const ParmDecl *getInheritedFrom() const {
0351     if (const auto *D = ValueOrInherited.template dyn_cast<ParmDecl *>())
0352       return D;
0353     if (const auto *C = ValueOrInherited.template dyn_cast<Chain *>())
0354       return C->PrevDeclWithDefaultArg;
0355     return nullptr;
0356   }
0357 
0358   /// Set the default argument.
0359   void set(ArgType Arg) {
0360     assert(!isSet() && "default argument already set");
0361     ValueOrInherited = Arg;
0362   }
0363 
0364   /// Set that the default argument was inherited from another parameter.
0365   void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
0366     InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
0367     if (!isSet())
0368       ValueOrInherited = InheritedFrom;
0369     else if ([[maybe_unused]] auto *D =
0370                  dyn_cast<ParmDecl *>(ValueOrInherited)) {
0371       assert(C.isSameDefaultTemplateArgument(D, InheritedFrom));
0372       ValueOrInherited =
0373           new (allocateDefaultArgStorageChain(C)) Chain{InheritedFrom, get()};
0374     } else if (auto *Inherited = dyn_cast<Chain *>(ValueOrInherited)) {
0375       assert(C.isSameDefaultTemplateArgument(Inherited->PrevDeclWithDefaultArg,
0376                                              InheritedFrom));
0377       Inherited->PrevDeclWithDefaultArg = InheritedFrom;
0378     } else
0379       ValueOrInherited = new (allocateDefaultArgStorageChain(C))
0380           Chain{InheritedFrom, cast<ArgType>(ValueOrInherited)};
0381   }
0382 
0383   /// Remove the default argument, even if it was inherited.
0384   void clear() {
0385     ValueOrInherited = ArgType();
0386   }
0387 };
0388 
0389 //===----------------------------------------------------------------------===//
0390 // Kinds of Templates
0391 //===----------------------------------------------------------------------===//
0392 
0393 /// \brief The base class of all kinds of template declarations (e.g.,
0394 /// class, function, etc.).
0395 ///
0396 /// The TemplateDecl class stores the list of template parameters and a
0397 /// reference to the templated scoped declaration: the underlying AST node.
0398 class TemplateDecl : public NamedDecl {
0399   void anchor() override;
0400 
0401 protected:
0402   // Construct a template decl with name, parameters, and templated element.
0403   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
0404                TemplateParameterList *Params, NamedDecl *Decl);
0405 
0406   // Construct a template decl with the given name and parameters.
0407   // Used when there is no templated element (e.g., for tt-params).
0408   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
0409                TemplateParameterList *Params)
0410       : TemplateDecl(DK, DC, L, Name, Params, nullptr) {}
0411 
0412 public:
0413   friend class ASTDeclReader;
0414   friend class ASTDeclWriter;
0415 
0416   /// Get the list of template parameters
0417   TemplateParameterList *getTemplateParameters() const {
0418     return TemplateParams;
0419   }
0420 
0421   /// \brief Get the total constraint-expression associated with this template,
0422   /// including constraint-expressions derived from the requires-clause,
0423   /// trailing requires-clause (for functions and methods) and constrained
0424   /// template parameters.
0425   void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const;
0426 
0427   bool hasAssociatedConstraints() const;
0428 
0429   /// Get the underlying, templated declaration.
0430   NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
0431 
0432   // Should a specialization behave like an alias for another type.
0433   bool isTypeAlias() const;
0434 
0435   // Implement isa/cast/dyncast/etc.
0436   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
0437 
0438   static bool classofKind(Kind K) {
0439     return K >= firstTemplate && K <= lastTemplate;
0440   }
0441 
0442   SourceRange getSourceRange() const override LLVM_READONLY {
0443     return SourceRange(getTemplateParameters()->getTemplateLoc(),
0444                        TemplatedDecl->getSourceRange().getEnd());
0445   }
0446 
0447 protected:
0448   NamedDecl *TemplatedDecl;
0449   TemplateParameterList *TemplateParams;
0450 
0451 public:
0452   void setTemplateParameters(TemplateParameterList *TParams) {
0453     TemplateParams = TParams;
0454   }
0455 
0456   /// Initialize the underlying templated declaration.
0457   void init(NamedDecl *NewTemplatedDecl) {
0458     if (TemplatedDecl)
0459       assert(TemplatedDecl == NewTemplatedDecl && "Inconsistent TemplatedDecl");
0460     else
0461       TemplatedDecl = NewTemplatedDecl;
0462   }
0463 };
0464 
0465 /// Provides information about a function template specialization,
0466 /// which is a FunctionDecl that has been explicitly specialization or
0467 /// instantiated from a function template.
0468 class FunctionTemplateSpecializationInfo final
0469     : public llvm::FoldingSetNode,
0470       private llvm::TrailingObjects<FunctionTemplateSpecializationInfo,
0471                                     MemberSpecializationInfo *> {
0472   /// The function template specialization that this structure describes and a
0473   /// flag indicating if the function is a member specialization.
0474   llvm::PointerIntPair<FunctionDecl *, 1, bool> Function;
0475 
0476   /// The function template from which this function template
0477   /// specialization was generated.
0478   ///
0479   /// The two bits contain the top 4 values of TemplateSpecializationKind.
0480   llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
0481 
0482 public:
0483   /// The template arguments used to produce the function template
0484   /// specialization from the function template.
0485   TemplateArgumentList *TemplateArguments;
0486 
0487   /// The template arguments as written in the sources, if provided.
0488   /// FIXME: Normally null; tail-allocate this.
0489   const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
0490 
0491   /// The point at which this function template specialization was
0492   /// first instantiated.
0493   SourceLocation PointOfInstantiation;
0494 
0495 private:
0496   FunctionTemplateSpecializationInfo(
0497       FunctionDecl *FD, FunctionTemplateDecl *Template,
0498       TemplateSpecializationKind TSK, TemplateArgumentList *TemplateArgs,
0499       const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
0500       SourceLocation POI, MemberSpecializationInfo *MSInfo)
0501       : Function(FD, MSInfo ? true : false), Template(Template, TSK - 1),
0502         TemplateArguments(TemplateArgs),
0503         TemplateArgumentsAsWritten(TemplateArgsAsWritten),
0504         PointOfInstantiation(POI) {
0505     if (MSInfo)
0506       getTrailingObjects<MemberSpecializationInfo *>()[0] = MSInfo;
0507   }
0508 
0509   size_t numTrailingObjects(OverloadToken<MemberSpecializationInfo*>) const {
0510     return Function.getInt();
0511   }
0512 
0513 public:
0514   friend TrailingObjects;
0515 
0516   static FunctionTemplateSpecializationInfo *
0517   Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
0518          TemplateSpecializationKind TSK, TemplateArgumentList *TemplateArgs,
0519          const TemplateArgumentListInfo *TemplateArgsAsWritten,
0520          SourceLocation POI, MemberSpecializationInfo *MSInfo);
0521 
0522   /// Retrieve the declaration of the function template specialization.
0523   FunctionDecl *getFunction() const { return Function.getPointer(); }
0524 
0525   /// Retrieve the template from which this function was specialized.
0526   FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
0527 
0528   /// Determine what kind of template specialization this is.
0529   TemplateSpecializationKind getTemplateSpecializationKind() const {
0530     return (TemplateSpecializationKind)(Template.getInt() + 1);
0531   }
0532 
0533   bool isExplicitSpecialization() const {
0534     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
0535   }
0536 
0537   /// True if this declaration is an explicit specialization,
0538   /// explicit instantiation declaration, or explicit instantiation
0539   /// definition.
0540   bool isExplicitInstantiationOrSpecialization() const {
0541     return isTemplateExplicitInstantiationOrSpecialization(
0542         getTemplateSpecializationKind());
0543   }
0544 
0545   /// Set the template specialization kind.
0546   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
0547     assert(TSK != TSK_Undeclared &&
0548          "Cannot encode TSK_Undeclared for a function template specialization");
0549     Template.setInt(TSK - 1);
0550   }
0551 
0552   /// Retrieve the first point of instantiation of this function
0553   /// template specialization.
0554   ///
0555   /// The point of instantiation may be an invalid source location if this
0556   /// function has yet to be instantiated.
0557   SourceLocation getPointOfInstantiation() const {
0558     return PointOfInstantiation;
0559   }
0560 
0561   /// Set the (first) point of instantiation of this function template
0562   /// specialization.
0563   void setPointOfInstantiation(SourceLocation POI) {
0564     PointOfInstantiation = POI;
0565   }
0566 
0567   /// Get the specialization info if this function template specialization is
0568   /// also a member specialization:
0569   ///
0570   /// \code
0571   /// template<typename> struct A {
0572   ///   template<typename> void f();
0573   ///   template<> void f<int>();
0574   /// };
0575   /// \endcode
0576   ///
0577   /// Here, A<int>::f<int> is a function template specialization that is
0578   /// an explicit specialization of A<int>::f, but it's also a member
0579   /// specialization (an implicit instantiation in this case) of A::f<int>.
0580   /// Further:
0581   ///
0582   /// \code
0583   /// template<> template<> void A<int>::f<int>() {}
0584   /// \endcode
0585   ///
0586   /// ... declares a function template specialization that is an explicit
0587   /// specialization of A<int>::f, and is also an explicit member
0588   /// specialization of A::f<int>.
0589   ///
0590   /// Note that the TemplateSpecializationKind of the MemberSpecializationInfo
0591   /// need not be the same as that returned by getTemplateSpecializationKind(),
0592   /// and represents the relationship between the function and the class-scope
0593   /// explicit specialization in the original templated class -- whereas our
0594   /// TemplateSpecializationKind represents the relationship between the
0595   /// function and the function template, and should always be
0596   /// TSK_ExplicitSpecialization whenever we have MemberSpecializationInfo.
0597   MemberSpecializationInfo *getMemberSpecializationInfo() const {
0598     return numTrailingObjects(OverloadToken<MemberSpecializationInfo *>())
0599                ? getTrailingObjects<MemberSpecializationInfo *>()[0]
0600                : nullptr;
0601   }
0602 
0603   void Profile(llvm::FoldingSetNodeID &ID) {
0604     Profile(ID, TemplateArguments->asArray(), getFunction()->getASTContext());
0605   }
0606 
0607   static void
0608   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
0609           const ASTContext &Context) {
0610     ID.AddInteger(TemplateArgs.size());
0611     for (const TemplateArgument &TemplateArg : TemplateArgs)
0612       TemplateArg.Profile(ID, Context);
0613   }
0614 };
0615 
0616 /// Provides information a specialization of a member of a class
0617 /// template, which may be a member function, static data member,
0618 /// member class or member enumeration.
0619 class MemberSpecializationInfo {
0620   // The member declaration from which this member was instantiated, and the
0621   // manner in which the instantiation occurred (in the lower two bits).
0622   llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
0623 
0624   // The point at which this member was first instantiated.
0625   SourceLocation PointOfInstantiation;
0626 
0627 public:
0628   explicit
0629   MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
0630                            SourceLocation POI = SourceLocation())
0631       : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
0632     assert(TSK != TSK_Undeclared &&
0633            "Cannot encode undeclared template specializations for members");
0634   }
0635 
0636   /// Retrieve the member declaration from which this member was
0637   /// instantiated.
0638   NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
0639 
0640   /// Determine what kind of template specialization this is.
0641   TemplateSpecializationKind getTemplateSpecializationKind() const {
0642     return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
0643   }
0644 
0645   bool isExplicitSpecialization() const {
0646     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
0647   }
0648 
0649   /// Set the template specialization kind.
0650   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
0651     assert(TSK != TSK_Undeclared &&
0652            "Cannot encode undeclared template specializations for members");
0653     MemberAndTSK.setInt(TSK - 1);
0654   }
0655 
0656   /// Retrieve the first point of instantiation of this member.
0657   /// If the point of instantiation is an invalid location, then this member
0658   /// has not yet been instantiated.
0659   SourceLocation getPointOfInstantiation() const {
0660     return PointOfInstantiation;
0661   }
0662 
0663   /// Set the first point of instantiation.
0664   void setPointOfInstantiation(SourceLocation POI) {
0665     PointOfInstantiation = POI;
0666   }
0667 };
0668 
0669 /// Provides information about a dependent function-template
0670 /// specialization declaration.
0671 ///
0672 /// This is used for function templates explicit specializations declared
0673 /// within class templates:
0674 ///
0675 /// \code
0676 /// template<typename> struct A {
0677 ///   template<typename> void f();
0678 ///   template<> void f<int>(); // DependentFunctionTemplateSpecializationInfo
0679 /// };
0680 /// \endcode
0681 ///
0682 /// As well as dependent friend declarations naming function template
0683 /// specializations declared within class templates:
0684 ///
0685 /// \code
0686 ///   template \<class T> void foo(T);
0687 ///   template \<class T> class A {
0688 ///     friend void foo<>(T); // DependentFunctionTemplateSpecializationInfo
0689 ///   };
0690 /// \endcode
0691 class DependentFunctionTemplateSpecializationInfo final
0692     : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
0693                                     FunctionTemplateDecl *> {
0694   friend TrailingObjects;
0695 
0696   /// The number of candidates for the primary template.
0697   unsigned NumCandidates;
0698 
0699   DependentFunctionTemplateSpecializationInfo(
0700       const UnresolvedSetImpl &Candidates,
0701       const ASTTemplateArgumentListInfo *TemplateArgsWritten);
0702 
0703 public:
0704   /// The template arguments as written in the sources, if provided.
0705   const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
0706 
0707   static DependentFunctionTemplateSpecializationInfo *
0708   Create(ASTContext &Context, const UnresolvedSetImpl &Candidates,
0709          const TemplateArgumentListInfo *TemplateArgs);
0710 
0711   /// Returns the candidates for the primary function template.
0712   ArrayRef<FunctionTemplateDecl *> getCandidates() const {
0713     return {getTrailingObjects<FunctionTemplateDecl *>(), NumCandidates};
0714   }
0715 };
0716 
0717 /// Declaration of a redeclarable template.
0718 class RedeclarableTemplateDecl : public TemplateDecl,
0719                                  public Redeclarable<RedeclarableTemplateDecl>
0720 {
0721   using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>;
0722 
0723   RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
0724     return getNextRedeclaration();
0725   }
0726 
0727   RedeclarableTemplateDecl *getPreviousDeclImpl() override {
0728     return getPreviousDecl();
0729   }
0730 
0731   RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
0732     return getMostRecentDecl();
0733   }
0734 
0735   void anchor() override;
0736 
0737 protected:
0738   template <typename EntryType> struct SpecEntryTraits {
0739     using DeclType = EntryType;
0740 
0741     static DeclType *getDecl(EntryType *D) {
0742       return D;
0743     }
0744 
0745     static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
0746       return D->getTemplateArgs().asArray();
0747     }
0748   };
0749 
0750   template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
0751             typename DeclType = typename SETraits::DeclType>
0752   struct SpecIterator
0753       : llvm::iterator_adaptor_base<
0754             SpecIterator<EntryType, SETraits, DeclType>,
0755             typename llvm::FoldingSetVector<EntryType>::iterator,
0756             typename std::iterator_traits<typename llvm::FoldingSetVector<
0757                 EntryType>::iterator>::iterator_category,
0758             DeclType *, ptrdiff_t, DeclType *, DeclType *> {
0759     SpecIterator() = default;
0760     explicit SpecIterator(
0761         typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
0762         : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
0763 
0764     DeclType *operator*() const {
0765       return SETraits::getDecl(&*this->I)->getMostRecentDecl();
0766     }
0767 
0768     DeclType *operator->() const { return **this; }
0769   };
0770 
0771   template <typename EntryType>
0772   static SpecIterator<EntryType>
0773   makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
0774     return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
0775   }
0776 
0777   void loadLazySpecializationsImpl(bool OnlyPartial = false) const;
0778 
0779   bool loadLazySpecializationsImpl(llvm::ArrayRef<TemplateArgument> Args,
0780                                    TemplateParameterList *TPL = nullptr) const;
0781 
0782   template <class EntryType, typename ...ProfileArguments>
0783   typename SpecEntryTraits<EntryType>::DeclType*
0784   findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
0785                          void *&InsertPos, ProfileArguments &&...ProfileArgs);
0786 
0787   template <class EntryType, typename... ProfileArguments>
0788   typename SpecEntryTraits<EntryType>::DeclType *
0789   findSpecializationLocally(llvm::FoldingSetVector<EntryType> &Specs,
0790                             void *&InsertPos,
0791                             ProfileArguments &&...ProfileArgs);
0792 
0793   template <class Derived, class EntryType>
0794   void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
0795                              EntryType *Entry, void *InsertPos);
0796 
0797   struct CommonBase {
0798     CommonBase() : InstantiatedFromMember(nullptr, false) {}
0799 
0800     /// The template from which this was most
0801     /// directly instantiated (or null).
0802     ///
0803     /// The boolean value indicates whether this template
0804     /// was explicitly specialized.
0805     llvm::PointerIntPair<RedeclarableTemplateDecl *, 1, bool>
0806         InstantiatedFromMember;
0807   };
0808 
0809   /// Pointer to the common data shared by all declarations of this
0810   /// template.
0811   mutable CommonBase *Common = nullptr;
0812 
0813   /// Retrieves the "common" pointer shared by all (re-)declarations of
0814   /// the same template. Calling this routine may implicitly allocate memory
0815   /// for the common pointer.
0816   CommonBase *getCommonPtr() const;
0817 
0818   virtual CommonBase *newCommon(ASTContext &C) const = 0;
0819 
0820   // Construct a template decl with name, parameters, and templated element.
0821   RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
0822                            SourceLocation L, DeclarationName Name,
0823                            TemplateParameterList *Params, NamedDecl *Decl)
0824       : TemplateDecl(DK, DC, L, Name, Params, Decl), redeclarable_base(C) {}
0825 
0826 public:
0827   friend class ASTDeclReader;
0828   friend class ASTDeclWriter;
0829   friend class ASTReader;
0830   template <class decl_type> friend class RedeclarableTemplate;
0831 
0832   /// Retrieves the canonical declaration of this template.
0833   RedeclarableTemplateDecl *getCanonicalDecl() override {
0834     return getFirstDecl();
0835   }
0836   const RedeclarableTemplateDecl *getCanonicalDecl() const {
0837     return getFirstDecl();
0838   }
0839 
0840   /// Determines whether this template was a specialization of a
0841   /// member template.
0842   ///
0843   /// In the following example, the function template \c X<int>::f and the
0844   /// member template \c X<int>::Inner are member specializations.
0845   ///
0846   /// \code
0847   /// template<typename T>
0848   /// struct X {
0849   ///   template<typename U> void f(T, U);
0850   ///   template<typename U> struct Inner;
0851   /// };
0852   ///
0853   /// template<> template<typename T>
0854   /// void X<int>::f(int, T);
0855   /// template<> template<typename T>
0856   /// struct X<int>::Inner { /* ... */ };
0857   /// \endcode
0858   bool isMemberSpecialization() const {
0859     return getCommonPtr()->InstantiatedFromMember.getInt();
0860   }
0861 
0862   /// Note that this member template is a specialization.
0863   void setMemberSpecialization() {
0864     assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
0865            "Only member templates can be member template specializations");
0866     getCommonPtr()->InstantiatedFromMember.setInt(true);
0867   }
0868 
0869   /// Retrieve the member template from which this template was
0870   /// instantiated, or nullptr if this template was not instantiated from a
0871   /// member template.
0872   ///
0873   /// A template is instantiated from a member template when the member
0874   /// template itself is part of a class template (or member thereof). For
0875   /// example, given
0876   ///
0877   /// \code
0878   /// template<typename T>
0879   /// struct X {
0880   ///   template<typename U> void f(T, U);
0881   /// };
0882   ///
0883   /// void test(X<int> x) {
0884   ///   x.f(1, 'a');
0885   /// };
0886   /// \endcode
0887   ///
0888   /// \c X<int>::f is a FunctionTemplateDecl that describes the function
0889   /// template
0890   ///
0891   /// \code
0892   /// template<typename U> void X<int>::f(int, U);
0893   /// \endcode
0894   ///
0895   /// which was itself created during the instantiation of \c X<int>. Calling
0896   /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
0897   /// retrieve the FunctionTemplateDecl for the original template \c f within
0898   /// the class template \c X<T>, i.e.,
0899   ///
0900   /// \code
0901   /// template<typename T>
0902   /// template<typename U>
0903   /// void X<T>::f(T, U);
0904   /// \endcode
0905   RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
0906     return getCommonPtr()->InstantiatedFromMember.getPointer();
0907   }
0908 
0909   void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
0910     assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
0911     getCommonPtr()->InstantiatedFromMember.setPointer(TD);
0912   }
0913 
0914   /// Retrieve the "injected" template arguments that correspond to the
0915   /// template parameters of this template.
0916   ///
0917   /// Although the C++ standard has no notion of the "injected" template
0918   /// arguments for a template, the notion is convenient when
0919   /// we need to perform substitutions inside the definition of a template.
0920   ArrayRef<TemplateArgument>
0921   getInjectedTemplateArgs(const ASTContext &Context) const {
0922     return getTemplateParameters()->getInjectedTemplateArgs(Context);
0923   }
0924 
0925   using redecl_range = redeclarable_base::redecl_range;
0926   using redecl_iterator = redeclarable_base::redecl_iterator;
0927 
0928   using redeclarable_base::redecls_begin;
0929   using redeclarable_base::redecls_end;
0930   using redeclarable_base::redecls;
0931   using redeclarable_base::getPreviousDecl;
0932   using redeclarable_base::getMostRecentDecl;
0933   using redeclarable_base::isFirstDecl;
0934 
0935   // Implement isa/cast/dyncast/etc.
0936   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
0937 
0938   static bool classofKind(Kind K) {
0939     return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
0940   }
0941 };
0942 
0943 template <> struct RedeclarableTemplateDecl::
0944 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
0945   using DeclType = FunctionDecl;
0946 
0947   static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
0948     return I->getFunction();
0949   }
0950 
0951   static ArrayRef<TemplateArgument>
0952   getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
0953     return I->TemplateArguments->asArray();
0954   }
0955 };
0956 
0957 /// Declaration of a template function.
0958 class FunctionTemplateDecl : public RedeclarableTemplateDecl {
0959 protected:
0960   friend class FunctionDecl;
0961 
0962   /// Data that is common to all of the declarations of a given
0963   /// function template.
0964   struct Common : CommonBase {
0965     /// The function template specializations for this function
0966     /// template, including explicit specializations and instantiations.
0967     llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
0968 
0969     Common() = default;
0970   };
0971 
0972   FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
0973                        DeclarationName Name, TemplateParameterList *Params,
0974                        NamedDecl *Decl)
0975       : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
0976                                  Decl) {}
0977 
0978   CommonBase *newCommon(ASTContext &C) const override;
0979 
0980   Common *getCommonPtr() const {
0981     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
0982   }
0983 
0984   /// Retrieve the set of function template specializations of this
0985   /// function template.
0986   llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
0987   getSpecializations() const;
0988 
0989   /// Add a specialization of this function template.
0990   ///
0991   /// \param InsertPos Insert position in the FoldingSetVector, must have been
0992   ///        retrieved by an earlier call to findSpecialization().
0993   void addSpecialization(FunctionTemplateSpecializationInfo* Info,
0994                          void *InsertPos);
0995 
0996 public:
0997   friend class ASTDeclReader;
0998   friend class ASTDeclWriter;
0999 
1000   /// Load any lazily-loaded specializations from the external source.
1001   void LoadLazySpecializations() const;
1002 
1003   /// Get the underlying function declaration of the template.
1004   FunctionDecl *getTemplatedDecl() const {
1005     return static_cast<FunctionDecl *>(TemplatedDecl);
1006   }
1007 
1008   /// Returns whether this template declaration defines the primary
1009   /// pattern.
1010   bool isThisDeclarationADefinition() const {
1011     return getTemplatedDecl()->isThisDeclarationADefinition();
1012   }
1013 
1014   bool isCompatibleWithDefinition() const {
1015     return getTemplatedDecl()->isInstantiatedFromMemberTemplate() ||
1016            isThisDeclarationADefinition();
1017   }
1018 
1019   // This bit closely tracks 'RedeclarableTemplateDecl::InstantiatedFromMember',
1020   // except this is per declaration, while the redeclarable field is
1021   // per chain. This indicates a template redeclaration which
1022   // is compatible with the definition, in the non-trivial case
1023   // where this is not already a definition.
1024   // This is only really needed for instantiating the definition of friend
1025   // function templates, which can have redeclarations in different template
1026   // contexts.
1027   // The bit is actually stored in the FunctionDecl for space efficiency
1028   // reasons.
1029   void setInstantiatedFromMemberTemplate(FunctionTemplateDecl *D) {
1030     getTemplatedDecl()->setInstantiatedFromMemberTemplate();
1031     RedeclarableTemplateDecl::setInstantiatedFromMemberTemplate(D);
1032   }
1033 
1034   /// Return the specialization with the provided arguments if it exists,
1035   /// otherwise return the insertion point.
1036   FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
1037                                    void *&InsertPos);
1038 
1039   FunctionTemplateDecl *getCanonicalDecl() override {
1040     return cast<FunctionTemplateDecl>(
1041              RedeclarableTemplateDecl::getCanonicalDecl());
1042   }
1043   const FunctionTemplateDecl *getCanonicalDecl() const {
1044     return cast<FunctionTemplateDecl>(
1045              RedeclarableTemplateDecl::getCanonicalDecl());
1046   }
1047 
1048   /// Retrieve the previous declaration of this function template, or
1049   /// nullptr if no such declaration exists.
1050   FunctionTemplateDecl *getPreviousDecl() {
1051     return cast_or_null<FunctionTemplateDecl>(
1052              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1053   }
1054   const FunctionTemplateDecl *getPreviousDecl() const {
1055     return cast_or_null<FunctionTemplateDecl>(
1056        static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1057   }
1058 
1059   FunctionTemplateDecl *getMostRecentDecl() {
1060     return cast<FunctionTemplateDecl>(
1061         static_cast<RedeclarableTemplateDecl *>(this)
1062             ->getMostRecentDecl());
1063   }
1064   const FunctionTemplateDecl *getMostRecentDecl() const {
1065     return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
1066   }
1067 
1068   FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
1069     return cast_or_null<FunctionTemplateDecl>(
1070              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1071   }
1072 
1073   using spec_iterator = SpecIterator<FunctionTemplateSpecializationInfo>;
1074   using spec_range = llvm::iterator_range<spec_iterator>;
1075 
1076   spec_range specializations() const {
1077     return spec_range(spec_begin(), spec_end());
1078   }
1079 
1080   spec_iterator spec_begin() const {
1081     return makeSpecIterator(getSpecializations(), false);
1082   }
1083 
1084   spec_iterator spec_end() const {
1085     return makeSpecIterator(getSpecializations(), true);
1086   }
1087 
1088   /// Return whether this function template is an abbreviated function template,
1089   /// e.g. `void foo(auto x)` or `template<typename T> void foo(auto x)`
1090   bool isAbbreviated() const {
1091     // Since the invented template parameters generated from 'auto' parameters
1092     // are either appended to the end of the explicit template parameter list or
1093     // form a new template parameter list, we can simply observe the last
1094     // parameter to determine if such a thing happened.
1095     const TemplateParameterList *TPL = getTemplateParameters();
1096     return TPL->getParam(TPL->size() - 1)->isImplicit();
1097   }
1098 
1099   /// Merge \p Prev with our RedeclarableTemplateDecl::Common.
1100   void mergePrevDecl(FunctionTemplateDecl *Prev);
1101 
1102   /// Create a function template node.
1103   static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1104                                       SourceLocation L,
1105                                       DeclarationName Name,
1106                                       TemplateParameterList *Params,
1107                                       NamedDecl *Decl);
1108 
1109   /// Create an empty function template node.
1110   static FunctionTemplateDecl *CreateDeserialized(ASTContext &C,
1111                                                   GlobalDeclID ID);
1112 
1113   // Implement isa/cast/dyncast support
1114   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1115   static bool classofKind(Kind K) { return K == FunctionTemplate; }
1116 };
1117 
1118 //===----------------------------------------------------------------------===//
1119 // Kinds of Template Parameters
1120 //===----------------------------------------------------------------------===//
1121 
1122 /// Defines the position of a template parameter within a template
1123 /// parameter list.
1124 ///
1125 /// Because template parameter can be listed
1126 /// sequentially for out-of-line template members, each template parameter is
1127 /// given a Depth - the nesting of template parameter scopes - and a Position -
1128 /// the occurrence within the parameter list.
1129 /// This class is inheritedly privately by different kinds of template
1130 /// parameters and is not part of the Decl hierarchy. Just a facility.
1131 class TemplateParmPosition {
1132 protected:
1133   enum { DepthWidth = 20, PositionWidth = 12 };
1134   unsigned Depth : DepthWidth;
1135   unsigned Position : PositionWidth;
1136 
1137   static constexpr unsigned MaxDepth = (1U << DepthWidth) - 1;
1138   static constexpr unsigned MaxPosition = (1U << PositionWidth) - 1;
1139 
1140   TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {
1141     // The input may fill maximum values to show that it is invalid.
1142     // Add one here to convert it to zero.
1143     assert((D + 1) <= MaxDepth &&
1144            "The depth of template parmeter position is more than 2^20!");
1145     assert((P + 1) <= MaxPosition &&
1146            "The position of template parmeter position is more than 2^12!");
1147   }
1148 
1149 public:
1150   TemplateParmPosition() = delete;
1151 
1152   /// Get the nesting depth of the template parameter.
1153   unsigned getDepth() const { return Depth; }
1154   void setDepth(unsigned D) {
1155     assert((D + 1) <= MaxDepth &&
1156            "The depth of template parmeter position is more than 2^20!");
1157     Depth = D;
1158   }
1159 
1160   /// Get the position of the template parameter within its parameter list.
1161   unsigned getPosition() const { return Position; }
1162   void setPosition(unsigned P) {
1163     assert((P + 1) <= MaxPosition &&
1164            "The position of template parmeter position is more than 2^12!");
1165     Position = P;
1166   }
1167 
1168   /// Get the index of the template parameter within its parameter list.
1169   unsigned getIndex() const { return Position; }
1170 };
1171 
1172 /// Declaration of a template type parameter.
1173 ///
1174 /// For example, "T" in
1175 /// \code
1176 /// template<typename T> class vector;
1177 /// \endcode
1178 class TemplateTypeParmDecl final : public TypeDecl,
1179     private llvm::TrailingObjects<TemplateTypeParmDecl, TypeConstraint> {
1180   /// Sema creates these on the stack during auto type deduction.
1181   friend class Sema;
1182   friend TrailingObjects;
1183   friend class ASTDeclReader;
1184 
1185   /// Whether this template type parameter was declaration with
1186   /// the 'typename' keyword.
1187   ///
1188   /// If false, it was declared with the 'class' keyword.
1189   bool Typename : 1;
1190 
1191   /// Whether this template type parameter has a type-constraint construct.
1192   bool HasTypeConstraint : 1;
1193 
1194   /// Whether the type constraint has been initialized. This can be false if the
1195   /// constraint was not initialized yet or if there was an error forming the
1196   /// type constraint.
1197   bool TypeConstraintInitialized : 1;
1198 
1199   /// Whether this type template parameter is an "expanded"
1200   /// parameter pack, meaning that its type is a pack expansion and we
1201   /// already know the set of types that expansion expands to.
1202   bool ExpandedParameterPack : 1;
1203 
1204   /// The number of type parameters in an expanded parameter pack.
1205   unsigned NumExpanded = 0;
1206 
1207   /// The default template argument, if any.
1208   using DefArgStorage =
1209       DefaultArgStorage<TemplateTypeParmDecl, TemplateArgumentLoc *>;
1210   DefArgStorage DefaultArgument;
1211 
1212   TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
1213                        SourceLocation IdLoc, IdentifierInfo *Id, bool Typename,
1214                        bool HasTypeConstraint,
1215                        std::optional<unsigned> NumExpanded)
1216       : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
1217         HasTypeConstraint(HasTypeConstraint), TypeConstraintInitialized(false),
1218         ExpandedParameterPack(NumExpanded),
1219         NumExpanded(NumExpanded.value_or(0)) {}
1220 
1221 public:
1222   static TemplateTypeParmDecl *
1223   Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc,
1224          SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1225          bool Typename, bool ParameterPack, bool HasTypeConstraint = false,
1226          std::optional<unsigned> NumExpanded = std::nullopt);
1227   static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
1228                                                   GlobalDeclID ID);
1229   static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
1230                                                   GlobalDeclID ID,
1231                                                   bool HasTypeConstraint);
1232 
1233   /// Whether this template type parameter was declared with
1234   /// the 'typename' keyword.
1235   ///
1236   /// If not, it was either declared with the 'class' keyword or with a
1237   /// type-constraint (see hasTypeConstraint()).
1238   bool wasDeclaredWithTypename() const {
1239     return Typename && !HasTypeConstraint;
1240   }
1241 
1242   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1243 
1244   /// Determine whether this template parameter has a default
1245   /// argument.
1246   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1247 
1248   /// Retrieve the default argument, if any.
1249   const TemplateArgumentLoc &getDefaultArgument() const {
1250     static const TemplateArgumentLoc NoneLoc;
1251     return DefaultArgument.isSet() ? *DefaultArgument.get() : NoneLoc;
1252   }
1253 
1254   /// Retrieves the location of the default argument declaration.
1255   SourceLocation getDefaultArgumentLoc() const;
1256 
1257   /// Determines whether the default argument was inherited
1258   /// from a previous declaration of this template.
1259   bool defaultArgumentWasInherited() const {
1260     return DefaultArgument.isInherited();
1261   }
1262 
1263   /// Set the default argument for this template parameter.
1264   void setDefaultArgument(const ASTContext &C,
1265                           const TemplateArgumentLoc &DefArg);
1266 
1267   /// Set that this default argument was inherited from another
1268   /// parameter.
1269   void setInheritedDefaultArgument(const ASTContext &C,
1270                                    TemplateTypeParmDecl *Prev) {
1271     DefaultArgument.setInherited(C, Prev);
1272   }
1273 
1274   /// Removes the default argument of this template parameter.
1275   void removeDefaultArgument() {
1276     DefaultArgument.clear();
1277   }
1278 
1279   /// Set whether this template type parameter was declared with
1280   /// the 'typename' or 'class' keyword.
1281   void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1282 
1283   /// Retrieve the depth of the template parameter.
1284   unsigned getDepth() const;
1285 
1286   /// Retrieve the index of the template parameter.
1287   unsigned getIndex() const;
1288 
1289   /// Returns whether this is a parameter pack.
1290   bool isParameterPack() const;
1291 
1292   /// Whether this parameter pack is a pack expansion.
1293   ///
1294   /// A template type template parameter pack can be a pack expansion if its
1295   /// type-constraint contains an unexpanded parameter pack.
1296   bool isPackExpansion() const {
1297     if (!isParameterPack())
1298       return false;
1299     if (const TypeConstraint *TC = getTypeConstraint())
1300       if (TC->hasExplicitTemplateArgs())
1301         for (const auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
1302           if (ArgLoc.getArgument().containsUnexpandedParameterPack())
1303             return true;
1304     return false;
1305   }
1306 
1307   /// Whether this parameter is a template type parameter pack that has a known
1308   /// list of different type-constraints at different positions.
1309   ///
1310   /// A parameter pack is an expanded parameter pack when the original
1311   /// parameter pack's type-constraint was itself a pack expansion, and that
1312   /// expansion has already been expanded. For example, given:
1313   ///
1314   /// \code
1315   /// template<typename ...Types>
1316   /// struct X {
1317   ///   template<convertible_to<Types> ...Convertibles>
1318   ///   struct Y { /* ... */ };
1319   /// };
1320   /// \endcode
1321   ///
1322   /// The parameter pack \c Convertibles has (convertible_to<Types> && ...) as
1323   /// its type-constraint. When \c Types is supplied with template arguments by
1324   /// instantiating \c X, the instantiation of \c Convertibles becomes an
1325   /// expanded parameter pack. For example, instantiating
1326   /// \c X<int, unsigned int> results in \c Convertibles being an expanded
1327   /// parameter pack of size 2 (use getNumExpansionTypes() to get this number).
1328   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1329 
1330   /// Retrieves the number of parameters in an expanded parameter pack.
1331   unsigned getNumExpansionParameters() const {
1332     assert(ExpandedParameterPack && "Not an expansion parameter pack");
1333     return NumExpanded;
1334   }
1335 
1336   /// Returns the type constraint associated with this template parameter (if
1337   /// any).
1338   const TypeConstraint *getTypeConstraint() const {
1339     return TypeConstraintInitialized ? getTrailingObjects<TypeConstraint>() :
1340          nullptr;
1341   }
1342 
1343   void setTypeConstraint(ConceptReference *CR,
1344                          Expr *ImmediatelyDeclaredConstraint);
1345 
1346   /// Determine whether this template parameter has a type-constraint.
1347   bool hasTypeConstraint() const {
1348     return HasTypeConstraint;
1349   }
1350 
1351   /// \brief Get the associated-constraints of this template parameter.
1352   /// This will either be the immediately-introduced constraint or empty.
1353   ///
1354   /// Use this instead of getTypeConstraint for concepts APIs that
1355   /// accept an ArrayRef of constraint expressions.
1356   void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
1357     if (HasTypeConstraint)
1358       AC.push_back(getTypeConstraint()->getImmediatelyDeclaredConstraint());
1359   }
1360 
1361   SourceRange getSourceRange() const override LLVM_READONLY;
1362 
1363   // Implement isa/cast/dyncast/etc.
1364   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1365   static bool classofKind(Kind K) { return K == TemplateTypeParm; }
1366 };
1367 
1368 /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
1369 /// e.g., "Size" in
1370 /// @code
1371 /// template<int Size> class array { };
1372 /// @endcode
1373 class NonTypeTemplateParmDecl final
1374     : public DeclaratorDecl,
1375       protected TemplateParmPosition,
1376       private llvm::TrailingObjects<NonTypeTemplateParmDecl,
1377                                     std::pair<QualType, TypeSourceInfo *>,
1378                                     Expr *> {
1379   friend class ASTDeclReader;
1380   friend TrailingObjects;
1381 
1382   /// The default template argument, if any, and whether or not
1383   /// it was inherited.
1384   using DefArgStorage =
1385       DefaultArgStorage<NonTypeTemplateParmDecl, TemplateArgumentLoc *>;
1386   DefArgStorage DefaultArgument;
1387 
1388   // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
1389   // down here to save memory.
1390 
1391   /// Whether this non-type template parameter is a parameter pack.
1392   bool ParameterPack;
1393 
1394   /// Whether this non-type template parameter is an "expanded"
1395   /// parameter pack, meaning that its type is a pack expansion and we
1396   /// already know the set of types that expansion expands to.
1397   bool ExpandedParameterPack = false;
1398 
1399   /// The number of types in an expanded parameter pack.
1400   unsigned NumExpandedTypes = 0;
1401 
1402   size_t numTrailingObjects(
1403       OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
1404     return NumExpandedTypes;
1405   }
1406 
1407   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1408                           SourceLocation IdLoc, unsigned D, unsigned P,
1409                           const IdentifierInfo *Id, QualType T,
1410                           bool ParameterPack, TypeSourceInfo *TInfo)
1411       : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
1412         TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1413 
1414   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1415                           SourceLocation IdLoc, unsigned D, unsigned P,
1416                           const IdentifierInfo *Id, QualType T,
1417                           TypeSourceInfo *TInfo,
1418                           ArrayRef<QualType> ExpandedTypes,
1419                           ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1420 
1421 public:
1422   static NonTypeTemplateParmDecl *
1423   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1424          SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id,
1425          QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
1426 
1427   static NonTypeTemplateParmDecl *
1428   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1429          SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id,
1430          QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
1431          ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1432 
1433   static NonTypeTemplateParmDecl *
1434   CreateDeserialized(ASTContext &C, GlobalDeclID ID, bool HasTypeConstraint);
1435   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1436                                                      GlobalDeclID ID,
1437                                                      unsigned NumExpandedTypes,
1438                                                      bool HasTypeConstraint);
1439 
1440   using TemplateParmPosition::getDepth;
1441   using TemplateParmPosition::setDepth;
1442   using TemplateParmPosition::getPosition;
1443   using TemplateParmPosition::setPosition;
1444   using TemplateParmPosition::getIndex;
1445 
1446   SourceRange getSourceRange() const override LLVM_READONLY;
1447 
1448   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1449 
1450   /// Determine whether this template parameter has a default
1451   /// argument.
1452   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1453 
1454   /// Retrieve the default argument, if any.
1455   const TemplateArgumentLoc &getDefaultArgument() const {
1456     static const TemplateArgumentLoc NoneLoc;
1457     return DefaultArgument.isSet() ? *DefaultArgument.get() : NoneLoc;
1458   }
1459 
1460   /// Retrieve the location of the default argument, if any.
1461   SourceLocation getDefaultArgumentLoc() const;
1462 
1463   /// Determines whether the default argument was inherited
1464   /// from a previous declaration of this template.
1465   bool defaultArgumentWasInherited() const {
1466     return DefaultArgument.isInherited();
1467   }
1468 
1469   /// Set the default argument for this template parameter, and
1470   /// whether that default argument was inherited from another
1471   /// declaration.
1472   void setDefaultArgument(const ASTContext &C,
1473                           const TemplateArgumentLoc &DefArg);
1474   void setInheritedDefaultArgument(const ASTContext &C,
1475                                    NonTypeTemplateParmDecl *Parm) {
1476     DefaultArgument.setInherited(C, Parm);
1477   }
1478 
1479   /// Removes the default argument of this template parameter.
1480   void removeDefaultArgument() { DefaultArgument.clear(); }
1481 
1482   /// Whether this parameter is a non-type template parameter pack.
1483   ///
1484   /// If the parameter is a parameter pack, the type may be a
1485   /// \c PackExpansionType. In the following example, the \c Dims parameter
1486   /// is a parameter pack (whose type is 'unsigned').
1487   ///
1488   /// \code
1489   /// template<typename T, unsigned ...Dims> struct multi_array;
1490   /// \endcode
1491   bool isParameterPack() const { return ParameterPack; }
1492 
1493   /// Whether this parameter pack is a pack expansion.
1494   ///
1495   /// A non-type template parameter pack is a pack expansion if its type
1496   /// contains an unexpanded parameter pack. In this case, we will have
1497   /// built a PackExpansionType wrapping the type.
1498   bool isPackExpansion() const {
1499     return ParameterPack && getType()->getAs<PackExpansionType>();
1500   }
1501 
1502   /// Whether this parameter is a non-type template parameter pack
1503   /// that has a known list of different types at different positions.
1504   ///
1505   /// A parameter pack is an expanded parameter pack when the original
1506   /// parameter pack's type was itself a pack expansion, and that expansion
1507   /// has already been expanded. For example, given:
1508   ///
1509   /// \code
1510   /// template<typename ...Types>
1511   /// struct X {
1512   ///   template<Types ...Values>
1513   ///   struct Y { /* ... */ };
1514   /// };
1515   /// \endcode
1516   ///
1517   /// The parameter pack \c Values has a \c PackExpansionType as its type,
1518   /// which expands \c Types. When \c Types is supplied with template arguments
1519   /// by instantiating \c X, the instantiation of \c Values becomes an
1520   /// expanded parameter pack. For example, instantiating
1521   /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1522   /// pack with expansion types \c int and \c unsigned int.
1523   ///
1524   /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1525   /// return the expansion types.
1526   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1527 
1528   /// Retrieves the number of expansion types in an expanded parameter
1529   /// pack.
1530   unsigned getNumExpansionTypes() const {
1531     assert(ExpandedParameterPack && "Not an expansion parameter pack");
1532     return NumExpandedTypes;
1533   }
1534 
1535   /// Retrieve a particular expansion type within an expanded parameter
1536   /// pack.
1537   QualType getExpansionType(unsigned I) const {
1538     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1539     auto TypesAndInfos =
1540         getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1541     return TypesAndInfos[I].first;
1542   }
1543 
1544   /// Retrieve a particular expansion type source info within an
1545   /// expanded parameter pack.
1546   TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1547     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1548     auto TypesAndInfos =
1549         getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1550     return TypesAndInfos[I].second;
1551   }
1552 
1553   /// Return the constraint introduced by the placeholder type of this non-type
1554   /// template parameter (if any).
1555   Expr *getPlaceholderTypeConstraint() const {
1556     return hasPlaceholderTypeConstraint() ? *getTrailingObjects<Expr *>() :
1557         nullptr;
1558   }
1559 
1560   void setPlaceholderTypeConstraint(Expr *E) {
1561     *getTrailingObjects<Expr *>() = E;
1562   }
1563 
1564   /// Determine whether this non-type template parameter's type has a
1565   /// placeholder with a type-constraint.
1566   bool hasPlaceholderTypeConstraint() const {
1567     auto *AT = getType()->getContainedAutoType();
1568     return AT && AT->isConstrained();
1569   }
1570 
1571   /// \brief Get the associated-constraints of this template parameter.
1572   /// This will either be a vector of size 1 containing the immediately-declared
1573   /// constraint introduced by the placeholder type, or an empty vector.
1574   ///
1575   /// Use this instead of getPlaceholderImmediatelyDeclaredConstraint for
1576   /// concepts APIs that accept an ArrayRef of constraint expressions.
1577   void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
1578     if (Expr *E = getPlaceholderTypeConstraint())
1579       AC.push_back(E);
1580   }
1581 
1582   // Implement isa/cast/dyncast/etc.
1583   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1584   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1585 };
1586 
1587 /// TemplateTemplateParmDecl - Declares a template template parameter,
1588 /// e.g., "T" in
1589 /// @code
1590 /// template <template <typename> class T> class container { };
1591 /// @endcode
1592 /// A template template parameter is a TemplateDecl because it defines the
1593 /// name of a template and the template parameters allowable for substitution.
1594 class TemplateTemplateParmDecl final
1595     : public TemplateDecl,
1596       protected TemplateParmPosition,
1597       private llvm::TrailingObjects<TemplateTemplateParmDecl,
1598                                     TemplateParameterList *> {
1599   /// The default template argument, if any.
1600   using DefArgStorage =
1601       DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>;
1602   DefArgStorage DefaultArgument;
1603 
1604   /// Whether this template template parameter was declaration with
1605   /// the 'typename' keyword.
1606   ///
1607   /// If false, it was declared with the 'class' keyword.
1608   LLVM_PREFERRED_TYPE(bool)
1609   unsigned Typename : 1;
1610 
1611   /// Whether this parameter is a parameter pack.
1612   LLVM_PREFERRED_TYPE(bool)
1613   unsigned ParameterPack : 1;
1614 
1615   /// Whether this template template parameter is an "expanded"
1616   /// parameter pack, meaning that it is a pack expansion and we
1617   /// already know the set of template parameters that expansion expands to.
1618   LLVM_PREFERRED_TYPE(bool)
1619   unsigned ExpandedParameterPack : 1;
1620 
1621   /// The number of parameters in an expanded parameter pack.
1622   unsigned NumExpandedParams = 0;
1623 
1624   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L, unsigned D,
1625                            unsigned P, bool ParameterPack, IdentifierInfo *Id,
1626                            bool Typename, TemplateParameterList *Params)
1627       : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1628         TemplateParmPosition(D, P), Typename(Typename),
1629         ParameterPack(ParameterPack), ExpandedParameterPack(false) {}
1630 
1631   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L, unsigned D,
1632                            unsigned P, IdentifierInfo *Id, bool Typename,
1633                            TemplateParameterList *Params,
1634                            ArrayRef<TemplateParameterList *> Expansions);
1635 
1636   void anchor() override;
1637 
1638 public:
1639   friend class ASTDeclReader;
1640   friend class ASTDeclWriter;
1641   friend TrailingObjects;
1642 
1643   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1644                                           SourceLocation L, unsigned D,
1645                                           unsigned P, bool ParameterPack,
1646                                           IdentifierInfo *Id, bool Typename,
1647                                           TemplateParameterList *Params);
1648   static TemplateTemplateParmDecl *
1649   Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D,
1650          unsigned P, IdentifierInfo *Id, bool Typename,
1651          TemplateParameterList *Params,
1652          ArrayRef<TemplateParameterList *> Expansions);
1653 
1654   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1655                                                       GlobalDeclID ID);
1656   static TemplateTemplateParmDecl *
1657   CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NumExpansions);
1658 
1659   using TemplateParmPosition::getDepth;
1660   using TemplateParmPosition::setDepth;
1661   using TemplateParmPosition::getPosition;
1662   using TemplateParmPosition::setPosition;
1663   using TemplateParmPosition::getIndex;
1664 
1665   /// Whether this template template parameter was declared with
1666   /// the 'typename' keyword.
1667   bool wasDeclaredWithTypename() const { return Typename; }
1668 
1669   /// Set whether this template template parameter was declared with
1670   /// the 'typename' or 'class' keyword.
1671   void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1672 
1673   /// Whether this template template parameter is a template
1674   /// parameter pack.
1675   ///
1676   /// \code
1677   /// template<template <class T> ...MetaFunctions> struct Apply;
1678   /// \endcode
1679   bool isParameterPack() const { return ParameterPack; }
1680 
1681   /// Whether this parameter pack is a pack expansion.
1682   ///
1683   /// A template template parameter pack is a pack expansion if its template
1684   /// parameter list contains an unexpanded parameter pack.
1685   bool isPackExpansion() const {
1686     return ParameterPack &&
1687            getTemplateParameters()->containsUnexpandedParameterPack();
1688   }
1689 
1690   /// Whether this parameter is a template template parameter pack that
1691   /// has a known list of different template parameter lists at different
1692   /// positions.
1693   ///
1694   /// A parameter pack is an expanded parameter pack when the original parameter
1695   /// pack's template parameter list was itself a pack expansion, and that
1696   /// expansion has already been expanded. For exampe, given:
1697   ///
1698   /// \code
1699   /// template<typename...Types> struct Outer {
1700   ///   template<template<Types> class...Templates> struct Inner;
1701   /// };
1702   /// \endcode
1703   ///
1704   /// The parameter pack \c Templates is a pack expansion, which expands the
1705   /// pack \c Types. When \c Types is supplied with template arguments by
1706   /// instantiating \c Outer, the instantiation of \c Templates is an expanded
1707   /// parameter pack.
1708   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1709 
1710   /// Retrieves the number of expansion template parameters in
1711   /// an expanded parameter pack.
1712   unsigned getNumExpansionTemplateParameters() const {
1713     assert(ExpandedParameterPack && "Not an expansion parameter pack");
1714     return NumExpandedParams;
1715   }
1716 
1717   /// Retrieve a particular expansion type within an expanded parameter
1718   /// pack.
1719   TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
1720     assert(I < NumExpandedParams && "Out-of-range expansion type index");
1721     return getTrailingObjects<TemplateParameterList *>()[I];
1722   }
1723 
1724   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1725 
1726   /// Determine whether this template parameter has a default
1727   /// argument.
1728   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1729 
1730   /// Retrieve the default argument, if any.
1731   const TemplateArgumentLoc &getDefaultArgument() const {
1732     static const TemplateArgumentLoc NoneLoc;
1733     return DefaultArgument.isSet() ? *DefaultArgument.get() : NoneLoc;
1734   }
1735 
1736   /// Retrieve the location of the default argument, if any.
1737   SourceLocation getDefaultArgumentLoc() const;
1738 
1739   /// Determines whether the default argument was inherited
1740   /// from a previous declaration of this template.
1741   bool defaultArgumentWasInherited() const {
1742     return DefaultArgument.isInherited();
1743   }
1744 
1745   /// Set the default argument for this template parameter, and
1746   /// whether that default argument was inherited from another
1747   /// declaration.
1748   void setDefaultArgument(const ASTContext &C,
1749                           const TemplateArgumentLoc &DefArg);
1750   void setInheritedDefaultArgument(const ASTContext &C,
1751                                    TemplateTemplateParmDecl *Prev) {
1752     DefaultArgument.setInherited(C, Prev);
1753   }
1754 
1755   /// Removes the default argument of this template parameter.
1756   void removeDefaultArgument() { DefaultArgument.clear(); }
1757 
1758   SourceRange getSourceRange() const override LLVM_READONLY {
1759     SourceLocation End = getLocation();
1760     if (hasDefaultArgument() && !defaultArgumentWasInherited())
1761       End = getDefaultArgument().getSourceRange().getEnd();
1762     return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1763   }
1764 
1765   // Implement isa/cast/dyncast/etc.
1766   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1767   static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1768 };
1769 
1770 /// Represents the builtin template declaration which is used to
1771 /// implement __make_integer_seq and other builtin templates.  It serves
1772 /// no real purpose beyond existing as a place to hold template parameters.
1773 class BuiltinTemplateDecl : public TemplateDecl {
1774   BuiltinTemplateKind BTK;
1775 
1776   BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
1777                       DeclarationName Name, BuiltinTemplateKind BTK);
1778 
1779   void anchor() override;
1780 
1781 public:
1782   // Implement isa/cast/dyncast support
1783   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1784   static bool classofKind(Kind K) { return K == BuiltinTemplate; }
1785 
1786   static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
1787                                      DeclarationName Name,
1788                                      BuiltinTemplateKind BTK) {
1789     return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
1790   }
1791 
1792   SourceRange getSourceRange() const override LLVM_READONLY {
1793     return {};
1794   }
1795 
1796   BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
1797 };
1798 
1799 /// Provides information about an explicit instantiation of a variable or class
1800 /// template.
1801 struct ExplicitInstantiationInfo {
1802   /// The template arguments as written..
1803   const ASTTemplateArgumentListInfo *TemplateArgsAsWritten = nullptr;
1804 
1805   /// The location of the extern keyword.
1806   SourceLocation ExternKeywordLoc;
1807 
1808   /// The location of the template keyword.
1809   SourceLocation TemplateKeywordLoc;
1810 
1811   ExplicitInstantiationInfo() = default;
1812 };
1813 
1814 using SpecializationOrInstantiationInfo =
1815     llvm::PointerUnion<const ASTTemplateArgumentListInfo *,
1816                        ExplicitInstantiationInfo *>;
1817 
1818 /// Represents a class template specialization, which refers to
1819 /// a class template with a given set of template arguments.
1820 ///
1821 /// Class template specializations represent both explicit
1822 /// specialization of class templates, as in the example below, and
1823 /// implicit instantiations of class templates.
1824 ///
1825 /// \code
1826 /// template<typename T> class array;
1827 ///
1828 /// template<>
1829 /// class array<bool> { }; // class template specialization array<bool>
1830 /// \endcode
1831 class ClassTemplateSpecializationDecl : public CXXRecordDecl,
1832                                         public llvm::FoldingSetNode {
1833   /// Structure that stores information about a class template
1834   /// specialization that was instantiated from a class template partial
1835   /// specialization.
1836   struct SpecializedPartialSpecialization {
1837     /// The class template partial specialization from which this
1838     /// class template specialization was instantiated.
1839     ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1840 
1841     /// The template argument list deduced for the class template
1842     /// partial specialization itself.
1843     const TemplateArgumentList *TemplateArgs;
1844   };
1845 
1846   /// The template that this specialization specializes
1847   llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1848     SpecializedTemplate;
1849 
1850   /// Further info for explicit template specialization/instantiation.
1851   /// Does not apply to implicit specializations.
1852   SpecializationOrInstantiationInfo ExplicitInfo = nullptr;
1853 
1854   /// The template arguments used to describe this specialization.
1855   const TemplateArgumentList *TemplateArgs;
1856 
1857   /// The point where this template was instantiated (if any)
1858   SourceLocation PointOfInstantiation;
1859 
1860   /// The kind of specialization this declaration refers to.
1861   LLVM_PREFERRED_TYPE(TemplateSpecializationKind)
1862   unsigned SpecializationKind : 3;
1863 
1864   /// Indicate that we have matched a parameter pack with a non pack
1865   /// argument, when the opposite match is also allowed (strict pack match).
1866   /// This needs to be cached as deduction is performed during declaration,
1867   /// and we need the information to be preserved so that it is consistent
1868   /// during instantiation.
1869   bool MatchedPackOnParmToNonPackOnArg : 1;
1870 
1871 protected:
1872   ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1873                                   DeclContext *DC, SourceLocation StartLoc,
1874                                   SourceLocation IdLoc,
1875                                   ClassTemplateDecl *SpecializedTemplate,
1876                                   ArrayRef<TemplateArgument> Args,
1877                                   bool MatchedPackOnParmToNonPackOnArg,
1878                                   ClassTemplateSpecializationDecl *PrevDecl);
1879 
1880   ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
1881 
1882 public:
1883   friend class ASTDeclReader;
1884   friend class ASTDeclWriter;
1885 
1886   static ClassTemplateSpecializationDecl *
1887   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1888          SourceLocation StartLoc, SourceLocation IdLoc,
1889          ClassTemplateDecl *SpecializedTemplate,
1890          ArrayRef<TemplateArgument> Args, bool MatchedPackOnParmToNonPackOnArg,
1891          ClassTemplateSpecializationDecl *PrevDecl);
1892   static ClassTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
1893                                                              GlobalDeclID ID);
1894 
1895   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1896                             bool Qualified) const override;
1897 
1898   // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
1899   // different "most recent" declaration from this function for the same
1900   // declaration, because we don't override getMostRecentDeclImpl(). But
1901   // it's not clear that we should override that, because the most recent
1902   // declaration as a CXXRecordDecl sometimes is the injected-class-name.
1903   ClassTemplateSpecializationDecl *getMostRecentDecl() {
1904     return cast<ClassTemplateSpecializationDecl>(
1905         getMostRecentNonInjectedDecl());
1906   }
1907 
1908   /// Retrieve the template that this specialization specializes.
1909   ClassTemplateDecl *getSpecializedTemplate() const;
1910 
1911   /// Retrieve the template arguments of the class template
1912   /// specialization.
1913   const TemplateArgumentList &getTemplateArgs() const {
1914     return *TemplateArgs;
1915   }
1916 
1917   void setTemplateArgs(TemplateArgumentList *Args) {
1918     TemplateArgs = Args;
1919   }
1920 
1921   /// Determine the kind of specialization that this
1922   /// declaration represents.
1923   TemplateSpecializationKind getSpecializationKind() const {
1924     return static_cast<TemplateSpecializationKind>(SpecializationKind);
1925   }
1926 
1927   bool isExplicitSpecialization() const {
1928     return getSpecializationKind() == TSK_ExplicitSpecialization;
1929   }
1930 
1931   /// Is this an explicit specialization at class scope (within the class that
1932   /// owns the primary template)? For example:
1933   ///
1934   /// \code
1935   /// template<typename T> struct Outer {
1936   ///   template<typename U> struct Inner;
1937   ///   template<> struct Inner; // class-scope explicit specialization
1938   /// };
1939   /// \endcode
1940   bool isClassScopeExplicitSpecialization() const {
1941     return isExplicitSpecialization() &&
1942            isa<CXXRecordDecl>(getLexicalDeclContext());
1943   }
1944 
1945   /// True if this declaration is an explicit specialization,
1946   /// explicit instantiation declaration, or explicit instantiation
1947   /// definition.
1948   bool isExplicitInstantiationOrSpecialization() const {
1949     return isTemplateExplicitInstantiationOrSpecialization(
1950         getTemplateSpecializationKind());
1951   }
1952 
1953   void setSpecializedTemplate(ClassTemplateDecl *Specialized) {
1954     SpecializedTemplate = Specialized;
1955   }
1956 
1957   void setSpecializationKind(TemplateSpecializationKind TSK) {
1958     SpecializationKind = TSK;
1959   }
1960 
1961   bool hasMatchedPackOnParmToNonPackOnArg() const {
1962     return MatchedPackOnParmToNonPackOnArg;
1963   }
1964 
1965   /// Get the point of instantiation (if any), or null if none.
1966   SourceLocation getPointOfInstantiation() const {
1967     return PointOfInstantiation;
1968   }
1969 
1970   void setPointOfInstantiation(SourceLocation Loc) {
1971     assert(Loc.isValid() && "point of instantiation must be valid!");
1972     PointOfInstantiation = Loc;
1973   }
1974 
1975   /// If this class template specialization is an instantiation of
1976   /// a template (rather than an explicit specialization), return the
1977   /// class template or class template partial specialization from which it
1978   /// was instantiated.
1979   llvm::PointerUnion<ClassTemplateDecl *,
1980                      ClassTemplatePartialSpecializationDecl *>
1981   getInstantiatedFrom() const {
1982     if (!isTemplateInstantiation(getSpecializationKind()))
1983       return llvm::PointerUnion<ClassTemplateDecl *,
1984                                 ClassTemplatePartialSpecializationDecl *>();
1985 
1986     return getSpecializedTemplateOrPartial();
1987   }
1988 
1989   /// Retrieve the class template or class template partial
1990   /// specialization which was specialized by this.
1991   llvm::PointerUnion<ClassTemplateDecl *,
1992                      ClassTemplatePartialSpecializationDecl *>
1993   getSpecializedTemplateOrPartial() const {
1994     if (const auto *PartialSpec =
1995             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
1996       return PartialSpec->PartialSpecialization;
1997 
1998     return cast<ClassTemplateDecl *>(SpecializedTemplate);
1999   }
2000 
2001   /// Retrieve the set of template arguments that should be used
2002   /// to instantiate members of the class template or class template partial
2003   /// specialization from which this class template specialization was
2004   /// instantiated.
2005   ///
2006   /// \returns For a class template specialization instantiated from the primary
2007   /// template, this function will return the same template arguments as
2008   /// getTemplateArgs(). For a class template specialization instantiated from
2009   /// a class template partial specialization, this function will return the
2010   /// deduced template arguments for the class template partial specialization
2011   /// itself.
2012   const TemplateArgumentList &getTemplateInstantiationArgs() const {
2013     if (const auto *PartialSpec =
2014             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2015       return *PartialSpec->TemplateArgs;
2016 
2017     return getTemplateArgs();
2018   }
2019 
2020   /// Note that this class template specialization is actually an
2021   /// instantiation of the given class template partial specialization whose
2022   /// template arguments have been deduced.
2023   void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
2024                           const TemplateArgumentList *TemplateArgs) {
2025     assert(!isa<SpecializedPartialSpecialization *>(SpecializedTemplate) &&
2026            "Already set to a class template partial specialization!");
2027     auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
2028     PS->PartialSpecialization = PartialSpec;
2029     PS->TemplateArgs = TemplateArgs;
2030     SpecializedTemplate = PS;
2031   }
2032 
2033   /// Note that this class template specialization is an instantiation
2034   /// of the given class template.
2035   void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
2036     assert(!isa<SpecializedPartialSpecialization *>(SpecializedTemplate) &&
2037            "Previously set to a class template partial specialization!");
2038     SpecializedTemplate = TemplDecl;
2039   }
2040 
2041   /// Retrieve the template argument list as written in the sources,
2042   /// if any.
2043   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2044     if (auto *Info =
2045             dyn_cast_if_present<ExplicitInstantiationInfo *>(ExplicitInfo))
2046       return Info->TemplateArgsAsWritten;
2047     return cast<const ASTTemplateArgumentListInfo *>(ExplicitInfo);
2048   }
2049 
2050   /// Set the template argument list as written in the sources.
2051   void
2052   setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten) {
2053     if (auto *Info =
2054             dyn_cast_if_present<ExplicitInstantiationInfo *>(ExplicitInfo))
2055       Info->TemplateArgsAsWritten = ArgsWritten;
2056     else
2057       ExplicitInfo = ArgsWritten;
2058   }
2059 
2060   /// Set the template argument list as written in the sources.
2061   void setTemplateArgsAsWritten(const TemplateArgumentListInfo &ArgsInfo) {
2062     setTemplateArgsAsWritten(
2063         ASTTemplateArgumentListInfo::Create(getASTContext(), ArgsInfo));
2064   }
2065 
2066   /// Gets the location of the extern keyword, if present.
2067   SourceLocation getExternKeywordLoc() const {
2068     if (auto *Info =
2069             dyn_cast_if_present<ExplicitInstantiationInfo *>(ExplicitInfo))
2070       return Info->ExternKeywordLoc;
2071     return SourceLocation();
2072   }
2073 
2074   /// Sets the location of the extern keyword.
2075   void setExternKeywordLoc(SourceLocation Loc);
2076 
2077   /// Gets the location of the template keyword, if present.
2078   SourceLocation getTemplateKeywordLoc() const {
2079     if (auto *Info =
2080             dyn_cast_if_present<ExplicitInstantiationInfo *>(ExplicitInfo))
2081       return Info->TemplateKeywordLoc;
2082     return SourceLocation();
2083   }
2084 
2085   /// Sets the location of the template keyword.
2086   void setTemplateKeywordLoc(SourceLocation Loc);
2087 
2088   SourceRange getSourceRange() const override LLVM_READONLY;
2089 
2090   void Profile(llvm::FoldingSetNodeID &ID) const {
2091     Profile(ID, TemplateArgs->asArray(), getASTContext());
2092   }
2093 
2094   static void
2095   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
2096           const ASTContext &Context) {
2097     ID.AddInteger(TemplateArgs.size());
2098     for (const TemplateArgument &TemplateArg : TemplateArgs)
2099       TemplateArg.Profile(ID, Context);
2100   }
2101 
2102   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2103 
2104   static bool classofKind(Kind K) {
2105     return K >= firstClassTemplateSpecialization &&
2106            K <= lastClassTemplateSpecialization;
2107   }
2108 };
2109 
2110 class ClassTemplatePartialSpecializationDecl
2111   : public ClassTemplateSpecializationDecl {
2112   /// The list of template parameters
2113   TemplateParameterList *TemplateParams = nullptr;
2114 
2115   /// The class template partial specialization from which this
2116   /// class template partial specialization was instantiated.
2117   ///
2118   /// The boolean value will be true to indicate that this class template
2119   /// partial specialization was specialized at this level.
2120   llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
2121       InstantiatedFromMember;
2122 
2123   ClassTemplatePartialSpecializationDecl(
2124       ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc,
2125       SourceLocation IdLoc, TemplateParameterList *Params,
2126       ClassTemplateDecl *SpecializedTemplate, ArrayRef<TemplateArgument> Args,
2127       ClassTemplatePartialSpecializationDecl *PrevDecl);
2128 
2129   ClassTemplatePartialSpecializationDecl(ASTContext &C)
2130     : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
2131       InstantiatedFromMember(nullptr, false) {}
2132 
2133   void anchor() override;
2134 
2135 public:
2136   friend class ASTDeclReader;
2137   friend class ASTDeclWriter;
2138 
2139   static ClassTemplatePartialSpecializationDecl *
2140   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
2141          SourceLocation StartLoc, SourceLocation IdLoc,
2142          TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate,
2143          ArrayRef<TemplateArgument> Args, QualType CanonInjectedType,
2144          ClassTemplatePartialSpecializationDecl *PrevDecl);
2145 
2146   static ClassTemplatePartialSpecializationDecl *
2147   CreateDeserialized(ASTContext &C, GlobalDeclID ID);
2148 
2149   ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
2150     return cast<ClassTemplatePartialSpecializationDecl>(
2151              static_cast<ClassTemplateSpecializationDecl *>(
2152                this)->getMostRecentDecl());
2153   }
2154 
2155   /// Get the list of template parameters
2156   TemplateParameterList *getTemplateParameters() const {
2157     return TemplateParams;
2158   }
2159 
2160   /// Get the template argument list of the template parameter list.
2161   ArrayRef<TemplateArgument>
2162   getInjectedTemplateArgs(const ASTContext &Context) const {
2163     return getTemplateParameters()->getInjectedTemplateArgs(Context);
2164   }
2165 
2166   /// \brief All associated constraints of this partial specialization,
2167   /// including the requires clause and any constraints derived from
2168   /// constrained-parameters.
2169   ///
2170   /// The constraints in the resulting list are to be treated as if in a
2171   /// conjunction ("and").
2172   void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
2173     TemplateParams->getAssociatedConstraints(AC);
2174   }
2175 
2176   bool hasAssociatedConstraints() const {
2177     return TemplateParams->hasAssociatedConstraints();
2178   }
2179 
2180   /// Retrieve the member class template partial specialization from
2181   /// which this particular class template partial specialization was
2182   /// instantiated.
2183   ///
2184   /// \code
2185   /// template<typename T>
2186   /// struct Outer {
2187   ///   template<typename U> struct Inner;
2188   ///   template<typename U> struct Inner<U*> { }; // #1
2189   /// };
2190   ///
2191   /// Outer<float>::Inner<int*> ii;
2192   /// \endcode
2193   ///
2194   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
2195   /// end up instantiating the partial specialization
2196   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
2197   /// template partial specialization \c Outer<T>::Inner<U*>. Given
2198   /// \c Outer<float>::Inner<U*>, this function would return
2199   /// \c Outer<T>::Inner<U*>.
2200   ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2201     const auto *First =
2202         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2203     return First->InstantiatedFromMember.getPointer();
2204   }
2205   ClassTemplatePartialSpecializationDecl *
2206   getInstantiatedFromMemberTemplate() const {
2207     return getInstantiatedFromMember();
2208   }
2209 
2210   void setInstantiatedFromMember(
2211                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
2212     auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2213     First->InstantiatedFromMember.setPointer(PartialSpec);
2214   }
2215 
2216   /// Determines whether this class template partial specialization
2217   /// template was a specialization of a member partial specialization.
2218   ///
2219   /// In the following example, the member template partial specialization
2220   /// \c X<int>::Inner<T*> is a member specialization.
2221   ///
2222   /// \code
2223   /// template<typename T>
2224   /// struct X {
2225   ///   template<typename U> struct Inner;
2226   ///   template<typename U> struct Inner<U*>;
2227   /// };
2228   ///
2229   /// template<> template<typename T>
2230   /// struct X<int>::Inner<T*> { /* ... */ };
2231   /// \endcode
2232   bool isMemberSpecialization() const {
2233     const auto *First =
2234         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2235     return First->InstantiatedFromMember.getInt();
2236   }
2237 
2238   /// Note that this member template is a specialization.
2239   void setMemberSpecialization() {
2240     auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2241     assert(First->InstantiatedFromMember.getPointer() &&
2242            "Only member templates can be member template specializations");
2243     return First->InstantiatedFromMember.setInt(true);
2244   }
2245 
2246   /// Retrieves the injected specialization type for this partial
2247   /// specialization.  This is not the same as the type-decl-type for
2248   /// this partial specialization, which is an InjectedClassNameType.
2249   QualType getInjectedSpecializationType() const {
2250     assert(getTypeForDecl() && "partial specialization has no type set!");
2251     return cast<InjectedClassNameType>(getTypeForDecl())
2252              ->getInjectedSpecializationType();
2253   }
2254 
2255   SourceRange getSourceRange() const override LLVM_READONLY;
2256 
2257   void Profile(llvm::FoldingSetNodeID &ID) const {
2258     Profile(ID, getTemplateArgs().asArray(), getTemplateParameters(),
2259             getASTContext());
2260   }
2261 
2262   static void
2263   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
2264           TemplateParameterList *TPL, const ASTContext &Context);
2265 
2266   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2267 
2268   static bool classofKind(Kind K) {
2269     return K == ClassTemplatePartialSpecialization;
2270   }
2271 };
2272 
2273 /// Declaration of a class template.
2274 class ClassTemplateDecl : public RedeclarableTemplateDecl {
2275 protected:
2276   /// Data that is common to all of the declarations of a given
2277   /// class template.
2278   struct Common : CommonBase {
2279     /// The class template specializations for this class
2280     /// template, including explicit specializations and instantiations.
2281     llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
2282 
2283     /// The class template partial specializations for this class
2284     /// template.
2285     llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
2286       PartialSpecializations;
2287 
2288     /// The injected-class-name type for this class template.
2289     QualType InjectedClassNameType;
2290 
2291     Common() = default;
2292   };
2293 
2294   /// Retrieve the set of specializations of this class template.
2295   llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
2296   getSpecializations() const;
2297 
2298   /// Retrieve the set of partial specializations of this class
2299   /// template.
2300   llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
2301   getPartialSpecializations() const;
2302 
2303   ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2304                     DeclarationName Name, TemplateParameterList *Params,
2305                     NamedDecl *Decl)
2306       : RedeclarableTemplateDecl(ClassTemplate, C, DC, L, Name, Params, Decl) {}
2307 
2308   CommonBase *newCommon(ASTContext &C) const override;
2309 
2310   Common *getCommonPtr() const {
2311     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2312   }
2313 
2314   void setCommonPtr(Common *C) { RedeclarableTemplateDecl::Common = C; }
2315 
2316 public:
2317 
2318   friend class ASTDeclReader;
2319   friend class ASTDeclWriter;
2320   friend class TemplateDeclInstantiator;
2321 
2322   /// Load any lazily-loaded specializations from the external source.
2323   void LoadLazySpecializations(bool OnlyPartial = false) const;
2324 
2325   /// Get the underlying class declarations of the template.
2326   CXXRecordDecl *getTemplatedDecl() const {
2327     return static_cast<CXXRecordDecl *>(TemplatedDecl);
2328   }
2329 
2330   /// Returns whether this template declaration defines the primary
2331   /// class pattern.
2332   bool isThisDeclarationADefinition() const {
2333     return getTemplatedDecl()->isThisDeclarationADefinition();
2334   }
2335 
2336   /// \brief Create a class template node.
2337   static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2338                                    SourceLocation L,
2339                                    DeclarationName Name,
2340                                    TemplateParameterList *Params,
2341                                    NamedDecl *Decl);
2342 
2343   /// Create an empty class template node.
2344   static ClassTemplateDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
2345 
2346   /// Return the specialization with the provided arguments if it exists,
2347   /// otherwise return the insertion point.
2348   ClassTemplateSpecializationDecl *
2349   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2350 
2351   /// Insert the specified specialization knowing that it is not already
2352   /// in. InsertPos must be obtained from findSpecialization.
2353   void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
2354 
2355   ClassTemplateDecl *getCanonicalDecl() override {
2356     return cast<ClassTemplateDecl>(
2357              RedeclarableTemplateDecl::getCanonicalDecl());
2358   }
2359   const ClassTemplateDecl *getCanonicalDecl() const {
2360     return cast<ClassTemplateDecl>(
2361              RedeclarableTemplateDecl::getCanonicalDecl());
2362   }
2363 
2364   /// Retrieve the previous declaration of this class template, or
2365   /// nullptr if no such declaration exists.
2366   ClassTemplateDecl *getPreviousDecl() {
2367     return cast_or_null<ClassTemplateDecl>(
2368              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2369   }
2370   const ClassTemplateDecl *getPreviousDecl() const {
2371     return cast_or_null<ClassTemplateDecl>(
2372              static_cast<const RedeclarableTemplateDecl *>(
2373                this)->getPreviousDecl());
2374   }
2375 
2376   ClassTemplateDecl *getMostRecentDecl() {
2377     return cast<ClassTemplateDecl>(
2378         static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2379   }
2380   const ClassTemplateDecl *getMostRecentDecl() const {
2381     return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
2382   }
2383 
2384   ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
2385     return cast_or_null<ClassTemplateDecl>(
2386              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2387   }
2388 
2389   /// Return the partial specialization with the provided arguments if it
2390   /// exists, otherwise return the insertion point.
2391   ClassTemplatePartialSpecializationDecl *
2392   findPartialSpecialization(ArrayRef<TemplateArgument> Args,
2393                             TemplateParameterList *TPL, void *&InsertPos);
2394 
2395   /// Insert the specified partial specialization knowing that it is not
2396   /// already in. InsertPos must be obtained from findPartialSpecialization.
2397   void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
2398                                 void *InsertPos);
2399 
2400   /// Retrieve the partial specializations as an ordered list.
2401   void getPartialSpecializations(
2402       SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS) const;
2403 
2404   /// Find a class template partial specialization with the given
2405   /// type T.
2406   ///
2407   /// \param T a dependent type that names a specialization of this class
2408   /// template.
2409   ///
2410   /// \returns the class template partial specialization that exactly matches
2411   /// the type \p T, or nullptr if no such partial specialization exists.
2412   ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
2413 
2414   /// Find a class template partial specialization which was instantiated
2415   /// from the given member partial specialization.
2416   ///
2417   /// \param D a member class template partial specialization.
2418   ///
2419   /// \returns the class template partial specialization which was instantiated
2420   /// from the given member partial specialization, or nullptr if no such
2421   /// partial specialization exists.
2422   ClassTemplatePartialSpecializationDecl *
2423   findPartialSpecInstantiatedFromMember(
2424                                      ClassTemplatePartialSpecializationDecl *D);
2425 
2426   /// Retrieve the template specialization type of the
2427   /// injected-class-name for this class template.
2428   ///
2429   /// The injected-class-name for a class template \c X is \c
2430   /// X<template-args>, where \c template-args is formed from the
2431   /// template arguments that correspond to the template parameters of
2432   /// \c X. For example:
2433   ///
2434   /// \code
2435   /// template<typename T, int N>
2436   /// struct array {
2437   ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
2438   /// };
2439   /// \endcode
2440   QualType getInjectedClassNameSpecialization();
2441 
2442   using spec_iterator = SpecIterator<ClassTemplateSpecializationDecl>;
2443   using spec_range = llvm::iterator_range<spec_iterator>;
2444 
2445   spec_range specializations() const {
2446     return spec_range(spec_begin(), spec_end());
2447   }
2448 
2449   spec_iterator spec_begin() const {
2450     return makeSpecIterator(getSpecializations(), false);
2451   }
2452 
2453   spec_iterator spec_end() const {
2454     return makeSpecIterator(getSpecializations(), true);
2455   }
2456 
2457   // Implement isa/cast/dyncast support
2458   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2459   static bool classofKind(Kind K) { return K == ClassTemplate; }
2460 };
2461 
2462 /// Declaration of a friend template.
2463 ///
2464 /// For example:
2465 /// \code
2466 /// template \<typename T> class A {
2467 ///   friend class MyVector<T>; // not a friend template
2468 ///   template \<typename U> friend class B; // not a friend template
2469 ///   template \<typename U> friend class Foo<T>::Nested; // friend template
2470 /// };
2471 /// \endcode
2472 ///
2473 /// \note This class is not currently in use.  All of the above
2474 /// will yield a FriendDecl, not a FriendTemplateDecl.
2475 class FriendTemplateDecl : public Decl {
2476   virtual void anchor();
2477 
2478 public:
2479   using FriendUnion = llvm::PointerUnion<NamedDecl *,TypeSourceInfo *>;
2480 
2481 private:
2482   // The number of template parameters;  always non-zero.
2483   unsigned NumParams = 0;
2484 
2485   // The parameter list.
2486   TemplateParameterList **Params = nullptr;
2487 
2488   // The declaration that's a friend of this class.
2489   FriendUnion Friend;
2490 
2491   // Location of the 'friend' specifier.
2492   SourceLocation FriendLoc;
2493 
2494   FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
2495                      TemplateParameterList **Params, unsigned NumParams,
2496                      FriendUnion Friend, SourceLocation FriendLoc)
2497       : Decl(Decl::FriendTemplate, DC, Loc), NumParams(NumParams),
2498         Params(Params), Friend(Friend), FriendLoc(FriendLoc) {}
2499 
2500   FriendTemplateDecl(EmptyShell Empty) : Decl(Decl::FriendTemplate, Empty) {}
2501 
2502 public:
2503   friend class ASTDeclReader;
2504 
2505   static FriendTemplateDecl *
2506   Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
2507          MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
2508          SourceLocation FriendLoc);
2509 
2510   static FriendTemplateDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
2511 
2512   /// If this friend declaration names a templated type (or
2513   /// a dependent member type of a templated type), return that
2514   /// type;  otherwise return null.
2515   TypeSourceInfo *getFriendType() const {
2516     return Friend.dyn_cast<TypeSourceInfo*>();
2517   }
2518 
2519   /// If this friend declaration names a templated function (or
2520   /// a member function of a templated type), return that type;
2521   /// otherwise return null.
2522   NamedDecl *getFriendDecl() const {
2523     return Friend.dyn_cast<NamedDecl*>();
2524   }
2525 
2526   /// Retrieves the location of the 'friend' keyword.
2527   SourceLocation getFriendLoc() const {
2528     return FriendLoc;
2529   }
2530 
2531   TemplateParameterList *getTemplateParameterList(unsigned i) const {
2532     assert(i <= NumParams);
2533     return Params[i];
2534   }
2535 
2536   unsigned getNumTemplateParameters() const {
2537     return NumParams;
2538   }
2539 
2540   // Implement isa/cast/dyncast/etc.
2541   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2542   static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
2543 };
2544 
2545 /// Declaration of an alias template.
2546 ///
2547 /// For example:
2548 /// \code
2549 /// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
2550 /// \endcode
2551 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
2552 protected:
2553   using Common = CommonBase;
2554 
2555   TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2556                         DeclarationName Name, TemplateParameterList *Params,
2557                         NamedDecl *Decl)
2558       : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
2559                                  Decl) {}
2560 
2561   CommonBase *newCommon(ASTContext &C) const override;
2562 
2563   Common *getCommonPtr() {
2564     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2565   }
2566 
2567 public:
2568   friend class ASTDeclReader;
2569   friend class ASTDeclWriter;
2570 
2571   /// Get the underlying function declaration of the template.
2572   TypeAliasDecl *getTemplatedDecl() const {
2573     return static_cast<TypeAliasDecl *>(TemplatedDecl);
2574   }
2575 
2576 
2577   TypeAliasTemplateDecl *getCanonicalDecl() override {
2578     return cast<TypeAliasTemplateDecl>(
2579              RedeclarableTemplateDecl::getCanonicalDecl());
2580   }
2581   const TypeAliasTemplateDecl *getCanonicalDecl() const {
2582     return cast<TypeAliasTemplateDecl>(
2583              RedeclarableTemplateDecl::getCanonicalDecl());
2584   }
2585 
2586   /// Retrieve the previous declaration of this function template, or
2587   /// nullptr if no such declaration exists.
2588   TypeAliasTemplateDecl *getPreviousDecl() {
2589     return cast_or_null<TypeAliasTemplateDecl>(
2590              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2591   }
2592   const TypeAliasTemplateDecl *getPreviousDecl() const {
2593     return cast_or_null<TypeAliasTemplateDecl>(
2594              static_cast<const RedeclarableTemplateDecl *>(
2595                this)->getPreviousDecl());
2596   }
2597 
2598   TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
2599     return cast_or_null<TypeAliasTemplateDecl>(
2600              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2601   }
2602 
2603   /// Create a function template node.
2604   static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2605                                        SourceLocation L,
2606                                        DeclarationName Name,
2607                                        TemplateParameterList *Params,
2608                                        NamedDecl *Decl);
2609 
2610   /// Create an empty alias template node.
2611   static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C,
2612                                                    GlobalDeclID ID);
2613 
2614   // Implement isa/cast/dyncast support
2615   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2616   static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2617 };
2618 
2619 /// Represents a variable template specialization, which refers to
2620 /// a variable template with a given set of template arguments.
2621 ///
2622 /// Variable template specializations represent both explicit
2623 /// specializations of variable templates, as in the example below, and
2624 /// implicit instantiations of variable templates.
2625 ///
2626 /// \code
2627 /// template<typename T> constexpr T pi = T(3.1415926535897932385);
2628 ///
2629 /// template<>
2630 /// constexpr float pi<float>; // variable template specialization pi<float>
2631 /// \endcode
2632 class VarTemplateSpecializationDecl : public VarDecl,
2633                                       public llvm::FoldingSetNode {
2634 
2635   /// Structure that stores information about a variable template
2636   /// specialization that was instantiated from a variable template partial
2637   /// specialization.
2638   struct SpecializedPartialSpecialization {
2639     /// The variable template partial specialization from which this
2640     /// variable template specialization was instantiated.
2641     VarTemplatePartialSpecializationDecl *PartialSpecialization;
2642 
2643     /// The template argument list deduced for the variable template
2644     /// partial specialization itself.
2645     const TemplateArgumentList *TemplateArgs;
2646   };
2647 
2648   /// The template that this specialization specializes.
2649   llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
2650   SpecializedTemplate;
2651 
2652   /// Further info for explicit template specialization/instantiation.
2653   /// Does not apply to implicit specializations.
2654   SpecializationOrInstantiationInfo ExplicitInfo = nullptr;
2655 
2656   /// The template arguments used to describe this specialization.
2657   const TemplateArgumentList *TemplateArgs;
2658 
2659   /// The point where this template was instantiated (if any).
2660   SourceLocation PointOfInstantiation;
2661 
2662   /// The kind of specialization this declaration refers to.
2663   LLVM_PREFERRED_TYPE(TemplateSpecializationKind)
2664   unsigned SpecializationKind : 3;
2665 
2666   /// Whether this declaration is a complete definition of the
2667   /// variable template specialization. We can't otherwise tell apart
2668   /// an instantiated declaration from an instantiated definition with
2669   /// no initializer.
2670   LLVM_PREFERRED_TYPE(bool)
2671   unsigned IsCompleteDefinition : 1;
2672 
2673 protected:
2674   VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
2675                                 SourceLocation StartLoc, SourceLocation IdLoc,
2676                                 VarTemplateDecl *SpecializedTemplate,
2677                                 QualType T, TypeSourceInfo *TInfo,
2678                                 StorageClass S,
2679                                 ArrayRef<TemplateArgument> Args);
2680 
2681   explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
2682 
2683 public:
2684   friend class ASTDeclReader;
2685   friend class ASTDeclWriter;
2686   friend class VarDecl;
2687 
2688   static VarTemplateSpecializationDecl *
2689   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2690          SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
2691          TypeSourceInfo *TInfo, StorageClass S,
2692          ArrayRef<TemplateArgument> Args);
2693   static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
2694                                                            GlobalDeclID ID);
2695 
2696   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2697                             bool Qualified) const override;
2698 
2699   VarTemplateSpecializationDecl *getMostRecentDecl() {
2700     VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
2701     return cast<VarTemplateSpecializationDecl>(Recent);
2702   }
2703 
2704   /// Retrieve the template that this specialization specializes.
2705   VarTemplateDecl *getSpecializedTemplate() const;
2706 
2707   /// Retrieve the template arguments of the variable template
2708   /// specialization.
2709   const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
2710 
2711   /// Determine the kind of specialization that this
2712   /// declaration represents.
2713   TemplateSpecializationKind getSpecializationKind() const {
2714     return static_cast<TemplateSpecializationKind>(SpecializationKind);
2715   }
2716 
2717   bool isExplicitSpecialization() const {
2718     return getSpecializationKind() == TSK_ExplicitSpecialization;
2719   }
2720 
2721   bool isClassScopeExplicitSpecialization() const {
2722     return isExplicitSpecialization() &&
2723            isa<CXXRecordDecl>(getLexicalDeclContext());
2724   }
2725 
2726   /// True if this declaration is an explicit specialization,
2727   /// explicit instantiation declaration, or explicit instantiation
2728   /// definition.
2729   bool isExplicitInstantiationOrSpecialization() const {
2730     return isTemplateExplicitInstantiationOrSpecialization(
2731         getTemplateSpecializationKind());
2732   }
2733 
2734   void setSpecializationKind(TemplateSpecializationKind TSK) {
2735     SpecializationKind = TSK;
2736   }
2737 
2738   /// Get the point of instantiation (if any), or null if none.
2739   SourceLocation getPointOfInstantiation() const {
2740     return PointOfInstantiation;
2741   }
2742 
2743   void setPointOfInstantiation(SourceLocation Loc) {
2744     assert(Loc.isValid() && "point of instantiation must be valid!");
2745     PointOfInstantiation = Loc;
2746   }
2747 
2748   void setCompleteDefinition() { IsCompleteDefinition = true; }
2749 
2750   /// If this variable template specialization is an instantiation of
2751   /// a template (rather than an explicit specialization), return the
2752   /// variable template or variable template partial specialization from which
2753   /// it was instantiated.
2754   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2755   getInstantiatedFrom() const {
2756     if (!isTemplateInstantiation(getSpecializationKind()))
2757       return llvm::PointerUnion<VarTemplateDecl *,
2758                                 VarTemplatePartialSpecializationDecl *>();
2759 
2760     return getSpecializedTemplateOrPartial();
2761   }
2762 
2763   /// Retrieve the variable template or variable template partial
2764   /// specialization which was specialized by this.
2765   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2766   getSpecializedTemplateOrPartial() const {
2767     if (const auto *PartialSpec =
2768             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2769       return PartialSpec->PartialSpecialization;
2770 
2771     return cast<VarTemplateDecl *>(SpecializedTemplate);
2772   }
2773 
2774   /// Retrieve the set of template arguments that should be used
2775   /// to instantiate the initializer of the variable template or variable
2776   /// template partial specialization from which this variable template
2777   /// specialization was instantiated.
2778   ///
2779   /// \returns For a variable template specialization instantiated from the
2780   /// primary template, this function will return the same template arguments
2781   /// as getTemplateArgs(). For a variable template specialization instantiated
2782   /// from a variable template partial specialization, this function will the
2783   /// return deduced template arguments for the variable template partial
2784   /// specialization itself.
2785   const TemplateArgumentList &getTemplateInstantiationArgs() const {
2786     if (const auto *PartialSpec =
2787             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2788       return *PartialSpec->TemplateArgs;
2789 
2790     return getTemplateArgs();
2791   }
2792 
2793   /// Note that this variable template specialization is actually an
2794   /// instantiation of the given variable template partial specialization whose
2795   /// template arguments have been deduced.
2796   void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
2797                           const TemplateArgumentList *TemplateArgs) {
2798     assert(!isa<SpecializedPartialSpecialization *>(SpecializedTemplate) &&
2799            "Already set to a variable template partial specialization!");
2800     auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
2801     PS->PartialSpecialization = PartialSpec;
2802     PS->TemplateArgs = TemplateArgs;
2803     SpecializedTemplate = PS;
2804   }
2805 
2806   /// Note that this variable template specialization is an instantiation
2807   /// of the given variable template.
2808   void setInstantiationOf(VarTemplateDecl *TemplDecl) {
2809     assert(!isa<SpecializedPartialSpecialization *>(SpecializedTemplate) &&
2810            "Previously set to a variable template partial specialization!");
2811     SpecializedTemplate = TemplDecl;
2812   }
2813 
2814   /// Retrieve the template argument list as written in the sources,
2815   /// if any.
2816   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2817     if (auto *Info =
2818             dyn_cast_if_present<ExplicitInstantiationInfo *>(ExplicitInfo))
2819       return Info->TemplateArgsAsWritten;
2820     return cast<const ASTTemplateArgumentListInfo *>(ExplicitInfo);
2821   }
2822 
2823   /// Set the template argument list as written in the sources.
2824   void
2825   setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten) {
2826     if (auto *Info =
2827             dyn_cast_if_present<ExplicitInstantiationInfo *>(ExplicitInfo))
2828       Info->TemplateArgsAsWritten = ArgsWritten;
2829     else
2830       ExplicitInfo = ArgsWritten;
2831   }
2832 
2833   /// Set the template argument list as written in the sources.
2834   void setTemplateArgsAsWritten(const TemplateArgumentListInfo &ArgsInfo) {
2835     setTemplateArgsAsWritten(
2836         ASTTemplateArgumentListInfo::Create(getASTContext(), ArgsInfo));
2837   }
2838 
2839   /// Gets the location of the extern keyword, if present.
2840   SourceLocation getExternKeywordLoc() const {
2841     if (auto *Info =
2842             dyn_cast_if_present<ExplicitInstantiationInfo *>(ExplicitInfo))
2843       return Info->ExternKeywordLoc;
2844     return SourceLocation();
2845   }
2846 
2847   /// Sets the location of the extern keyword.
2848   void setExternKeywordLoc(SourceLocation Loc);
2849 
2850   /// Gets the location of the template keyword, if present.
2851   SourceLocation getTemplateKeywordLoc() const {
2852     if (auto *Info =
2853             dyn_cast_if_present<ExplicitInstantiationInfo *>(ExplicitInfo))
2854       return Info->TemplateKeywordLoc;
2855     return SourceLocation();
2856   }
2857 
2858   /// Sets the location of the template keyword.
2859   void setTemplateKeywordLoc(SourceLocation Loc);
2860 
2861   SourceRange getSourceRange() const override LLVM_READONLY;
2862 
2863   void Profile(llvm::FoldingSetNodeID &ID) const {
2864     Profile(ID, TemplateArgs->asArray(), getASTContext());
2865   }
2866 
2867   static void Profile(llvm::FoldingSetNodeID &ID,
2868                       ArrayRef<TemplateArgument> TemplateArgs,
2869                       const ASTContext &Context) {
2870     ID.AddInteger(TemplateArgs.size());
2871     for (const TemplateArgument &TemplateArg : TemplateArgs)
2872       TemplateArg.Profile(ID, Context);
2873   }
2874 
2875   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2876 
2877   static bool classofKind(Kind K) {
2878     return K >= firstVarTemplateSpecialization &&
2879            K <= lastVarTemplateSpecialization;
2880   }
2881 };
2882 
2883 class VarTemplatePartialSpecializationDecl
2884     : public VarTemplateSpecializationDecl {
2885   /// The list of template parameters
2886   TemplateParameterList *TemplateParams = nullptr;
2887 
2888   /// The variable template partial specialization from which this
2889   /// variable template partial specialization was instantiated.
2890   ///
2891   /// The boolean value will be true to indicate that this variable template
2892   /// partial specialization was specialized at this level.
2893   llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
2894   InstantiatedFromMember;
2895 
2896   VarTemplatePartialSpecializationDecl(
2897       ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2898       SourceLocation IdLoc, TemplateParameterList *Params,
2899       VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
2900       StorageClass S, ArrayRef<TemplateArgument> Args);
2901 
2902   VarTemplatePartialSpecializationDecl(ASTContext &Context)
2903       : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization,
2904                                       Context),
2905         InstantiatedFromMember(nullptr, false) {}
2906 
2907   void anchor() override;
2908 
2909 public:
2910   friend class ASTDeclReader;
2911   friend class ASTDeclWriter;
2912 
2913   static VarTemplatePartialSpecializationDecl *
2914   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2915          SourceLocation IdLoc, TemplateParameterList *Params,
2916          VarTemplateDecl *SpecializedTemplate, QualType T,
2917          TypeSourceInfo *TInfo, StorageClass S,
2918          ArrayRef<TemplateArgument> Args);
2919 
2920   static VarTemplatePartialSpecializationDecl *
2921   CreateDeserialized(ASTContext &C, GlobalDeclID ID);
2922 
2923   VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
2924     return cast<VarTemplatePartialSpecializationDecl>(
2925              static_cast<VarTemplateSpecializationDecl *>(
2926                this)->getMostRecentDecl());
2927   }
2928 
2929   /// Get the list of template parameters
2930   TemplateParameterList *getTemplateParameters() const {
2931     return TemplateParams;
2932   }
2933 
2934   /// Get the template argument list of the template parameter list.
2935   ArrayRef<TemplateArgument>
2936   getInjectedTemplateArgs(const ASTContext &Context) const {
2937     return getTemplateParameters()->getInjectedTemplateArgs(Context);
2938   }
2939 
2940   /// \brief All associated constraints of this partial specialization,
2941   /// including the requires clause and any constraints derived from
2942   /// constrained-parameters.
2943   ///
2944   /// The constraints in the resulting list are to be treated as if in a
2945   /// conjunction ("and").
2946   void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
2947     TemplateParams->getAssociatedConstraints(AC);
2948   }
2949 
2950   bool hasAssociatedConstraints() const {
2951     return TemplateParams->hasAssociatedConstraints();
2952   }
2953 
2954   /// \brief Retrieve the member variable template partial specialization from
2955   /// which this particular variable template partial specialization was
2956   /// instantiated.
2957   ///
2958   /// \code
2959   /// template<typename T>
2960   /// struct Outer {
2961   ///   template<typename U> U Inner;
2962   ///   template<typename U> U* Inner<U*> = (U*)(0); // #1
2963   /// };
2964   ///
2965   /// template int* Outer<float>::Inner<int*>;
2966   /// \endcode
2967   ///
2968   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
2969   /// end up instantiating the partial specialization
2970   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
2971   /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
2972   /// \c Outer<float>::Inner<U*>, this function would return
2973   /// \c Outer<T>::Inner<U*>.
2974   VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2975     const auto *First =
2976         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2977     return First->InstantiatedFromMember.getPointer();
2978   }
2979 
2980   void
2981   setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
2982     auto *First = cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2983     First->InstantiatedFromMember.setPointer(PartialSpec);
2984   }
2985 
2986   /// Determines whether this variable template partial specialization
2987   /// was a specialization of a member partial specialization.
2988   ///
2989   /// In the following example, the member template partial specialization
2990   /// \c X<int>::Inner<T*> is a member specialization.
2991   ///
2992   /// \code
2993   /// template<typename T>
2994   /// struct X {
2995   ///   template<typename U> U Inner;
2996   ///   template<typename U> U* Inner<U*> = (U*)(0);
2997   /// };
2998   ///
2999   /// template<> template<typename T>
3000   /// U* X<int>::Inner<T*> = (T*)(0) + 1;
3001   /// \endcode
3002   bool isMemberSpecialization() const {
3003     const auto *First =
3004         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
3005     return First->InstantiatedFromMember.getInt();
3006   }
3007 
3008   /// Note that this member template is a specialization.
3009   void setMemberSpecialization() {
3010     auto *First = cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
3011     assert(First->InstantiatedFromMember.getPointer() &&
3012            "Only member templates can be member template specializations");
3013     return First->InstantiatedFromMember.setInt(true);
3014   }
3015 
3016   SourceRange getSourceRange() const override LLVM_READONLY;
3017 
3018   void Profile(llvm::FoldingSetNodeID &ID) const {
3019     Profile(ID, getTemplateArgs().asArray(), getTemplateParameters(),
3020             getASTContext());
3021   }
3022 
3023   static void
3024   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
3025           TemplateParameterList *TPL, const ASTContext &Context);
3026 
3027   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3028 
3029   static bool classofKind(Kind K) {
3030     return K == VarTemplatePartialSpecialization;
3031   }
3032 };
3033 
3034 /// Declaration of a variable template.
3035 class VarTemplateDecl : public RedeclarableTemplateDecl {
3036 protected:
3037   /// Data that is common to all of the declarations of a given
3038   /// variable template.
3039   struct Common : CommonBase {
3040     /// The variable template specializations for this variable
3041     /// template, including explicit specializations and instantiations.
3042     llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
3043 
3044     /// The variable template partial specializations for this variable
3045     /// template.
3046     llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
3047     PartialSpecializations;
3048 
3049     Common() = default;
3050   };
3051 
3052   /// Retrieve the set of specializations of this variable template.
3053   llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
3054   getSpecializations() const;
3055 
3056   /// Retrieve the set of partial specializations of this class
3057   /// template.
3058   llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
3059   getPartialSpecializations() const;
3060 
3061   VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
3062                   DeclarationName Name, TemplateParameterList *Params,
3063                   NamedDecl *Decl)
3064       : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
3065 
3066   CommonBase *newCommon(ASTContext &C) const override;
3067 
3068   Common *getCommonPtr() const {
3069     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
3070   }
3071 
3072 public:
3073   friend class ASTDeclReader;
3074   friend class ASTDeclWriter;
3075 
3076   /// Load any lazily-loaded specializations from the external source.
3077   void LoadLazySpecializations(bool OnlyPartial = false) const;
3078 
3079   /// Get the underlying variable declarations of the template.
3080   VarDecl *getTemplatedDecl() const {
3081     return static_cast<VarDecl *>(TemplatedDecl);
3082   }
3083 
3084   /// Returns whether this template declaration defines the primary
3085   /// variable pattern.
3086   bool isThisDeclarationADefinition() const {
3087     return getTemplatedDecl()->isThisDeclarationADefinition();
3088   }
3089 
3090   VarTemplateDecl *getDefinition();
3091 
3092   /// Create a variable template node.
3093   static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
3094                                  SourceLocation L, DeclarationName Name,
3095                                  TemplateParameterList *Params,
3096                                  VarDecl *Decl);
3097 
3098   /// Create an empty variable template node.
3099   static VarTemplateDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
3100 
3101   /// Return the specialization with the provided arguments if it exists,
3102   /// otherwise return the insertion point.
3103   VarTemplateSpecializationDecl *
3104   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
3105 
3106   /// Insert the specified specialization knowing that it is not already
3107   /// in. InsertPos must be obtained from findSpecialization.
3108   void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
3109 
3110   VarTemplateDecl *getCanonicalDecl() override {
3111     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
3112   }
3113   const VarTemplateDecl *getCanonicalDecl() const {
3114     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
3115   }
3116 
3117   /// Retrieve the previous declaration of this variable template, or
3118   /// nullptr if no such declaration exists.
3119   VarTemplateDecl *getPreviousDecl() {
3120     return cast_or_null<VarTemplateDecl>(
3121         static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
3122   }
3123   const VarTemplateDecl *getPreviousDecl() const {
3124     return cast_or_null<VarTemplateDecl>(
3125             static_cast<const RedeclarableTemplateDecl *>(
3126               this)->getPreviousDecl());
3127   }
3128 
3129   VarTemplateDecl *getMostRecentDecl() {
3130     return cast<VarTemplateDecl>(
3131         static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
3132   }
3133   const VarTemplateDecl *getMostRecentDecl() const {
3134     return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
3135   }
3136 
3137   VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
3138     return cast_or_null<VarTemplateDecl>(
3139         RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
3140   }
3141 
3142   /// Return the partial specialization with the provided arguments if it
3143   /// exists, otherwise return the insertion point.
3144   VarTemplatePartialSpecializationDecl *
3145   findPartialSpecialization(ArrayRef<TemplateArgument> Args,
3146                             TemplateParameterList *TPL, void *&InsertPos);
3147 
3148   /// Insert the specified partial specialization knowing that it is not
3149   /// already in. InsertPos must be obtained from findPartialSpecialization.
3150   void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
3151                                 void *InsertPos);
3152 
3153   /// Retrieve the partial specializations as an ordered list.
3154   void getPartialSpecializations(
3155       SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS) const;
3156 
3157   /// Find a variable template partial specialization which was
3158   /// instantiated
3159   /// from the given member partial specialization.
3160   ///
3161   /// \param D a member variable template partial specialization.
3162   ///
3163   /// \returns the variable template partial specialization which was
3164   /// instantiated
3165   /// from the given member partial specialization, or nullptr if no such
3166   /// partial specialization exists.
3167   VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
3168       VarTemplatePartialSpecializationDecl *D);
3169 
3170   using spec_iterator = SpecIterator<VarTemplateSpecializationDecl>;
3171   using spec_range = llvm::iterator_range<spec_iterator>;
3172 
3173   spec_range specializations() const {
3174     return spec_range(spec_begin(), spec_end());
3175   }
3176 
3177   spec_iterator spec_begin() const {
3178     return makeSpecIterator(getSpecializations(), false);
3179   }
3180 
3181   spec_iterator spec_end() const {
3182     return makeSpecIterator(getSpecializations(), true);
3183   }
3184 
3185   // Implement isa/cast/dyncast support
3186   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3187   static bool classofKind(Kind K) { return K == VarTemplate; }
3188 };
3189 
3190 /// Declaration of a C++20 concept.
3191 class ConceptDecl : public TemplateDecl, public Mergeable<ConceptDecl> {
3192 protected:
3193   Expr *ConstraintExpr;
3194 
3195   ConceptDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
3196               TemplateParameterList *Params, Expr *ConstraintExpr)
3197       : TemplateDecl(Concept, DC, L, Name, Params),
3198         ConstraintExpr(ConstraintExpr) {};
3199 public:
3200   static ConceptDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3201                              DeclarationName Name,
3202                              TemplateParameterList *Params,
3203                              Expr *ConstraintExpr = nullptr);
3204   static ConceptDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
3205 
3206   Expr *getConstraintExpr() const {
3207     return ConstraintExpr;
3208   }
3209 
3210   bool hasDefinition() const { return ConstraintExpr != nullptr; }
3211 
3212   void setDefinition(Expr *E) { ConstraintExpr = E; }
3213 
3214   SourceRange getSourceRange() const override LLVM_READONLY {
3215     return SourceRange(getTemplateParameters()->getTemplateLoc(),
3216                        ConstraintExpr ? ConstraintExpr->getEndLoc()
3217                                       : SourceLocation());
3218   }
3219 
3220   bool isTypeConcept() const {
3221     return isa<TemplateTypeParmDecl>(getTemplateParameters()->getParam(0));
3222   }
3223 
3224   ConceptDecl *getCanonicalDecl() override {
3225     return cast<ConceptDecl>(getPrimaryMergedDecl(this));
3226   }
3227   const ConceptDecl *getCanonicalDecl() const {
3228     return const_cast<ConceptDecl *>(this)->getCanonicalDecl();
3229   }
3230 
3231   // Implement isa/cast/dyncast/etc.
3232   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3233   static bool classofKind(Kind K) { return K == Concept; }
3234 
3235   friend class ASTReader;
3236   friend class ASTDeclReader;
3237   friend class ASTDeclWriter;
3238 };
3239 
3240 // An implementation detail of ConceptSpecialicationExpr that holds the template
3241 // arguments, so we can later use this to reconstitute the template arguments
3242 // during constraint checking.
3243 class ImplicitConceptSpecializationDecl final
3244     : public Decl,
3245       private llvm::TrailingObjects<ImplicitConceptSpecializationDecl,
3246                                     TemplateArgument> {
3247   unsigned NumTemplateArgs;
3248 
3249   ImplicitConceptSpecializationDecl(DeclContext *DC, SourceLocation SL,
3250                                     ArrayRef<TemplateArgument> ConvertedArgs);
3251   ImplicitConceptSpecializationDecl(EmptyShell Empty, unsigned NumTemplateArgs);
3252 
3253 public:
3254   static ImplicitConceptSpecializationDecl *
3255   Create(const ASTContext &C, DeclContext *DC, SourceLocation SL,
3256          ArrayRef<TemplateArgument> ConvertedArgs);
3257   static ImplicitConceptSpecializationDecl *
3258   CreateDeserialized(const ASTContext &C, GlobalDeclID ID,
3259                      unsigned NumTemplateArgs);
3260 
3261   ArrayRef<TemplateArgument> getTemplateArguments() const {
3262     return ArrayRef<TemplateArgument>(getTrailingObjects<TemplateArgument>(),
3263                                       NumTemplateArgs);
3264   }
3265   void setTemplateArguments(ArrayRef<TemplateArgument> Converted);
3266 
3267   static bool classofKind(Kind K) { return K == ImplicitConceptSpecialization; }
3268   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3269 
3270   friend TrailingObjects;
3271   friend class ASTDeclReader;
3272 };
3273 
3274 /// A template parameter object.
3275 ///
3276 /// Template parameter objects represent values of class type used as template
3277 /// arguments. There is one template parameter object for each such distinct
3278 /// value used as a template argument across the program.
3279 ///
3280 /// \code
3281 /// struct A { int x, y; };
3282 /// template<A> struct S;
3283 /// S<A{1, 2}> s1;
3284 /// S<A{1, 2}> s2; // same type, argument is same TemplateParamObjectDecl.
3285 /// \endcode
3286 class TemplateParamObjectDecl : public ValueDecl,
3287                                 public Mergeable<TemplateParamObjectDecl>,
3288                                 public llvm::FoldingSetNode {
3289 private:
3290   /// The value of this template parameter object.
3291   APValue Value;
3292 
3293   TemplateParamObjectDecl(DeclContext *DC, QualType T, const APValue &V)
3294       : ValueDecl(TemplateParamObject, DC, SourceLocation(), DeclarationName(),
3295                   T),
3296         Value(V) {}
3297 
3298   static TemplateParamObjectDecl *Create(const ASTContext &C, QualType T,
3299                                          const APValue &V);
3300   static TemplateParamObjectDecl *CreateDeserialized(ASTContext &C,
3301                                                      GlobalDeclID ID);
3302 
3303   /// Only ASTContext::getTemplateParamObjectDecl and deserialization
3304   /// create these.
3305   friend class ASTContext;
3306   friend class ASTReader;
3307   friend class ASTDeclReader;
3308 
3309 public:
3310   /// Print this template parameter object in a human-readable format.
3311   void printName(llvm::raw_ostream &OS,
3312                  const PrintingPolicy &Policy) const override;
3313 
3314   /// Print this object as an equivalent expression.
3315   void printAsExpr(llvm::raw_ostream &OS) const;
3316   void printAsExpr(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const;
3317 
3318   /// Print this object as an initializer suitable for a variable of the
3319   /// object's type.
3320   void printAsInit(llvm::raw_ostream &OS) const;
3321   void printAsInit(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const;
3322 
3323   const APValue &getValue() const { return Value; }
3324 
3325   static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
3326                       const APValue &V) {
3327     ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
3328     V.Profile(ID);
3329   }
3330   void Profile(llvm::FoldingSetNodeID &ID) {
3331     Profile(ID, getType(), getValue());
3332   }
3333 
3334   TemplateParamObjectDecl *getCanonicalDecl() override {
3335     return getFirstDecl();
3336   }
3337   const TemplateParamObjectDecl *getCanonicalDecl() const {
3338     return getFirstDecl();
3339   }
3340 
3341   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3342   static bool classofKind(Kind K) { return K == TemplateParamObject; }
3343 };
3344 
3345 inline NamedDecl *getAsNamedDecl(TemplateParameter P) {
3346   if (auto *PD = P.dyn_cast<TemplateTypeParmDecl *>())
3347     return PD;
3348   if (auto *PD = P.dyn_cast<NonTypeTemplateParmDecl *>())
3349     return PD;
3350   return cast<TemplateTemplateParmDecl *>(P);
3351 }
3352 
3353 inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
3354   auto *TD = dyn_cast<TemplateDecl>(D);
3355   return TD && (isa<ClassTemplateDecl>(TD) ||
3356                 isa<ClassTemplatePartialSpecializationDecl>(TD) ||
3357                 isa<TypeAliasTemplateDecl>(TD) ||
3358                 isa<TemplateTemplateParmDecl>(TD))
3359              ? TD
3360              : nullptr;
3361 }
3362 
3363 /// Check whether the template parameter is a pack expansion, and if so,
3364 /// determine the number of parameters produced by that expansion. For instance:
3365 ///
3366 /// \code
3367 /// template<typename ...Ts> struct A {
3368 ///   template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3369 /// };
3370 /// \endcode
3371 ///
3372 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3373 /// is not a pack expansion, so returns an empty Optional.
3374 inline std::optional<unsigned> getExpandedPackSize(const NamedDecl *Param) {
3375   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3376     if (TTP->isExpandedParameterPack())
3377       return TTP->getNumExpansionParameters();
3378   }
3379 
3380   if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3381     if (NTTP->isExpandedParameterPack())
3382       return NTTP->getNumExpansionTypes();
3383   }
3384 
3385   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3386     if (TTP->isExpandedParameterPack())
3387       return TTP->getNumExpansionTemplateParameters();
3388   }
3389 
3390   return std::nullopt;
3391 }
3392 
3393 /// Internal helper used by Subst* nodes to retrieve the parameter list
3394 /// for their AssociatedDecl.
3395 TemplateParameterList *getReplacedTemplateParameterList(Decl *D);
3396 
3397 } // namespace clang
3398 
3399 #endif // LLVM_CLANG_AST_DECLTEMPLATE_H