Home | History | Annotate | Download | only in AST
      1 //===-- DeclTemplate.h - Classes for representing C++ templates -*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 ///
     10 /// \file
     11 /// \brief Defines the C++ template declaration subclasses.
     12 ///
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
     16 #define LLVM_CLANG_AST_DECLTEMPLATE_H
     17 
     18 #include "clang/AST/DeclCXX.h"
     19 #include "clang/AST/Redeclarable.h"
     20 #include "clang/AST/TemplateBase.h"
     21 #include "llvm/ADT/PointerUnion.h"
     22 #include "llvm/Support/Compiler.h"
     23 #include "llvm/Support/TrailingObjects.h"
     24 #include <limits>
     25 
     26 namespace clang {
     27 
     28 enum BuiltinTemplateKind : int;
     29 class TemplateParameterList;
     30 class TemplateDecl;
     31 class RedeclarableTemplateDecl;
     32 class FunctionTemplateDecl;
     33 class ClassTemplateDecl;
     34 class ClassTemplatePartialSpecializationDecl;
     35 class TemplateTypeParmDecl;
     36 class NonTypeTemplateParmDecl;
     37 class TemplateTemplateParmDecl;
     38 class TypeAliasTemplateDecl;
     39 class VarTemplateDecl;
     40 class VarTemplatePartialSpecializationDecl;
     41 
     42 /// \brief Stores a template parameter of any kind.
     43 typedef llvm::PointerUnion3<TemplateTypeParmDecl*, NonTypeTemplateParmDecl*,
     44                             TemplateTemplateParmDecl*> TemplateParameter;
     45 
     46 /// \brief Stores a list of template parameters for a TemplateDecl and its
     47 /// derived classes.
     48 class LLVM_ALIGNAS(/*alignof(void*)*/ LLVM_PTR_SIZE) TemplateParameterList final
     49     : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *> {
     50 
     51   /// The location of the 'template' keyword.
     52   SourceLocation TemplateLoc;
     53 
     54   /// The locations of the '<' and '>' angle brackets.
     55   SourceLocation LAngleLoc, RAngleLoc;
     56 
     57   /// The number of template parameters in this template
     58   /// parameter list.
     59   unsigned NumParams : 31;
     60 
     61   /// Whether this template parameter list contains an unexpanded parameter
     62   /// pack.
     63   unsigned ContainsUnexpandedParameterPack : 1;
     64 
     65 protected:
     66   size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
     67     return NumParams;
     68   }
     69 
     70   TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
     71                         NamedDecl **Params, unsigned NumParams,
     72                         SourceLocation RAngleLoc);
     73 
     74 public:
     75   static TemplateParameterList *Create(const ASTContext &C,
     76                                        SourceLocation TemplateLoc,
     77                                        SourceLocation LAngleLoc,
     78                                        NamedDecl **Params,
     79                                        unsigned NumParams,
     80                                        SourceLocation RAngleLoc);
     81 
     82   /// \brief Iterates through the template parameters in this list.
     83   typedef NamedDecl** iterator;
     84 
     85   /// \brief Iterates through the template parameters in this list.
     86   typedef NamedDecl* const* const_iterator;
     87 
     88   iterator begin() { return getTrailingObjects<NamedDecl *>(); }
     89   const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
     90   iterator end() { return begin() + NumParams; }
     91   const_iterator end() const { return begin() + NumParams; }
     92 
     93   unsigned size() const { return NumParams; }
     94 
     95   ArrayRef<NamedDecl*> asArray() {
     96     return llvm::makeArrayRef(begin(), end());
     97   }
     98   ArrayRef<const NamedDecl*> asArray() const {
     99     return llvm::makeArrayRef(begin(), size());
    100   }
    101 
    102   NamedDecl* getParam(unsigned Idx) {
    103     assert(Idx < size() && "Template parameter index out-of-range");
    104     return begin()[Idx];
    105   }
    106 
    107   const NamedDecl* getParam(unsigned Idx) const {
    108     assert(Idx < size() && "Template parameter index out-of-range");
    109     return begin()[Idx];
    110   }
    111 
    112   /// \brief Returns the minimum number of arguments needed to form a
    113   /// template specialization.
    114   ///
    115   /// This may be fewer than the number of template parameters, if some of
    116   /// the parameters have default arguments or if there is a parameter pack.
    117   unsigned getMinRequiredArguments() const;
    118 
    119   /// \brief Get the depth of this template parameter list in the set of
    120   /// template parameter lists.
    121   ///
    122   /// The first template parameter list in a declaration will have depth 0,
    123   /// the second template parameter list will have depth 1, etc.
    124   unsigned getDepth() const;
    125 
    126   /// \brief Determine whether this template parameter list contains an
    127   /// unexpanded parameter pack.
    128   bool containsUnexpandedParameterPack() const {
    129     return ContainsUnexpandedParameterPack;
    130   }
    131 
    132   SourceLocation getTemplateLoc() const { return TemplateLoc; }
    133   SourceLocation getLAngleLoc() const { return LAngleLoc; }
    134   SourceLocation getRAngleLoc() const { return RAngleLoc; }
    135 
    136   SourceRange getSourceRange() const LLVM_READONLY {
    137     return SourceRange(TemplateLoc, RAngleLoc);
    138   }
    139 
    140   friend TrailingObjects;
    141   template <size_t N> friend class FixedSizeTemplateParameterListStorage;
    142 };
    143 
    144 /// \brief Stores a list of template parameters for a TemplateDecl and its
    145 /// derived classes. Suitable for creating on the stack.
    146 template <size_t N> class FixedSizeTemplateParameterListStorage {
    147   // This is kinda ugly: TemplateParameterList usually gets allocated
    148   // in a block of memory with NamedDecls appended to it. Here, to get
    149   // it stack allocated, we include the params as a separate
    150   // variable. After allocation, the TemplateParameterList object
    151   // treats them as part of itself.
    152   TemplateParameterList List;
    153   NamedDecl *Params[N];
    154 
    155 public:
    156   FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
    157                                         SourceLocation LAngleLoc,
    158                                         NamedDecl **Params,
    159                                         SourceLocation RAngleLoc)
    160       : List(TemplateLoc, LAngleLoc, Params, N, RAngleLoc) {
    161     // Because we're doing an evil layout hack above, have some
    162     // asserts, just to double-check everything is laid out like
    163     // expected.
    164     assert(sizeof(*this) ==
    165                TemplateParameterList::totalSizeToAlloc<NamedDecl *>(N) &&
    166            "Object layout not as expected");
    167     assert(this->Params == List.getTrailingObjects<NamedDecl *>() &&
    168            "Object layout not as expected");
    169   }
    170   TemplateParameterList *get() { return &List; }
    171 };
    172 
    173 /// \brief A template argument list.
    174 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateArgumentList final
    175     : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
    176   /// \brief The template argument list.
    177   const TemplateArgument *Arguments;
    178 
    179   /// \brief The number of template arguments in this template
    180   /// argument list.
    181   unsigned NumArguments;
    182 
    183   TemplateArgumentList(const TemplateArgumentList &Other) = delete;
    184   void operator=(const TemplateArgumentList &Other) = delete;
    185 
    186   // Constructs an instance with an internal Argument list, containing
    187   // a copy of the Args array. (Called by CreateCopy)
    188   TemplateArgumentList(const TemplateArgument *Args, unsigned NumArgs);
    189 
    190 public:
    191   /// \brief Type used to indicate that the template argument list itself is a
    192   /// stack object. It does not own its template arguments.
    193   enum OnStackType { OnStack };
    194 
    195   /// \brief Create a new template argument list that copies the given set of
    196   /// template arguments.
    197   static TemplateArgumentList *CreateCopy(ASTContext &Context,
    198                                           const TemplateArgument *Args,
    199                                           unsigned NumArgs);
    200 
    201   /// \brief Construct a new, temporary template argument list on the stack.
    202   ///
    203   /// The template argument list does not own the template arguments
    204   /// provided.
    205   explicit TemplateArgumentList(OnStackType, const TemplateArgument *Args,
    206                                 unsigned NumArgs)
    207       : Arguments(Args), NumArguments(NumArgs) {}
    208 
    209   /// \brief Produces a shallow copy of the given template argument list.
    210   ///
    211   /// This operation assumes that the input argument list outlives it.
    212   /// This takes the list as a pointer to avoid looking like a copy
    213   /// constructor, since this really really isn't safe to use that
    214   /// way.
    215   explicit TemplateArgumentList(const TemplateArgumentList *Other)
    216       : Arguments(Other->data()), NumArguments(Other->size()) {}
    217 
    218   /// \brief Retrieve the template argument at a given index.
    219   const TemplateArgument &get(unsigned Idx) const {
    220     assert(Idx < NumArguments && "Invalid template argument index");
    221     return data()[Idx];
    222   }
    223 
    224   /// \brief Retrieve the template argument at a given index.
    225   const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
    226 
    227   /// \brief Produce this as an array ref.
    228   ArrayRef<TemplateArgument> asArray() const {
    229     return llvm::makeArrayRef(data(), size());
    230   }
    231 
    232   /// \brief Retrieve the number of template arguments in this
    233   /// template argument list.
    234   unsigned size() const { return NumArguments; }
    235 
    236   /// \brief Retrieve a pointer to the template argument list.
    237   const TemplateArgument *data() const { return Arguments; }
    238 
    239   friend TrailingObjects;
    240 };
    241 
    242 void *allocateDefaultArgStorageChain(const ASTContext &C);
    243 
    244 /// Storage for a default argument. This is conceptually either empty, or an
    245 /// argument value, or a pointer to a previous declaration that had a default
    246 /// argument.
    247 ///
    248 /// However, this is complicated by modules: while we require all the default
    249 /// arguments for a template to be equivalent, there may be more than one, and
    250 /// we need to track all the originating parameters to determine if the default
    251 /// argument is visible.
    252 template<typename ParmDecl, typename ArgType>
    253 class DefaultArgStorage {
    254   /// Storage for both the value *and* another parameter from which we inherit
    255   /// the default argument. This is used when multiple default arguments for a
    256   /// parameter are merged together from different modules.
    257   struct Chain {
    258     ParmDecl *PrevDeclWithDefaultArg;
    259     ArgType Value;
    260   };
    261   static_assert(sizeof(Chain) == sizeof(void *) * 2,
    262                 "non-pointer argument type?");
    263 
    264   llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
    265 
    266   static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
    267     const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
    268     if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl*>())
    269       Parm = Prev;
    270     assert(!Parm->getDefaultArgStorage()
    271                 .ValueOrInherited.template is<ParmDecl *>() &&
    272            "should only be one level of indirection");
    273     return Parm;
    274   }
    275 
    276 public:
    277   DefaultArgStorage() : ValueOrInherited(ArgType()) {}
    278 
    279   /// Determine whether there is a default argument for this parameter.
    280   bool isSet() const { return !ValueOrInherited.isNull(); }
    281   /// Determine whether the default argument for this parameter was inherited
    282   /// from a previous declaration of the same entity.
    283   bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
    284   /// Get the default argument's value. This does not consider whether the
    285   /// default argument is visible.
    286   ArgType get() const {
    287     const DefaultArgStorage *Storage = this;
    288     if (auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl*>())
    289       Storage = &Prev->getDefaultArgStorage();
    290     if (auto *C = Storage->ValueOrInherited.template dyn_cast<Chain*>())
    291       return C->Value;
    292     return Storage->ValueOrInherited.template get<ArgType>();
    293   }
    294   /// Get the parameter from which we inherit the default argument, if any.
    295   /// This is the parameter on which the default argument was actually written.
    296   const ParmDecl *getInheritedFrom() const {
    297     if (auto *D = ValueOrInherited.template dyn_cast<ParmDecl*>())
    298       return D;
    299     if (auto *C = ValueOrInherited.template dyn_cast<Chain*>())
    300       return C->PrevDeclWithDefaultArg;
    301     return nullptr;
    302   }
    303   /// Set the default argument.
    304   void set(ArgType Arg) {
    305     assert(!isSet() && "default argument already set");
    306     ValueOrInherited = Arg;
    307   }
    308   /// Set that the default argument was inherited from another parameter.
    309   void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
    310     assert(!isInherited() && "default argument already inherited");
    311     InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
    312     if (!isSet())
    313       ValueOrInherited = InheritedFrom;
    314     else
    315       ValueOrInherited = new (allocateDefaultArgStorageChain(C))
    316           Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
    317   }
    318   /// Remove the default argument, even if it was inherited.
    319   void clear() {
    320     ValueOrInherited = ArgType();
    321   }
    322 };
    323 
    324 //===----------------------------------------------------------------------===//
    325 // Kinds of Templates
    326 //===----------------------------------------------------------------------===//
    327 
    328 /// \brief The base class of all kinds of template declarations (e.g.,
    329 /// class, function, etc.).
    330 ///
    331 /// The TemplateDecl class stores the list of template parameters and a
    332 /// reference to the templated scoped declaration: the underlying AST node.
    333 class TemplateDecl : public NamedDecl {
    334   void anchor() override;
    335 protected:
    336   // This is probably never used.
    337   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
    338                DeclarationName Name)
    339     : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
    340       TemplateParams(nullptr) {}
    341 
    342   // Construct a template decl with the given name and parameters.
    343   // Used when there is not templated element (tt-params).
    344   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
    345                DeclarationName Name, TemplateParameterList *Params)
    346     : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
    347       TemplateParams(Params) {}
    348 
    349   // Construct a template decl with name, parameters, and templated element.
    350   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
    351                DeclarationName Name, TemplateParameterList *Params,
    352                NamedDecl *Decl)
    353     : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
    354       TemplateParams(Params) { }
    355 public:
    356   /// Get the list of template parameters
    357   TemplateParameterList *getTemplateParameters() const {
    358     return TemplateParams;
    359   }
    360 
    361   /// Get the underlying, templated declaration.
    362   NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
    363 
    364   // Implement isa/cast/dyncast/etc.
    365   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    366   static bool classofKind(Kind K) {
    367     return K >= firstTemplate && K <= lastTemplate;
    368   }
    369 
    370   SourceRange getSourceRange() const override LLVM_READONLY {
    371     return SourceRange(TemplateParams->getTemplateLoc(),
    372                        TemplatedDecl->getSourceRange().getEnd());
    373   }
    374 
    375 protected:
    376   NamedDecl *TemplatedDecl;
    377   TemplateParameterList* TemplateParams;
    378 
    379 public:
    380   /// \brief Initialize the underlying templated declaration and
    381   /// template parameters.
    382   void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
    383     assert(!TemplatedDecl && "TemplatedDecl already set!");
    384     assert(!TemplateParams && "TemplateParams already set!");
    385     TemplatedDecl = templatedDecl;
    386     TemplateParams = templateParams;
    387   }
    388 };
    389 
    390 /// \brief Provides information about a function template specialization,
    391 /// which is a FunctionDecl that has been explicitly specialization or
    392 /// instantiated from a function template.
    393 class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
    394   FunctionTemplateSpecializationInfo(FunctionDecl *FD,
    395                                      FunctionTemplateDecl *Template,
    396                                      TemplateSpecializationKind TSK,
    397                                      const TemplateArgumentList *TemplateArgs,
    398                        const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
    399                                      SourceLocation POI)
    400   : Function(FD),
    401     Template(Template, TSK - 1),
    402     TemplateArguments(TemplateArgs),
    403     TemplateArgumentsAsWritten(TemplateArgsAsWritten),
    404     PointOfInstantiation(POI) { }
    405 
    406 public:
    407   static FunctionTemplateSpecializationInfo *
    408   Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
    409          TemplateSpecializationKind TSK,
    410          const TemplateArgumentList *TemplateArgs,
    411          const TemplateArgumentListInfo *TemplateArgsAsWritten,
    412          SourceLocation POI);
    413 
    414   /// \brief The function template specialization that this structure
    415   /// describes.
    416   FunctionDecl *Function;
    417 
    418   /// \brief The function template from which this function template
    419   /// specialization was generated.
    420   ///
    421   /// The two bits contain the top 4 values of TemplateSpecializationKind.
    422   llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
    423 
    424   /// \brief The template arguments used to produce the function template
    425   /// specialization from the function template.
    426   const TemplateArgumentList *TemplateArguments;
    427 
    428   /// \brief The template arguments as written in the sources, if provided.
    429   const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
    430 
    431   /// \brief The point at which this function template specialization was
    432   /// first instantiated.
    433   SourceLocation PointOfInstantiation;
    434 
    435   /// \brief Retrieve the template from which this function was specialized.
    436   FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
    437 
    438   /// \brief Determine what kind of template specialization this is.
    439   TemplateSpecializationKind getTemplateSpecializationKind() const {
    440     return (TemplateSpecializationKind)(Template.getInt() + 1);
    441   }
    442 
    443   bool isExplicitSpecialization() const {
    444     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
    445   }
    446 
    447   /// \brief True if this declaration is an explicit specialization,
    448   /// explicit instantiation declaration, or explicit instantiation
    449   /// definition.
    450   bool isExplicitInstantiationOrSpecialization() const {
    451     return isTemplateExplicitInstantiationOrSpecialization(
    452         getTemplateSpecializationKind());
    453   }
    454 
    455   /// \brief Set the template specialization kind.
    456   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
    457     assert(TSK != TSK_Undeclared &&
    458          "Cannot encode TSK_Undeclared for a function template specialization");
    459     Template.setInt(TSK - 1);
    460   }
    461 
    462   /// \brief Retrieve the first point of instantiation of this function
    463   /// template specialization.
    464   ///
    465   /// The point of instantiation may be an invalid source location if this
    466   /// function has yet to be instantiated.
    467   SourceLocation getPointOfInstantiation() const {
    468     return PointOfInstantiation;
    469   }
    470 
    471   /// \brief Set the (first) point of instantiation of this function template
    472   /// specialization.
    473   void setPointOfInstantiation(SourceLocation POI) {
    474     PointOfInstantiation = POI;
    475   }
    476 
    477   void Profile(llvm::FoldingSetNodeID &ID) {
    478     Profile(ID, TemplateArguments->asArray(),
    479             Function->getASTContext());
    480   }
    481 
    482   static void
    483   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
    484           ASTContext &Context) {
    485     ID.AddInteger(TemplateArgs.size());
    486     for (unsigned Arg = 0; Arg != TemplateArgs.size(); ++Arg)
    487       TemplateArgs[Arg].Profile(ID, Context);
    488   }
    489 };
    490 
    491 /// \brief Provides information a specialization of a member of a class
    492 /// template, which may be a member function, static data member,
    493 /// member class or member enumeration.
    494 class MemberSpecializationInfo {
    495   // The member declaration from which this member was instantiated, and the
    496   // manner in which the instantiation occurred (in the lower two bits).
    497   llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
    498 
    499   // The point at which this member was first instantiated.
    500   SourceLocation PointOfInstantiation;
    501 
    502 public:
    503   explicit
    504   MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
    505                            SourceLocation POI = SourceLocation())
    506     : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
    507     assert(TSK != TSK_Undeclared &&
    508            "Cannot encode undeclared template specializations for members");
    509   }
    510 
    511   /// \brief Retrieve the member declaration from which this member was
    512   /// instantiated.
    513   NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
    514 
    515   /// \brief Determine what kind of template specialization this is.
    516   TemplateSpecializationKind getTemplateSpecializationKind() const {
    517     return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
    518   }
    519 
    520   bool isExplicitSpecialization() const {
    521     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
    522   }
    523 
    524   /// \brief Set the template specialization kind.
    525   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
    526     assert(TSK != TSK_Undeclared &&
    527            "Cannot encode undeclared template specializations for members");
    528     MemberAndTSK.setInt(TSK - 1);
    529   }
    530 
    531   /// \brief Retrieve the first point of instantiation of this member.
    532   /// If the point of instantiation is an invalid location, then this member
    533   /// has not yet been instantiated.
    534   SourceLocation getPointOfInstantiation() const {
    535     return PointOfInstantiation;
    536   }
    537 
    538   /// \brief Set the first point of instantiation.
    539   void setPointOfInstantiation(SourceLocation POI) {
    540     PointOfInstantiation = POI;
    541   }
    542 };
    543 
    544 /// \brief Provides information about a dependent function-template
    545 /// specialization declaration.
    546 ///
    547 /// Since explicit function template specialization and instantiation
    548 /// declarations can only appear in namespace scope, and you can only
    549 /// specialize a member of a fully-specialized class, the only way to
    550 /// get one of these is in a friend declaration like the following:
    551 ///
    552 /// \code
    553 ///   template \<class T> void foo(T);
    554 ///   template \<class T> class A {
    555 ///     friend void foo<>(T);
    556 ///   };
    557 /// \endcode
    558 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8)
    559     DependentFunctionTemplateSpecializationInfo final
    560     : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
    561                                     TemplateArgumentLoc,
    562                                     FunctionTemplateDecl *> {
    563   /// The number of potential template candidates.
    564   unsigned NumTemplates;
    565 
    566   /// The number of template arguments.
    567   unsigned NumArgs;
    568 
    569   /// The locations of the left and right angle brackets.
    570   SourceRange AngleLocs;
    571 
    572   size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
    573     return NumArgs;
    574   }
    575   size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
    576     return NumTemplates;
    577   }
    578 
    579   DependentFunctionTemplateSpecializationInfo(
    580                                  const UnresolvedSetImpl &Templates,
    581                                  const TemplateArgumentListInfo &TemplateArgs);
    582 
    583 public:
    584   static DependentFunctionTemplateSpecializationInfo *
    585   Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
    586          const TemplateArgumentListInfo &TemplateArgs);
    587 
    588   /// \brief Returns the number of function templates that this might
    589   /// be a specialization of.
    590   unsigned getNumTemplates() const { return NumTemplates; }
    591 
    592   /// \brief Returns the i'th template candidate.
    593   FunctionTemplateDecl *getTemplate(unsigned I) const {
    594     assert(I < getNumTemplates() && "template index out of range");
    595     return getTrailingObjects<FunctionTemplateDecl *>()[I];
    596   }
    597 
    598   /// \brief Returns the explicit template arguments that were given.
    599   const TemplateArgumentLoc *getTemplateArgs() const {
    600     return getTrailingObjects<TemplateArgumentLoc>();
    601   }
    602 
    603   /// \brief Returns the number of explicit template arguments that were given.
    604   unsigned getNumTemplateArgs() const { return NumArgs; }
    605 
    606   /// \brief Returns the nth template argument.
    607   const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
    608     assert(I < getNumTemplateArgs() && "template arg index out of range");
    609     return getTemplateArgs()[I];
    610   }
    611 
    612   SourceLocation getLAngleLoc() const {
    613     return AngleLocs.getBegin();
    614   }
    615 
    616   SourceLocation getRAngleLoc() const {
    617     return AngleLocs.getEnd();
    618   }
    619 
    620   friend TrailingObjects;
    621 };
    622 
    623 /// Declaration of a redeclarable template.
    624 class RedeclarableTemplateDecl : public TemplateDecl,
    625                                  public Redeclarable<RedeclarableTemplateDecl>
    626 {
    627   typedef Redeclarable<RedeclarableTemplateDecl> redeclarable_base;
    628   RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
    629     return getNextRedeclaration();
    630   }
    631   RedeclarableTemplateDecl *getPreviousDeclImpl() override {
    632     return getPreviousDecl();
    633   }
    634   RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
    635     return getMostRecentDecl();
    636   }
    637 
    638 protected:
    639   template <typename EntryType> struct SpecEntryTraits {
    640     typedef EntryType DeclType;
    641 
    642     static DeclType *getDecl(EntryType *D) {
    643       return D;
    644     }
    645     static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
    646       return D->getTemplateArgs().asArray();
    647     }
    648   };
    649 
    650   template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
    651             typename DeclType = typename SETraits::DeclType>
    652   struct SpecIterator
    653       : llvm::iterator_adaptor_base<
    654             SpecIterator<EntryType, SETraits, DeclType>,
    655             typename llvm::FoldingSetVector<EntryType>::iterator,
    656             typename std::iterator_traits<typename llvm::FoldingSetVector<
    657                 EntryType>::iterator>::iterator_category,
    658             DeclType *, ptrdiff_t, DeclType *, DeclType *> {
    659     SpecIterator() {}
    660     explicit SpecIterator(
    661         typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
    662         : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
    663 
    664     DeclType *operator*() const {
    665       return SETraits::getDecl(&*this->I)->getMostRecentDecl();
    666     }
    667     DeclType *operator->() const { return **this; }
    668   };
    669 
    670   template <typename EntryType>
    671   static SpecIterator<EntryType>
    672   makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
    673     return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
    674   }
    675 
    676   template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
    677   findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
    678                          ArrayRef<TemplateArgument> Args, void *&InsertPos);
    679 
    680   template <class Derived, class EntryType>
    681   void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
    682                              EntryType *Entry, void *InsertPos);
    683 
    684   struct CommonBase {
    685     CommonBase() : InstantiatedFromMember(nullptr, false) { }
    686 
    687     /// \brief The template from which this was most
    688     /// directly instantiated (or null).
    689     ///
    690     /// The boolean value indicates whether this template
    691     /// was explicitly specialized.
    692     llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
    693       InstantiatedFromMember;
    694   };
    695 
    696   /// \brief Pointer to the common data shared by all declarations of this
    697   /// template.
    698   mutable CommonBase *Common;
    699 
    700   /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
    701   /// the same template. Calling this routine may implicitly allocate memory
    702   /// for the common pointer.
    703   CommonBase *getCommonPtr() const;
    704 
    705   virtual CommonBase *newCommon(ASTContext &C) const = 0;
    706 
    707   // Construct a template decl with name, parameters, and templated element.
    708   RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
    709                            SourceLocation L, DeclarationName Name,
    710                            TemplateParameterList *Params, NamedDecl *Decl)
    711       : TemplateDecl(DK, DC, L, Name, Params, Decl), redeclarable_base(C),
    712         Common() {}
    713 
    714 public:
    715   template <class decl_type> friend class RedeclarableTemplate;
    716 
    717   /// \brief Retrieves the canonical declaration of this template.
    718   RedeclarableTemplateDecl *getCanonicalDecl() override {
    719     return getFirstDecl();
    720   }
    721   const RedeclarableTemplateDecl *getCanonicalDecl() const {
    722     return getFirstDecl();
    723   }
    724 
    725   /// \brief Determines whether this template was a specialization of a
    726   /// member template.
    727   ///
    728   /// In the following example, the function template \c X<int>::f and the
    729   /// member template \c X<int>::Inner are member specializations.
    730   ///
    731   /// \code
    732   /// template<typename T>
    733   /// struct X {
    734   ///   template<typename U> void f(T, U);
    735   ///   template<typename U> struct Inner;
    736   /// };
    737   ///
    738   /// template<> template<typename T>
    739   /// void X<int>::f(int, T);
    740   /// template<> template<typename T>
    741   /// struct X<int>::Inner { /* ... */ };
    742   /// \endcode
    743   bool isMemberSpecialization() const {
    744     return getCommonPtr()->InstantiatedFromMember.getInt();
    745   }
    746 
    747   /// \brief Note that this member template is a specialization.
    748   void setMemberSpecialization() {
    749     assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
    750            "Only member templates can be member template specializations");
    751     getCommonPtr()->InstantiatedFromMember.setInt(true);
    752   }
    753 
    754   /// \brief Retrieve the member template from which this template was
    755   /// instantiated, or NULL if this template was not instantiated from a
    756   /// member template.
    757   ///
    758   /// A template is instantiated from a member template when the member
    759   /// template itself is part of a class template (or member thereof). For
    760   /// example, given
    761   ///
    762   /// \code
    763   /// template<typename T>
    764   /// struct X {
    765   ///   template<typename U> void f(T, U);
    766   /// };
    767   ///
    768   /// void test(X<int> x) {
    769   ///   x.f(1, 'a');
    770   /// };
    771   /// \endcode
    772   ///
    773   /// \c X<int>::f is a FunctionTemplateDecl that describes the function
    774   /// template
    775   ///
    776   /// \code
    777   /// template<typename U> void X<int>::f(int, U);
    778   /// \endcode
    779   ///
    780   /// which was itself created during the instantiation of \c X<int>. Calling
    781   /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
    782   /// retrieve the FunctionTemplateDecl for the original template \c f within
    783   /// the class template \c X<T>, i.e.,
    784   ///
    785   /// \code
    786   /// template<typename T>
    787   /// template<typename U>
    788   /// void X<T>::f(T, U);
    789   /// \endcode
    790   RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
    791     return getCommonPtr()->InstantiatedFromMember.getPointer();
    792   }
    793 
    794   void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
    795     assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
    796     getCommonPtr()->InstantiatedFromMember.setPointer(TD);
    797   }
    798 
    799   typedef redeclarable_base::redecl_range redecl_range;
    800   typedef redeclarable_base::redecl_iterator redecl_iterator;
    801   using redeclarable_base::redecls_begin;
    802   using redeclarable_base::redecls_end;
    803   using redeclarable_base::redecls;
    804   using redeclarable_base::getPreviousDecl;
    805   using redeclarable_base::getMostRecentDecl;
    806   using redeclarable_base::isFirstDecl;
    807 
    808   // Implement isa/cast/dyncast/etc.
    809   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    810   static bool classofKind(Kind K) {
    811     return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
    812   }
    813 
    814   friend class ASTReader;
    815   friend class ASTDeclReader;
    816   friend class ASTDeclWriter;
    817 };
    818 
    819 template <> struct RedeclarableTemplateDecl::
    820 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
    821   typedef FunctionDecl DeclType;
    822 
    823   static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
    824     return I->Function;
    825   }
    826   static ArrayRef<TemplateArgument>
    827   getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
    828     return I->TemplateArguments->asArray();
    829   }
    830 };
    831 
    832 /// Declaration of a template function.
    833 class FunctionTemplateDecl : public RedeclarableTemplateDecl {
    834   static void DeallocateCommon(void *Ptr);
    835 
    836 protected:
    837   /// \brief Data that is common to all of the declarations of a given
    838   /// function template.
    839   struct Common : CommonBase {
    840     Common() : InjectedArgs(), LazySpecializations() { }
    841 
    842     /// \brief The function template specializations for this function
    843     /// template, including explicit specializations and instantiations.
    844     llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
    845 
    846     /// \brief The set of "injected" template arguments used within this
    847     /// function template.
    848     ///
    849     /// This pointer refers to the template arguments (there are as
    850     /// many template arguments as template parameaters) for the function
    851     /// template, and is allocated lazily, since most function templates do not
    852     /// require the use of this information.
    853     TemplateArgument *InjectedArgs;
    854 
    855     /// \brief If non-null, points to an array of specializations known only
    856     /// by their external declaration IDs.
    857     ///
    858     /// The first value in the array is the number of of specializations
    859     /// that follow.
    860     uint32_t *LazySpecializations;
    861   };
    862 
    863   FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
    864                        DeclarationName Name, TemplateParameterList *Params,
    865                        NamedDecl *Decl)
    866       : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
    867                                  Decl) {}
    868 
    869   CommonBase *newCommon(ASTContext &C) const override;
    870 
    871   Common *getCommonPtr() const {
    872     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
    873   }
    874 
    875   friend class FunctionDecl;
    876 
    877   /// \brief Retrieve the set of function template specializations of this
    878   /// function template.
    879   llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
    880   getSpecializations() const;
    881 
    882   /// \brief Add a specialization of this function template.
    883   ///
    884   /// \param InsertPos Insert position in the FoldingSetVector, must have been
    885   ///        retrieved by an earlier call to findSpecialization().
    886   void addSpecialization(FunctionTemplateSpecializationInfo* Info,
    887                          void *InsertPos);
    888 
    889 public:
    890   /// \brief Load any lazily-loaded specializations from the external source.
    891   void LoadLazySpecializations() const;
    892 
    893   /// Get the underlying function declaration of the template.
    894   FunctionDecl *getTemplatedDecl() const {
    895     return static_cast<FunctionDecl*>(TemplatedDecl);
    896   }
    897 
    898   /// Returns whether this template declaration defines the primary
    899   /// pattern.
    900   bool isThisDeclarationADefinition() const {
    901     return getTemplatedDecl()->isThisDeclarationADefinition();
    902   }
    903 
    904   /// \brief Return the specialization with the provided arguments if it exists,
    905   /// otherwise return the insertion point.
    906   FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
    907                                    void *&InsertPos);
    908 
    909   FunctionTemplateDecl *getCanonicalDecl() override {
    910     return cast<FunctionTemplateDecl>(
    911              RedeclarableTemplateDecl::getCanonicalDecl());
    912   }
    913   const FunctionTemplateDecl *getCanonicalDecl() const {
    914     return cast<FunctionTemplateDecl>(
    915              RedeclarableTemplateDecl::getCanonicalDecl());
    916   }
    917 
    918   /// \brief Retrieve the previous declaration of this function template, or
    919   /// NULL if no such declaration exists.
    920   FunctionTemplateDecl *getPreviousDecl() {
    921     return cast_or_null<FunctionTemplateDecl>(
    922              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
    923   }
    924 
    925   /// \brief Retrieve the previous declaration of this function template, or
    926   /// NULL if no such declaration exists.
    927   const FunctionTemplateDecl *getPreviousDecl() const {
    928     return cast_or_null<FunctionTemplateDecl>(
    929        static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
    930   }
    931 
    932   FunctionTemplateDecl *getMostRecentDecl() {
    933     return cast<FunctionTemplateDecl>(
    934         static_cast<RedeclarableTemplateDecl *>(this)
    935             ->getMostRecentDecl());
    936   }
    937   const FunctionTemplateDecl *getMostRecentDecl() const {
    938     return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
    939   }
    940 
    941   FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
    942     return cast_or_null<FunctionTemplateDecl>(
    943              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
    944   }
    945 
    946   typedef SpecIterator<FunctionTemplateSpecializationInfo> spec_iterator;
    947   typedef llvm::iterator_range<spec_iterator> spec_range;
    948 
    949   spec_range specializations() const {
    950     return spec_range(spec_begin(), spec_end());
    951   }
    952   spec_iterator spec_begin() const {
    953     return makeSpecIterator(getSpecializations(), false);
    954   }
    955 
    956   spec_iterator spec_end() const {
    957     return makeSpecIterator(getSpecializations(), true);
    958   }
    959 
    960   /// \brief Retrieve the "injected" template arguments that correspond to the
    961   /// template parameters of this function template.
    962   ///
    963   /// Although the C++ standard has no notion of the "injected" template
    964   /// arguments for a function template, the notion is convenient when
    965   /// we need to perform substitutions inside the definition of a function
    966   /// template.
    967   ArrayRef<TemplateArgument> getInjectedTemplateArgs();
    968 
    969   /// \brief Create a function template node.
    970   static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
    971                                       SourceLocation L,
    972                                       DeclarationName Name,
    973                                       TemplateParameterList *Params,
    974                                       NamedDecl *Decl);
    975 
    976   /// \brief Create an empty function template node.
    977   static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
    978 
    979   // Implement isa/cast/dyncast support
    980   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    981   static bool classofKind(Kind K) { return K == FunctionTemplate; }
    982 
    983   friend class ASTDeclReader;
    984   friend class ASTDeclWriter;
    985 };
    986 
    987 //===----------------------------------------------------------------------===//
    988 // Kinds of Template Parameters
    989 //===----------------------------------------------------------------------===//
    990 
    991 /// \brief Defines the position of a template parameter within a template
    992 /// parameter list.
    993 ///
    994 /// Because template parameter can be listed
    995 /// sequentially for out-of-line template members, each template parameter is
    996 /// given a Depth - the nesting of template parameter scopes - and a Position -
    997 /// the occurrence within the parameter list.
    998 /// This class is inheritedly privately by different kinds of template
    999 /// parameters and is not part of the Decl hierarchy. Just a facility.
   1000 class TemplateParmPosition {
   1001   TemplateParmPosition() = delete;
   1002 
   1003 protected:
   1004   TemplateParmPosition(unsigned D, unsigned P)
   1005     : Depth(D), Position(P)
   1006   { }
   1007 
   1008   // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
   1009   // position? Maybe?
   1010   unsigned Depth;
   1011   unsigned Position;
   1012 
   1013 public:
   1014   /// Get the nesting depth of the template parameter.
   1015   unsigned getDepth() const { return Depth; }
   1016   void setDepth(unsigned D) { Depth = D; }
   1017 
   1018   /// Get the position of the template parameter within its parameter list.
   1019   unsigned getPosition() const { return Position; }
   1020   void setPosition(unsigned P) { Position = P; }
   1021 
   1022   /// Get the index of the template parameter within its parameter list.
   1023   unsigned getIndex() const { return Position; }
   1024 };
   1025 
   1026 /// \brief Declaration of a template type parameter.
   1027 ///
   1028 /// For example, "T" in
   1029 /// \code
   1030 /// template<typename T> class vector;
   1031 /// \endcode
   1032 class TemplateTypeParmDecl : public TypeDecl {
   1033   /// \brief Whether this template type parameter was declaration with
   1034   /// the 'typename' keyword.
   1035   ///
   1036   /// If false, it was declared with the 'class' keyword.
   1037   bool Typename : 1;
   1038 
   1039   /// \brief The default template argument, if any.
   1040   typedef DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>
   1041       DefArgStorage;
   1042   DefArgStorage DefaultArgument;
   1043 
   1044   TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
   1045                        SourceLocation IdLoc, IdentifierInfo *Id,
   1046                        bool Typename)
   1047     : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
   1048       DefaultArgument() { }
   1049 
   1050   /// Sema creates these on the stack during auto type deduction.
   1051   friend class Sema;
   1052 
   1053 public:
   1054   static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
   1055                                       SourceLocation KeyLoc,
   1056                                       SourceLocation NameLoc,
   1057                                       unsigned D, unsigned P,
   1058                                       IdentifierInfo *Id, bool Typename,
   1059                                       bool ParameterPack);
   1060   static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
   1061                                                   unsigned ID);
   1062 
   1063   /// \brief Whether this template type parameter was declared with
   1064   /// the 'typename' keyword.
   1065   ///
   1066   /// If not, it was declared with the 'class' keyword.
   1067   bool wasDeclaredWithTypename() const { return Typename; }
   1068 
   1069   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
   1070 
   1071   /// \brief Determine whether this template parameter has a default
   1072   /// argument.
   1073   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
   1074 
   1075   /// \brief Retrieve the default argument, if any.
   1076   QualType getDefaultArgument() const {
   1077     return DefaultArgument.get()->getType();
   1078   }
   1079 
   1080   /// \brief Retrieves the default argument's source information, if any.
   1081   TypeSourceInfo *getDefaultArgumentInfo() const {
   1082     return DefaultArgument.get();
   1083   }
   1084 
   1085   /// \brief Retrieves the location of the default argument declaration.
   1086   SourceLocation getDefaultArgumentLoc() const;
   1087 
   1088   /// \brief Determines whether the default argument was inherited
   1089   /// from a previous declaration of this template.
   1090   bool defaultArgumentWasInherited() const {
   1091     return DefaultArgument.isInherited();
   1092   }
   1093 
   1094   /// \brief Set the default argument for this template parameter.
   1095   void setDefaultArgument(TypeSourceInfo *DefArg) {
   1096     DefaultArgument.set(DefArg);
   1097   }
   1098   /// \brief Set that this default argument was inherited from another
   1099   /// parameter.
   1100   void setInheritedDefaultArgument(const ASTContext &C,
   1101                                    TemplateTypeParmDecl *Prev) {
   1102     DefaultArgument.setInherited(C, Prev);
   1103   }
   1104 
   1105   /// \brief Removes the default argument of this template parameter.
   1106   void removeDefaultArgument() {
   1107     DefaultArgument.clear();
   1108   }
   1109 
   1110   /// \brief Set whether this template type parameter was declared with
   1111   /// the 'typename' or 'class' keyword.
   1112   void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
   1113 
   1114   /// \brief Retrieve the depth of the template parameter.
   1115   unsigned getDepth() const;
   1116 
   1117   /// \brief Retrieve the index of the template parameter.
   1118   unsigned getIndex() const;
   1119 
   1120   /// \brief Returns whether this is a parameter pack.
   1121   bool isParameterPack() const;
   1122 
   1123   SourceRange getSourceRange() const override LLVM_READONLY;
   1124 
   1125   // Implement isa/cast/dyncast/etc.
   1126   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1127   static bool classofKind(Kind K) { return K == TemplateTypeParm; }
   1128 };
   1129 
   1130 /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
   1131 /// e.g., "Size" in
   1132 /// @code
   1133 /// template<int Size> class array { };
   1134 /// @endcode
   1135 class NonTypeTemplateParmDecl final
   1136     : public DeclaratorDecl,
   1137       protected TemplateParmPosition,
   1138       private llvm::TrailingObjects<NonTypeTemplateParmDecl,
   1139                                     std::pair<QualType, TypeSourceInfo *>> {
   1140   /// \brief The default template argument, if any, and whether or not
   1141   /// it was inherited.
   1142   typedef DefaultArgStorage<NonTypeTemplateParmDecl, Expr*> DefArgStorage;
   1143   DefArgStorage DefaultArgument;
   1144 
   1145   // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
   1146   // down here to save memory.
   1147 
   1148   /// \brief Whether this non-type template parameter is a parameter pack.
   1149   bool ParameterPack;
   1150 
   1151   /// \brief Whether this non-type template parameter is an "expanded"
   1152   /// parameter pack, meaning that its type is a pack expansion and we
   1153   /// already know the set of types that expansion expands to.
   1154   bool ExpandedParameterPack;
   1155 
   1156   /// \brief The number of types in an expanded parameter pack.
   1157   unsigned NumExpandedTypes;
   1158 
   1159   size_t numTrailingObjects(
   1160       OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
   1161     return NumExpandedTypes;
   1162   }
   1163 
   1164   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
   1165                           SourceLocation IdLoc, unsigned D, unsigned P,
   1166                           IdentifierInfo *Id, QualType T,
   1167                           bool ParameterPack, TypeSourceInfo *TInfo)
   1168     : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
   1169       TemplateParmPosition(D, P), ParameterPack(ParameterPack),
   1170       ExpandedParameterPack(false), NumExpandedTypes(0)
   1171   { }
   1172 
   1173   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
   1174                           SourceLocation IdLoc, unsigned D, unsigned P,
   1175                           IdentifierInfo *Id, QualType T,
   1176                           TypeSourceInfo *TInfo,
   1177                           const QualType *ExpandedTypes,
   1178                           unsigned NumExpandedTypes,
   1179                           TypeSourceInfo **ExpandedTInfos);
   1180 
   1181   friend class ASTDeclReader;
   1182   friend TrailingObjects;
   1183 
   1184 public:
   1185   static NonTypeTemplateParmDecl *
   1186   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
   1187          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
   1188          QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
   1189 
   1190   static NonTypeTemplateParmDecl *
   1191   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
   1192          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
   1193          QualType T, TypeSourceInfo *TInfo,
   1194          const QualType *ExpandedTypes, unsigned NumExpandedTypes,
   1195          TypeSourceInfo **ExpandedTInfos);
   1196 
   1197   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1198                                                      unsigned ID);
   1199   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1200                                                      unsigned ID,
   1201                                                      unsigned NumExpandedTypes);
   1202 
   1203   using TemplateParmPosition::getDepth;
   1204   using TemplateParmPosition::setDepth;
   1205   using TemplateParmPosition::getPosition;
   1206   using TemplateParmPosition::setPosition;
   1207   using TemplateParmPosition::getIndex;
   1208 
   1209   SourceRange getSourceRange() const override LLVM_READONLY;
   1210 
   1211   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
   1212 
   1213   /// \brief Determine whether this template parameter has a default
   1214   /// argument.
   1215   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
   1216 
   1217   /// \brief Retrieve the default argument, if any.
   1218   Expr *getDefaultArgument() const { return DefaultArgument.get(); }
   1219 
   1220   /// \brief Retrieve the location of the default argument, if any.
   1221   SourceLocation getDefaultArgumentLoc() const;
   1222 
   1223   /// \brief Determines whether the default argument was inherited
   1224   /// from a previous declaration of this template.
   1225   bool defaultArgumentWasInherited() const {
   1226     return DefaultArgument.isInherited();
   1227   }
   1228 
   1229   /// \brief Set the default argument for this template parameter, and
   1230   /// whether that default argument was inherited from another
   1231   /// declaration.
   1232   void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
   1233   void setInheritedDefaultArgument(const ASTContext &C,
   1234                                    NonTypeTemplateParmDecl *Parm) {
   1235     DefaultArgument.setInherited(C, Parm);
   1236   }
   1237 
   1238   /// \brief Removes the default argument of this template parameter.
   1239   void removeDefaultArgument() { DefaultArgument.clear(); }
   1240 
   1241   /// \brief Whether this parameter is a non-type template parameter pack.
   1242   ///
   1243   /// If the parameter is a parameter pack, the type may be a
   1244   /// \c PackExpansionType. In the following example, the \c Dims parameter
   1245   /// is a parameter pack (whose type is 'unsigned').
   1246   ///
   1247   /// \code
   1248   /// template<typename T, unsigned ...Dims> struct multi_array;
   1249   /// \endcode
   1250   bool isParameterPack() const { return ParameterPack; }
   1251 
   1252   /// \brief Whether this parameter pack is a pack expansion.
   1253   ///
   1254   /// A non-type template parameter pack is a pack expansion if its type
   1255   /// contains an unexpanded parameter pack. In this case, we will have
   1256   /// built a PackExpansionType wrapping the type.
   1257   bool isPackExpansion() const {
   1258     return ParameterPack && getType()->getAs<PackExpansionType>();
   1259   }
   1260 
   1261   /// \brief Whether this parameter is a non-type template parameter pack
   1262   /// that has a known list of different types at different positions.
   1263   ///
   1264   /// A parameter pack is an expanded parameter pack when the original
   1265   /// parameter pack's type was itself a pack expansion, and that expansion
   1266   /// has already been expanded. For example, given:
   1267   ///
   1268   /// \code
   1269   /// template<typename ...Types>
   1270   /// struct X {
   1271   ///   template<Types ...Values>
   1272   ///   struct Y { /* ... */ };
   1273   /// };
   1274   /// \endcode
   1275   ///
   1276   /// The parameter pack \c Values has a \c PackExpansionType as its type,
   1277   /// which expands \c Types. When \c Types is supplied with template arguments
   1278   /// by instantiating \c X, the instantiation of \c Values becomes an
   1279   /// expanded parameter pack. For example, instantiating
   1280   /// \c X<int, unsigned int> results in \c Values being an expanded parameter
   1281   /// pack with expansion types \c int and \c unsigned int.
   1282   ///
   1283   /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
   1284   /// return the expansion types.
   1285   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
   1286 
   1287   /// \brief Retrieves the number of expansion types in an expanded parameter
   1288   /// pack.
   1289   unsigned getNumExpansionTypes() const {
   1290     assert(ExpandedParameterPack && "Not an expansion parameter pack");
   1291     return NumExpandedTypes;
   1292   }
   1293 
   1294   /// \brief Retrieve a particular expansion type within an expanded parameter
   1295   /// pack.
   1296   QualType getExpansionType(unsigned I) const {
   1297     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
   1298     auto TypesAndInfos =
   1299         getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
   1300     return TypesAndInfos[I].first;
   1301   }
   1302 
   1303   /// \brief Retrieve a particular expansion type source info within an
   1304   /// expanded parameter pack.
   1305   TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
   1306     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
   1307     auto TypesAndInfos =
   1308         getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
   1309     return TypesAndInfos[I].second;
   1310   }
   1311 
   1312   // Implement isa/cast/dyncast/etc.
   1313   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1314   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
   1315 };
   1316 
   1317 /// TemplateTemplateParmDecl - Declares a template template parameter,
   1318 /// e.g., "T" in
   1319 /// @code
   1320 /// template <template <typename> class T> class container { };
   1321 /// @endcode
   1322 /// A template template parameter is a TemplateDecl because it defines the
   1323 /// name of a template and the template parameters allowable for substitution.
   1324 class TemplateTemplateParmDecl final
   1325     : public TemplateDecl,
   1326       protected TemplateParmPosition,
   1327       private llvm::TrailingObjects<TemplateTemplateParmDecl,
   1328                                     TemplateParameterList *> {
   1329   void anchor() override;
   1330 
   1331   /// \brief The default template argument, if any.
   1332   typedef DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>
   1333       DefArgStorage;
   1334   DefArgStorage DefaultArgument;
   1335 
   1336   /// \brief Whether this parameter is a parameter pack.
   1337   bool ParameterPack;
   1338 
   1339   /// \brief Whether this template template parameter is an "expanded"
   1340   /// parameter pack, meaning that it is a pack expansion and we
   1341   /// already know the set of template parameters that expansion expands to.
   1342   bool ExpandedParameterPack;
   1343 
   1344   /// \brief The number of parameters in an expanded parameter pack.
   1345   unsigned NumExpandedParams;
   1346 
   1347   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
   1348                            unsigned D, unsigned P, bool ParameterPack,
   1349                            IdentifierInfo *Id, TemplateParameterList *Params)
   1350     : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
   1351       TemplateParmPosition(D, P), ParameterPack(ParameterPack),
   1352       ExpandedParameterPack(false), NumExpandedParams(0)
   1353     { }
   1354 
   1355   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
   1356                            unsigned D, unsigned P,
   1357                            IdentifierInfo *Id, TemplateParameterList *Params,
   1358                            unsigned NumExpansions,
   1359                            TemplateParameterList * const *Expansions);
   1360 
   1361 public:
   1362   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
   1363                                           SourceLocation L, unsigned D,
   1364                                           unsigned P, bool ParameterPack,
   1365                                           IdentifierInfo *Id,
   1366                                           TemplateParameterList *Params);
   1367   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
   1368                                           SourceLocation L, unsigned D,
   1369                                           unsigned P,
   1370                                           IdentifierInfo *Id,
   1371                                           TemplateParameterList *Params,
   1372                                  ArrayRef<TemplateParameterList *> Expansions);
   1373 
   1374   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1375                                                       unsigned ID);
   1376   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1377                                                       unsigned ID,
   1378                                                       unsigned NumExpansions);
   1379 
   1380   using TemplateParmPosition::getDepth;
   1381   using TemplateParmPosition::getPosition;
   1382   using TemplateParmPosition::getIndex;
   1383 
   1384   /// \brief Whether this template template parameter is a template
   1385   /// parameter pack.
   1386   ///
   1387   /// \code
   1388   /// template<template <class T> ...MetaFunctions> struct Apply;
   1389   /// \endcode
   1390   bool isParameterPack() const { return ParameterPack; }
   1391 
   1392   /// \brief Whether this parameter pack is a pack expansion.
   1393   ///
   1394   /// A template template parameter pack is a pack expansion if its template
   1395   /// parameter list contains an unexpanded parameter pack.
   1396   bool isPackExpansion() const {
   1397     return ParameterPack &&
   1398            getTemplateParameters()->containsUnexpandedParameterPack();
   1399   }
   1400 
   1401   /// \brief Whether this parameter is a template template parameter pack that
   1402   /// has a known list of different template parameter lists at different
   1403   /// positions.
   1404   ///
   1405   /// A parameter pack is an expanded parameter pack when the original parameter
   1406   /// pack's template parameter list was itself a pack expansion, and that
   1407   /// expansion has already been expanded. For exampe, given:
   1408   ///
   1409   /// \code
   1410   /// template<typename...Types> struct Outer {
   1411   ///   template<template<Types> class...Templates> struct Inner;
   1412   /// };
   1413   /// \endcode
   1414   ///
   1415   /// The parameter pack \c Templates is a pack expansion, which expands the
   1416   /// pack \c Types. When \c Types is supplied with template arguments by
   1417   /// instantiating \c Outer, the instantiation of \c Templates is an expanded
   1418   /// parameter pack.
   1419   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
   1420 
   1421   /// \brief Retrieves the number of expansion template parameters in
   1422   /// an expanded parameter pack.
   1423   unsigned getNumExpansionTemplateParameters() const {
   1424     assert(ExpandedParameterPack && "Not an expansion parameter pack");
   1425     return NumExpandedParams;
   1426   }
   1427 
   1428   /// \brief Retrieve a particular expansion type within an expanded parameter
   1429   /// pack.
   1430   TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
   1431     assert(I < NumExpandedParams && "Out-of-range expansion type index");
   1432     return getTrailingObjects<TemplateParameterList *>()[I];
   1433   }
   1434 
   1435   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
   1436 
   1437   /// \brief Determine whether this template parameter has a default
   1438   /// argument.
   1439   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
   1440 
   1441   /// \brief Retrieve the default argument, if any.
   1442   const TemplateArgumentLoc &getDefaultArgument() const {
   1443     static const TemplateArgumentLoc None;
   1444     return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
   1445   }
   1446 
   1447   /// \brief Retrieve the location of the default argument, if any.
   1448   SourceLocation getDefaultArgumentLoc() const;
   1449 
   1450   /// \brief Determines whether the default argument was inherited
   1451   /// from a previous declaration of this template.
   1452   bool defaultArgumentWasInherited() const {
   1453     return DefaultArgument.isInherited();
   1454   }
   1455 
   1456   /// \brief Set the default argument for this template parameter, and
   1457   /// whether that default argument was inherited from another
   1458   /// declaration.
   1459   void setDefaultArgument(const ASTContext &C,
   1460                           const TemplateArgumentLoc &DefArg);
   1461   void setInheritedDefaultArgument(const ASTContext &C,
   1462                                    TemplateTemplateParmDecl *Prev) {
   1463     DefaultArgument.setInherited(C, Prev);
   1464   }
   1465 
   1466   /// \brief Removes the default argument of this template parameter.
   1467   void removeDefaultArgument() { DefaultArgument.clear(); }
   1468 
   1469   SourceRange getSourceRange() const override LLVM_READONLY {
   1470     SourceLocation End = getLocation();
   1471     if (hasDefaultArgument() && !defaultArgumentWasInherited())
   1472       End = getDefaultArgument().getSourceRange().getEnd();
   1473     return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
   1474   }
   1475 
   1476   // Implement isa/cast/dyncast/etc.
   1477   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1478   static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
   1479 
   1480   friend class ASTDeclReader;
   1481   friend class ASTDeclWriter;
   1482   friend TrailingObjects;
   1483 };
   1484 
   1485 /// \brief Represents the builtin template declaration which is used to
   1486 /// implement __make_integer_seq.  It serves no real purpose beyond existing as
   1487 /// a place to hold template parameters.
   1488 class BuiltinTemplateDecl : public TemplateDecl {
   1489   void anchor() override;
   1490 
   1491   BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
   1492                       DeclarationName Name, BuiltinTemplateKind BTK);
   1493 
   1494   BuiltinTemplateKind BTK;
   1495 
   1496 public:
   1497   // Implement isa/cast/dyncast support
   1498   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1499   static bool classofKind(Kind K) { return K == BuiltinTemplate; }
   1500 
   1501   static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
   1502                                      DeclarationName Name,
   1503                                      BuiltinTemplateKind BTK) {
   1504     return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
   1505   }
   1506 
   1507   SourceRange getSourceRange() const override LLVM_READONLY {
   1508     return SourceRange();
   1509   }
   1510 
   1511   BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
   1512 };
   1513 
   1514 /// \brief Represents a class template specialization, which refers to
   1515 /// a class template with a given set of template arguments.
   1516 ///
   1517 /// Class template specializations represent both explicit
   1518 /// specialization of class templates, as in the example below, and
   1519 /// implicit instantiations of class templates.
   1520 ///
   1521 /// \code
   1522 /// template<typename T> class array;
   1523 ///
   1524 /// template<>
   1525 /// class array<bool> { }; // class template specialization array<bool>
   1526 /// \endcode
   1527 class ClassTemplateSpecializationDecl
   1528   : public CXXRecordDecl, public llvm::FoldingSetNode {
   1529 
   1530   /// \brief Structure that stores information about a class template
   1531   /// specialization that was instantiated from a class template partial
   1532   /// specialization.
   1533   struct SpecializedPartialSpecialization {
   1534     /// \brief The class template partial specialization from which this
   1535     /// class template specialization was instantiated.
   1536     ClassTemplatePartialSpecializationDecl *PartialSpecialization;
   1537 
   1538     /// \brief The template argument list deduced for the class template
   1539     /// partial specialization itself.
   1540     const TemplateArgumentList *TemplateArgs;
   1541   };
   1542 
   1543   /// \brief The template that this specialization specializes
   1544   llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
   1545     SpecializedTemplate;
   1546 
   1547   /// \brief Further info for explicit template specialization/instantiation.
   1548   struct ExplicitSpecializationInfo {
   1549     /// \brief The type-as-written.
   1550     TypeSourceInfo *TypeAsWritten;
   1551     /// \brief The location of the extern keyword.
   1552     SourceLocation ExternLoc;
   1553     /// \brief The location of the template keyword.
   1554     SourceLocation TemplateKeywordLoc;
   1555 
   1556     ExplicitSpecializationInfo()
   1557       : TypeAsWritten(nullptr), ExternLoc(), TemplateKeywordLoc() {}
   1558   };
   1559 
   1560   /// \brief Further info for explicit template specialization/instantiation.
   1561   /// Does not apply to implicit specializations.
   1562   ExplicitSpecializationInfo *ExplicitInfo;
   1563 
   1564   /// \brief The template arguments used to describe this specialization.
   1565   const TemplateArgumentList *TemplateArgs;
   1566 
   1567   /// \brief The point where this template was instantiated (if any)
   1568   SourceLocation PointOfInstantiation;
   1569 
   1570   /// \brief The kind of specialization this declaration refers to.
   1571   /// Really a value of type TemplateSpecializationKind.
   1572   unsigned SpecializationKind : 3;
   1573 
   1574 protected:
   1575   ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
   1576                                   DeclContext *DC, SourceLocation StartLoc,
   1577                                   SourceLocation IdLoc,
   1578                                   ClassTemplateDecl *SpecializedTemplate,
   1579                                   const TemplateArgument *Args,
   1580                                   unsigned NumArgs,
   1581                                   ClassTemplateSpecializationDecl *PrevDecl);
   1582 
   1583   explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
   1584 
   1585 public:
   1586   static ClassTemplateSpecializationDecl *
   1587   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
   1588          SourceLocation StartLoc, SourceLocation IdLoc,
   1589          ClassTemplateDecl *SpecializedTemplate,
   1590          const TemplateArgument *Args,
   1591          unsigned NumArgs,
   1592          ClassTemplateSpecializationDecl *PrevDecl);
   1593   static ClassTemplateSpecializationDecl *
   1594   CreateDeserialized(ASTContext &C, unsigned ID);
   1595 
   1596   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
   1597                             bool Qualified) const override;
   1598 
   1599   // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
   1600   // different "most recent" declaration from this function for the same
   1601   // declaration, because we don't override getMostRecentDeclImpl(). But
   1602   // it's not clear that we should override that, because the most recent
   1603   // declaration as a CXXRecordDecl sometimes is the injected-class-name.
   1604   ClassTemplateSpecializationDecl *getMostRecentDecl() {
   1605     CXXRecordDecl *Recent = static_cast<CXXRecordDecl *>(
   1606                               this)->getMostRecentDecl();
   1607     while (!isa<ClassTemplateSpecializationDecl>(Recent)) {
   1608       // FIXME: Does injected class name need to be in the redeclarations chain?
   1609       assert(Recent->isInjectedClassName() && Recent->getPreviousDecl());
   1610       Recent = Recent->getPreviousDecl();
   1611     }
   1612     return cast<ClassTemplateSpecializationDecl>(Recent);
   1613   }
   1614 
   1615   /// \brief Retrieve the template that this specialization specializes.
   1616   ClassTemplateDecl *getSpecializedTemplate() const;
   1617 
   1618   /// \brief Retrieve the template arguments of the class template
   1619   /// specialization.
   1620   const TemplateArgumentList &getTemplateArgs() const {
   1621     return *TemplateArgs;
   1622   }
   1623 
   1624   /// \brief Determine the kind of specialization that this
   1625   /// declaration represents.
   1626   TemplateSpecializationKind getSpecializationKind() const {
   1627     return static_cast<TemplateSpecializationKind>(SpecializationKind);
   1628   }
   1629 
   1630   bool isExplicitSpecialization() const {
   1631     return getSpecializationKind() == TSK_ExplicitSpecialization;
   1632   }
   1633 
   1634   /// \brief True if this declaration is an explicit specialization,
   1635   /// explicit instantiation declaration, or explicit instantiation
   1636   /// definition.
   1637   bool isExplicitInstantiationOrSpecialization() const {
   1638     return isTemplateExplicitInstantiationOrSpecialization(
   1639         getTemplateSpecializationKind());
   1640   }
   1641 
   1642   void setSpecializationKind(TemplateSpecializationKind TSK) {
   1643     SpecializationKind = TSK;
   1644   }
   1645 
   1646   /// \brief Get the point of instantiation (if any), or null if none.
   1647   SourceLocation getPointOfInstantiation() const {
   1648     return PointOfInstantiation;
   1649   }
   1650 
   1651   void setPointOfInstantiation(SourceLocation Loc) {
   1652     assert(Loc.isValid() && "point of instantiation must be valid!");
   1653     PointOfInstantiation = Loc;
   1654   }
   1655 
   1656   /// \brief If this class template specialization is an instantiation of
   1657   /// a template (rather than an explicit specialization), return the
   1658   /// class template or class template partial specialization from which it
   1659   /// was instantiated.
   1660   llvm::PointerUnion<ClassTemplateDecl *,
   1661                      ClassTemplatePartialSpecializationDecl *>
   1662   getInstantiatedFrom() const {
   1663     if (!isTemplateInstantiation(getSpecializationKind()))
   1664       return llvm::PointerUnion<ClassTemplateDecl *,
   1665                                 ClassTemplatePartialSpecializationDecl *>();
   1666 
   1667     return getSpecializedTemplateOrPartial();
   1668   }
   1669 
   1670   /// \brief Retrieve the class template or class template partial
   1671   /// specialization which was specialized by this.
   1672   llvm::PointerUnion<ClassTemplateDecl *,
   1673                      ClassTemplatePartialSpecializationDecl *>
   1674   getSpecializedTemplateOrPartial() const {
   1675     if (SpecializedPartialSpecialization *PartialSpec
   1676           = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
   1677       return PartialSpec->PartialSpecialization;
   1678 
   1679     return SpecializedTemplate.get<ClassTemplateDecl*>();
   1680   }
   1681 
   1682   /// \brief Retrieve the set of template arguments that should be used
   1683   /// to instantiate members of the class template or class template partial
   1684   /// specialization from which this class template specialization was
   1685   /// instantiated.
   1686   ///
   1687   /// \returns For a class template specialization instantiated from the primary
   1688   /// template, this function will return the same template arguments as
   1689   /// getTemplateArgs(). For a class template specialization instantiated from
   1690   /// a class template partial specialization, this function will return the
   1691   /// deduced template arguments for the class template partial specialization
   1692   /// itself.
   1693   const TemplateArgumentList &getTemplateInstantiationArgs() const {
   1694     if (SpecializedPartialSpecialization *PartialSpec
   1695         = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
   1696       return *PartialSpec->TemplateArgs;
   1697 
   1698     return getTemplateArgs();
   1699   }
   1700 
   1701   /// \brief Note that this class template specialization is actually an
   1702   /// instantiation of the given class template partial specialization whose
   1703   /// template arguments have been deduced.
   1704   void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
   1705                           const TemplateArgumentList *TemplateArgs) {
   1706     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
   1707            "Already set to a class template partial specialization!");
   1708     SpecializedPartialSpecialization *PS
   1709       = new (getASTContext()) SpecializedPartialSpecialization();
   1710     PS->PartialSpecialization = PartialSpec;
   1711     PS->TemplateArgs = TemplateArgs;
   1712     SpecializedTemplate = PS;
   1713   }
   1714 
   1715   /// \brief Note that this class template specialization is an instantiation
   1716   /// of the given class template.
   1717   void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
   1718     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
   1719            "Previously set to a class template partial specialization!");
   1720     SpecializedTemplate = TemplDecl;
   1721   }
   1722 
   1723   /// \brief Sets the type of this specialization as it was written by
   1724   /// the user. This will be a class template specialization type.
   1725   void setTypeAsWritten(TypeSourceInfo *T) {
   1726     if (!ExplicitInfo)
   1727       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   1728     ExplicitInfo->TypeAsWritten = T;
   1729   }
   1730   /// \brief Gets the type of this specialization as it was written by
   1731   /// the user, if it was so written.
   1732   TypeSourceInfo *getTypeAsWritten() const {
   1733     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
   1734   }
   1735 
   1736   /// \brief Gets the location of the extern keyword, if present.
   1737   SourceLocation getExternLoc() const {
   1738     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
   1739   }
   1740   /// \brief Sets the location of the extern keyword.
   1741   void setExternLoc(SourceLocation Loc) {
   1742     if (!ExplicitInfo)
   1743       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   1744     ExplicitInfo->ExternLoc = Loc;
   1745   }
   1746 
   1747   /// \brief Sets the location of the template keyword.
   1748   void setTemplateKeywordLoc(SourceLocation Loc) {
   1749     if (!ExplicitInfo)
   1750       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   1751     ExplicitInfo->TemplateKeywordLoc = Loc;
   1752   }
   1753   /// \brief Gets the location of the template keyword, if present.
   1754   SourceLocation getTemplateKeywordLoc() const {
   1755     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
   1756   }
   1757 
   1758   SourceRange getSourceRange() const override LLVM_READONLY;
   1759 
   1760   void Profile(llvm::FoldingSetNodeID &ID) const {
   1761     Profile(ID, TemplateArgs->asArray(), getASTContext());
   1762   }
   1763 
   1764   static void
   1765   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
   1766           ASTContext &Context) {
   1767     ID.AddInteger(TemplateArgs.size());
   1768     for (unsigned Arg = 0; Arg != TemplateArgs.size(); ++Arg)
   1769       TemplateArgs[Arg].Profile(ID, Context);
   1770   }
   1771 
   1772   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1773   static bool classofKind(Kind K) {
   1774     return K >= firstClassTemplateSpecialization &&
   1775            K <= lastClassTemplateSpecialization;
   1776   }
   1777 
   1778   friend class ASTDeclReader;
   1779   friend class ASTDeclWriter;
   1780 };
   1781 
   1782 class ClassTemplatePartialSpecializationDecl
   1783   : public ClassTemplateSpecializationDecl {
   1784   void anchor() override;
   1785 
   1786   /// \brief The list of template parameters
   1787   TemplateParameterList* TemplateParams;
   1788 
   1789   /// \brief The source info for the template arguments as written.
   1790   /// FIXME: redundant with TypeAsWritten?
   1791   const ASTTemplateArgumentListInfo *ArgsAsWritten;
   1792 
   1793   /// \brief The class template partial specialization from which this
   1794   /// class template partial specialization was instantiated.
   1795   ///
   1796   /// The boolean value will be true to indicate that this class template
   1797   /// partial specialization was specialized at this level.
   1798   llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
   1799       InstantiatedFromMember;
   1800 
   1801   ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
   1802                                          DeclContext *DC,
   1803                                          SourceLocation StartLoc,
   1804                                          SourceLocation IdLoc,
   1805                                          TemplateParameterList *Params,
   1806                                          ClassTemplateDecl *SpecializedTemplate,
   1807                                          const TemplateArgument *Args,
   1808                                          unsigned NumArgs,
   1809                                const ASTTemplateArgumentListInfo *ArgsAsWritten,
   1810                                ClassTemplatePartialSpecializationDecl *PrevDecl);
   1811 
   1812   ClassTemplatePartialSpecializationDecl(ASTContext &C)
   1813     : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
   1814       TemplateParams(nullptr), ArgsAsWritten(nullptr),
   1815       InstantiatedFromMember(nullptr, false) {}
   1816 
   1817 public:
   1818   static ClassTemplatePartialSpecializationDecl *
   1819   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
   1820          SourceLocation StartLoc, SourceLocation IdLoc,
   1821          TemplateParameterList *Params,
   1822          ClassTemplateDecl *SpecializedTemplate,
   1823          const TemplateArgument *Args,
   1824          unsigned NumArgs,
   1825          const TemplateArgumentListInfo &ArgInfos,
   1826          QualType CanonInjectedType,
   1827          ClassTemplatePartialSpecializationDecl *PrevDecl);
   1828 
   1829   static ClassTemplatePartialSpecializationDecl *
   1830   CreateDeserialized(ASTContext &C, unsigned ID);
   1831 
   1832   ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
   1833     return cast<ClassTemplatePartialSpecializationDecl>(
   1834              static_cast<ClassTemplateSpecializationDecl *>(
   1835                this)->getMostRecentDecl());
   1836   }
   1837 
   1838   /// Get the list of template parameters
   1839   TemplateParameterList *getTemplateParameters() const {
   1840     return TemplateParams;
   1841   }
   1842 
   1843   /// Get the template arguments as written.
   1844   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
   1845     return ArgsAsWritten;
   1846   }
   1847 
   1848   /// \brief Retrieve the member class template partial specialization from
   1849   /// which this particular class template partial specialization was
   1850   /// instantiated.
   1851   ///
   1852   /// \code
   1853   /// template<typename T>
   1854   /// struct Outer {
   1855   ///   template<typename U> struct Inner;
   1856   ///   template<typename U> struct Inner<U*> { }; // #1
   1857   /// };
   1858   ///
   1859   /// Outer<float>::Inner<int*> ii;
   1860   /// \endcode
   1861   ///
   1862   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
   1863   /// end up instantiating the partial specialization
   1864   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
   1865   /// template partial specialization \c Outer<T>::Inner<U*>. Given
   1866   /// \c Outer<float>::Inner<U*>, this function would return
   1867   /// \c Outer<T>::Inner<U*>.
   1868   ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
   1869     const ClassTemplatePartialSpecializationDecl *First =
   1870         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
   1871     return First->InstantiatedFromMember.getPointer();
   1872   }
   1873 
   1874   void setInstantiatedFromMember(
   1875                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
   1876     ClassTemplatePartialSpecializationDecl *First =
   1877         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
   1878     First->InstantiatedFromMember.setPointer(PartialSpec);
   1879   }
   1880 
   1881   /// \brief Determines whether this class template partial specialization
   1882   /// template was a specialization of a member partial specialization.
   1883   ///
   1884   /// In the following example, the member template partial specialization
   1885   /// \c X<int>::Inner<T*> is a member specialization.
   1886   ///
   1887   /// \code
   1888   /// template<typename T>
   1889   /// struct X {
   1890   ///   template<typename U> struct Inner;
   1891   ///   template<typename U> struct Inner<U*>;
   1892   /// };
   1893   ///
   1894   /// template<> template<typename T>
   1895   /// struct X<int>::Inner<T*> { /* ... */ };
   1896   /// \endcode
   1897   bool isMemberSpecialization() {
   1898     ClassTemplatePartialSpecializationDecl *First =
   1899         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
   1900     return First->InstantiatedFromMember.getInt();
   1901   }
   1902 
   1903   /// \brief Note that this member template is a specialization.
   1904   void setMemberSpecialization() {
   1905     ClassTemplatePartialSpecializationDecl *First =
   1906         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
   1907     assert(First->InstantiatedFromMember.getPointer() &&
   1908            "Only member templates can be member template specializations");
   1909     return First->InstantiatedFromMember.setInt(true);
   1910   }
   1911 
   1912   /// Retrieves the injected specialization type for this partial
   1913   /// specialization.  This is not the same as the type-decl-type for
   1914   /// this partial specialization, which is an InjectedClassNameType.
   1915   QualType getInjectedSpecializationType() const {
   1916     assert(getTypeForDecl() && "partial specialization has no type set!");
   1917     return cast<InjectedClassNameType>(getTypeForDecl())
   1918              ->getInjectedSpecializationType();
   1919   }
   1920 
   1921   // FIXME: Add Profile support!
   1922 
   1923   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1924   static bool classofKind(Kind K) {
   1925     return K == ClassTemplatePartialSpecialization;
   1926   }
   1927 
   1928   friend class ASTDeclReader;
   1929   friend class ASTDeclWriter;
   1930 };
   1931 
   1932 /// Declaration of a class template.
   1933 class ClassTemplateDecl : public RedeclarableTemplateDecl {
   1934   static void DeallocateCommon(void *Ptr);
   1935 
   1936 protected:
   1937   /// \brief Data that is common to all of the declarations of a given
   1938   /// class template.
   1939   struct Common : CommonBase {
   1940     Common() : LazySpecializations() { }
   1941 
   1942     /// \brief The class template specializations for this class
   1943     /// template, including explicit specializations and instantiations.
   1944     llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
   1945 
   1946     /// \brief The class template partial specializations for this class
   1947     /// template.
   1948     llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
   1949       PartialSpecializations;
   1950 
   1951     /// \brief The injected-class-name type for this class template.
   1952     QualType InjectedClassNameType;
   1953 
   1954     /// \brief If non-null, points to an array of specializations (including
   1955     /// partial specializations) known only by their external declaration IDs.
   1956     ///
   1957     /// The first value in the array is the number of of specializations/
   1958     /// partial specializations that follow.
   1959     uint32_t *LazySpecializations;
   1960   };
   1961 
   1962   /// \brief Retrieve the set of specializations of this class template.
   1963   llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
   1964   getSpecializations() const;
   1965 
   1966   /// \brief Retrieve the set of partial specializations of this class
   1967   /// template.
   1968   llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
   1969   getPartialSpecializations();
   1970 
   1971   ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
   1972                     DeclarationName Name, TemplateParameterList *Params,
   1973                     NamedDecl *Decl)
   1974       : RedeclarableTemplateDecl(ClassTemplate, C, DC, L, Name, Params, Decl) {}
   1975 
   1976   CommonBase *newCommon(ASTContext &C) const override;
   1977 
   1978   Common *getCommonPtr() const {
   1979     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
   1980   }
   1981 
   1982 public:
   1983   /// \brief Load any lazily-loaded specializations from the external source.
   1984   void LoadLazySpecializations() const;
   1985 
   1986   /// \brief Get the underlying class declarations of the template.
   1987   CXXRecordDecl *getTemplatedDecl() const {
   1988     return static_cast<CXXRecordDecl *>(TemplatedDecl);
   1989   }
   1990 
   1991   /// \brief Returns whether this template declaration defines the primary
   1992   /// class pattern.
   1993   bool isThisDeclarationADefinition() const {
   1994     return getTemplatedDecl()->isThisDeclarationADefinition();
   1995   }
   1996 
   1997   /// \brief Create a class template node.
   1998   static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
   1999                                    SourceLocation L,
   2000                                    DeclarationName Name,
   2001                                    TemplateParameterList *Params,
   2002                                    NamedDecl *Decl,
   2003                                    ClassTemplateDecl *PrevDecl);
   2004 
   2005   /// \brief Create an empty class template node.
   2006   static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2007 
   2008   /// \brief Return the specialization with the provided arguments if it exists,
   2009   /// otherwise return the insertion point.
   2010   ClassTemplateSpecializationDecl *
   2011   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
   2012 
   2013   /// \brief Insert the specified specialization knowing that it is not already
   2014   /// in. InsertPos must be obtained from findSpecialization.
   2015   void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
   2016 
   2017   ClassTemplateDecl *getCanonicalDecl() override {
   2018     return cast<ClassTemplateDecl>(
   2019              RedeclarableTemplateDecl::getCanonicalDecl());
   2020   }
   2021   const ClassTemplateDecl *getCanonicalDecl() const {
   2022     return cast<ClassTemplateDecl>(
   2023              RedeclarableTemplateDecl::getCanonicalDecl());
   2024   }
   2025 
   2026   /// \brief Retrieve the previous declaration of this class template, or
   2027   /// NULL if no such declaration exists.
   2028   ClassTemplateDecl *getPreviousDecl() {
   2029     return cast_or_null<ClassTemplateDecl>(
   2030              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
   2031   }
   2032 
   2033   /// \brief Retrieve the previous declaration of this class template, or
   2034   /// NULL if no such declaration exists.
   2035   const ClassTemplateDecl *getPreviousDecl() const {
   2036     return cast_or_null<ClassTemplateDecl>(
   2037              static_cast<const RedeclarableTemplateDecl *>(
   2038                this)->getPreviousDecl());
   2039   }
   2040 
   2041   ClassTemplateDecl *getMostRecentDecl() {
   2042     return cast<ClassTemplateDecl>(
   2043         static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
   2044   }
   2045   const ClassTemplateDecl *getMostRecentDecl() const {
   2046     return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
   2047   }
   2048 
   2049   ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
   2050     return cast_or_null<ClassTemplateDecl>(
   2051              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
   2052   }
   2053 
   2054   /// \brief Return the partial specialization with the provided arguments if it
   2055   /// exists, otherwise return the insertion point.
   2056   ClassTemplatePartialSpecializationDecl *
   2057   findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
   2058 
   2059   /// \brief Insert the specified partial specialization knowing that it is not
   2060   /// already in. InsertPos must be obtained from findPartialSpecialization.
   2061   void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
   2062                                 void *InsertPos);
   2063 
   2064   /// \brief Retrieve the partial specializations as an ordered list.
   2065   void getPartialSpecializations(
   2066           SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
   2067 
   2068   /// \brief Find a class template partial specialization with the given
   2069   /// type T.
   2070   ///
   2071   /// \param T a dependent type that names a specialization of this class
   2072   /// template.
   2073   ///
   2074   /// \returns the class template partial specialization that exactly matches
   2075   /// the type \p T, or NULL if no such partial specialization exists.
   2076   ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
   2077 
   2078   /// \brief Find a class template partial specialization which was instantiated
   2079   /// from the given member partial specialization.
   2080   ///
   2081   /// \param D a member class template partial specialization.
   2082   ///
   2083   /// \returns the class template partial specialization which was instantiated
   2084   /// from the given member partial specialization, or NULL if no such partial
   2085   /// specialization exists.
   2086   ClassTemplatePartialSpecializationDecl *
   2087   findPartialSpecInstantiatedFromMember(
   2088                                      ClassTemplatePartialSpecializationDecl *D);
   2089 
   2090   /// \brief Retrieve the template specialization type of the
   2091   /// injected-class-name for this class template.
   2092   ///
   2093   /// The injected-class-name for a class template \c X is \c
   2094   /// X<template-args>, where \c template-args is formed from the
   2095   /// template arguments that correspond to the template parameters of
   2096   /// \c X. For example:
   2097   ///
   2098   /// \code
   2099   /// template<typename T, int N>
   2100   /// struct array {
   2101   ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
   2102   /// };
   2103   /// \endcode
   2104   QualType getInjectedClassNameSpecialization();
   2105 
   2106   typedef SpecIterator<ClassTemplateSpecializationDecl> spec_iterator;
   2107   typedef llvm::iterator_range<spec_iterator> spec_range;
   2108 
   2109   spec_range specializations() const {
   2110     return spec_range(spec_begin(), spec_end());
   2111   }
   2112 
   2113   spec_iterator spec_begin() const {
   2114     return makeSpecIterator(getSpecializations(), false);
   2115   }
   2116 
   2117   spec_iterator spec_end() const {
   2118     return makeSpecIterator(getSpecializations(), true);
   2119   }
   2120 
   2121   // Implement isa/cast/dyncast support
   2122   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2123   static bool classofKind(Kind K) { return K == ClassTemplate; }
   2124 
   2125   friend class ASTDeclReader;
   2126   friend class ASTDeclWriter;
   2127 };
   2128 
   2129 /// \brief Declaration of a friend template.
   2130 ///
   2131 /// For example:
   2132 /// \code
   2133 /// template \<typename T> class A {
   2134 ///   friend class MyVector<T>; // not a friend template
   2135 ///   template \<typename U> friend class B; // not a friend template
   2136 ///   template \<typename U> friend class Foo<T>::Nested; // friend template
   2137 /// };
   2138 /// \endcode
   2139 ///
   2140 /// \note This class is not currently in use.  All of the above
   2141 /// will yield a FriendDecl, not a FriendTemplateDecl.
   2142 class FriendTemplateDecl : public Decl {
   2143   virtual void anchor();
   2144 public:
   2145   typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
   2146 
   2147 private:
   2148   // The number of template parameters;  always non-zero.
   2149   unsigned NumParams;
   2150 
   2151   // The parameter list.
   2152   TemplateParameterList **Params;
   2153 
   2154   // The declaration that's a friend of this class.
   2155   FriendUnion Friend;
   2156 
   2157   // Location of the 'friend' specifier.
   2158   SourceLocation FriendLoc;
   2159 
   2160 
   2161   FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
   2162                      unsigned NParams,
   2163                      TemplateParameterList **Params,
   2164                      FriendUnion Friend,
   2165                      SourceLocation FriendLoc)
   2166     : Decl(Decl::FriendTemplate, DC, Loc),
   2167       NumParams(NParams),
   2168       Params(Params),
   2169       Friend(Friend),
   2170       FriendLoc(FriendLoc)
   2171   {}
   2172 
   2173   FriendTemplateDecl(EmptyShell Empty)
   2174     : Decl(Decl::FriendTemplate, Empty),
   2175       NumParams(0),
   2176       Params(nullptr)
   2177   {}
   2178 
   2179 public:
   2180   static FriendTemplateDecl *Create(ASTContext &Context,
   2181                                     DeclContext *DC, SourceLocation Loc,
   2182                                     unsigned NParams,
   2183                                     TemplateParameterList **Params,
   2184                                     FriendUnion Friend,
   2185                                     SourceLocation FriendLoc);
   2186 
   2187   static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2188 
   2189   /// If this friend declaration names a templated type (or
   2190   /// a dependent member type of a templated type), return that
   2191   /// type;  otherwise return null.
   2192   TypeSourceInfo *getFriendType() const {
   2193     return Friend.dyn_cast<TypeSourceInfo*>();
   2194   }
   2195 
   2196   /// If this friend declaration names a templated function (or
   2197   /// a member function of a templated type), return that type;
   2198   /// otherwise return null.
   2199   NamedDecl *getFriendDecl() const {
   2200     return Friend.dyn_cast<NamedDecl*>();
   2201   }
   2202 
   2203   /// \brief Retrieves the location of the 'friend' keyword.
   2204   SourceLocation getFriendLoc() const {
   2205     return FriendLoc;
   2206   }
   2207 
   2208   TemplateParameterList *getTemplateParameterList(unsigned i) const {
   2209     assert(i <= NumParams);
   2210     return Params[i];
   2211   }
   2212 
   2213   unsigned getNumTemplateParameters() const {
   2214     return NumParams;
   2215   }
   2216 
   2217   // Implement isa/cast/dyncast/etc.
   2218   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2219   static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
   2220 
   2221   friend class ASTDeclReader;
   2222 };
   2223 
   2224 /// \brief Declaration of an alias template.
   2225 ///
   2226 /// For example:
   2227 /// \code
   2228 /// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
   2229 /// \endcode
   2230 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
   2231   static void DeallocateCommon(void *Ptr);
   2232 
   2233 protected:
   2234   typedef CommonBase Common;
   2235 
   2236   TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
   2237                         DeclarationName Name, TemplateParameterList *Params,
   2238                         NamedDecl *Decl)
   2239       : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
   2240                                  Decl) {}
   2241 
   2242   CommonBase *newCommon(ASTContext &C) const override;
   2243 
   2244   Common *getCommonPtr() {
   2245     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
   2246   }
   2247 
   2248 public:
   2249   /// Get the underlying function declaration of the template.
   2250   TypeAliasDecl *getTemplatedDecl() const {
   2251     return static_cast<TypeAliasDecl*>(TemplatedDecl);
   2252   }
   2253 
   2254 
   2255   TypeAliasTemplateDecl *getCanonicalDecl() override {
   2256     return cast<TypeAliasTemplateDecl>(
   2257              RedeclarableTemplateDecl::getCanonicalDecl());
   2258   }
   2259   const TypeAliasTemplateDecl *getCanonicalDecl() const {
   2260     return cast<TypeAliasTemplateDecl>(
   2261              RedeclarableTemplateDecl::getCanonicalDecl());
   2262   }
   2263 
   2264   /// \brief Retrieve the previous declaration of this function template, or
   2265   /// NULL if no such declaration exists.
   2266   TypeAliasTemplateDecl *getPreviousDecl() {
   2267     return cast_or_null<TypeAliasTemplateDecl>(
   2268              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
   2269   }
   2270 
   2271   /// \brief Retrieve the previous declaration of this function template, or
   2272   /// NULL if no such declaration exists.
   2273   const TypeAliasTemplateDecl *getPreviousDecl() const {
   2274     return cast_or_null<TypeAliasTemplateDecl>(
   2275              static_cast<const RedeclarableTemplateDecl *>(
   2276                this)->getPreviousDecl());
   2277   }
   2278 
   2279   TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
   2280     return cast_or_null<TypeAliasTemplateDecl>(
   2281              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
   2282   }
   2283 
   2284 
   2285   /// \brief Create a function template node.
   2286   static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
   2287                                        SourceLocation L,
   2288                                        DeclarationName Name,
   2289                                        TemplateParameterList *Params,
   2290                                        NamedDecl *Decl);
   2291 
   2292   /// \brief Create an empty alias template node.
   2293   static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2294 
   2295   // Implement isa/cast/dyncast support
   2296   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2297   static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
   2298 
   2299   friend class ASTDeclReader;
   2300   friend class ASTDeclWriter;
   2301 };
   2302 
   2303 /// \brief Declaration of a function specialization at template class scope.
   2304 ///
   2305 /// This is a non-standard extension needed to support MSVC.
   2306 ///
   2307 /// For example:
   2308 /// \code
   2309 /// template <class T>
   2310 /// class A {
   2311 ///    template <class U> void foo(U a) { }
   2312 ///    template<> void foo(int a) { }
   2313 /// }
   2314 /// \endcode
   2315 ///
   2316 /// "template<> foo(int a)" will be saved in Specialization as a normal
   2317 /// CXXMethodDecl. Then during an instantiation of class A, it will be
   2318 /// transformed into an actual function specialization.
   2319 class ClassScopeFunctionSpecializationDecl : public Decl {
   2320   virtual void anchor();
   2321 
   2322   ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
   2323                                        CXXMethodDecl *FD, bool Args,
   2324                                        TemplateArgumentListInfo TemplArgs)
   2325     : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
   2326       Specialization(FD), HasExplicitTemplateArgs(Args),
   2327       TemplateArgs(TemplArgs) {}
   2328 
   2329   ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
   2330     : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
   2331 
   2332   CXXMethodDecl *Specialization;
   2333   bool HasExplicitTemplateArgs;
   2334   TemplateArgumentListInfo TemplateArgs;
   2335 
   2336 public:
   2337   CXXMethodDecl *getSpecialization() const { return Specialization; }
   2338   bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
   2339   const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
   2340 
   2341   static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
   2342                                                       DeclContext *DC,
   2343                                                       SourceLocation Loc,
   2344                                                       CXXMethodDecl *FD,
   2345                                                    bool HasExplicitTemplateArgs,
   2346                                         TemplateArgumentListInfo TemplateArgs) {
   2347     return new (C, DC) ClassScopeFunctionSpecializationDecl(
   2348         DC, Loc, FD, HasExplicitTemplateArgs, TemplateArgs);
   2349   }
   2350 
   2351   static ClassScopeFunctionSpecializationDecl *
   2352   CreateDeserialized(ASTContext &Context, unsigned ID);
   2353 
   2354   // Implement isa/cast/dyncast/etc.
   2355   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2356   static bool classofKind(Kind K) {
   2357     return K == Decl::ClassScopeFunctionSpecialization;
   2358   }
   2359 
   2360   friend class ASTDeclReader;
   2361   friend class ASTDeclWriter;
   2362 };
   2363 
   2364 /// Implementation of inline functions that require the template declarations
   2365 inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
   2366   : Function(FTD) { }
   2367 
   2368 /// \brief Represents a variable template specialization, which refers to
   2369 /// a variable template with a given set of template arguments.
   2370 ///
   2371 /// Variable template specializations represent both explicit
   2372 /// specializations of variable templates, as in the example below, and
   2373 /// implicit instantiations of variable templates.
   2374 ///
   2375 /// \code
   2376 /// template<typename T> constexpr T pi = T(3.1415926535897932385);
   2377 ///
   2378 /// template<>
   2379 /// constexpr float pi<float>; // variable template specialization pi<float>
   2380 /// \endcode
   2381 class VarTemplateSpecializationDecl : public VarDecl,
   2382                                       public llvm::FoldingSetNode {
   2383 
   2384   /// \brief Structure that stores information about a variable template
   2385   /// specialization that was instantiated from a variable template partial
   2386   /// specialization.
   2387   struct SpecializedPartialSpecialization {
   2388     /// \brief The variable template partial specialization from which this
   2389     /// variable template specialization was instantiated.
   2390     VarTemplatePartialSpecializationDecl *PartialSpecialization;
   2391 
   2392     /// \brief The template argument list deduced for the variable template
   2393     /// partial specialization itself.
   2394     const TemplateArgumentList *TemplateArgs;
   2395   };
   2396 
   2397   /// \brief The template that this specialization specializes.
   2398   llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
   2399   SpecializedTemplate;
   2400 
   2401   /// \brief Further info for explicit template specialization/instantiation.
   2402   struct ExplicitSpecializationInfo {
   2403     /// \brief The type-as-written.
   2404     TypeSourceInfo *TypeAsWritten;
   2405     /// \brief The location of the extern keyword.
   2406     SourceLocation ExternLoc;
   2407     /// \brief The location of the template keyword.
   2408     SourceLocation TemplateKeywordLoc;
   2409 
   2410     ExplicitSpecializationInfo()
   2411         : TypeAsWritten(nullptr), ExternLoc(), TemplateKeywordLoc() {}
   2412   };
   2413 
   2414   /// \brief Further info for explicit template specialization/instantiation.
   2415   /// Does not apply to implicit specializations.
   2416   ExplicitSpecializationInfo *ExplicitInfo;
   2417 
   2418   /// \brief The template arguments used to describe this specialization.
   2419   const TemplateArgumentList *TemplateArgs;
   2420   TemplateArgumentListInfo TemplateArgsInfo;
   2421 
   2422   /// \brief The point where this template was instantiated (if any).
   2423   SourceLocation PointOfInstantiation;
   2424 
   2425   /// \brief The kind of specialization this declaration refers to.
   2426   /// Really a value of type TemplateSpecializationKind.
   2427   unsigned SpecializationKind : 3;
   2428 
   2429 protected:
   2430   VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
   2431                                 SourceLocation StartLoc, SourceLocation IdLoc,
   2432                                 VarTemplateDecl *SpecializedTemplate,
   2433                                 QualType T, TypeSourceInfo *TInfo,
   2434                                 StorageClass S, const TemplateArgument *Args,
   2435                                 unsigned NumArgs);
   2436 
   2437   explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
   2438 
   2439 public:
   2440   static VarTemplateSpecializationDecl *
   2441   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
   2442          SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
   2443          TypeSourceInfo *TInfo, StorageClass S, const TemplateArgument *Args,
   2444          unsigned NumArgs);
   2445   static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
   2446                                                            unsigned ID);
   2447 
   2448   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
   2449                             bool Qualified) const override;
   2450 
   2451   VarTemplateSpecializationDecl *getMostRecentDecl() {
   2452     VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
   2453     return cast<VarTemplateSpecializationDecl>(Recent);
   2454   }
   2455 
   2456   /// \brief Retrieve the template that this specialization specializes.
   2457   VarTemplateDecl *getSpecializedTemplate() const;
   2458 
   2459   /// \brief Retrieve the template arguments of the variable template
   2460   /// specialization.
   2461   const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
   2462 
   2463   // TODO: Always set this when creating the new specialization?
   2464   void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
   2465 
   2466   const TemplateArgumentListInfo &getTemplateArgsInfo() const {
   2467     return TemplateArgsInfo;
   2468   }
   2469 
   2470   /// \brief Determine the kind of specialization that this
   2471   /// declaration represents.
   2472   TemplateSpecializationKind getSpecializationKind() const {
   2473     return static_cast<TemplateSpecializationKind>(SpecializationKind);
   2474   }
   2475 
   2476   bool isExplicitSpecialization() const {
   2477     return getSpecializationKind() == TSK_ExplicitSpecialization;
   2478   }
   2479 
   2480   /// \brief True if this declaration is an explicit specialization,
   2481   /// explicit instantiation declaration, or explicit instantiation
   2482   /// definition.
   2483   bool isExplicitInstantiationOrSpecialization() const {
   2484     return isTemplateExplicitInstantiationOrSpecialization(
   2485         getTemplateSpecializationKind());
   2486   }
   2487 
   2488   void setSpecializationKind(TemplateSpecializationKind TSK) {
   2489     SpecializationKind = TSK;
   2490   }
   2491 
   2492   /// \brief Get the point of instantiation (if any), or null if none.
   2493   SourceLocation getPointOfInstantiation() const {
   2494     return PointOfInstantiation;
   2495   }
   2496 
   2497   void setPointOfInstantiation(SourceLocation Loc) {
   2498     assert(Loc.isValid() && "point of instantiation must be valid!");
   2499     PointOfInstantiation = Loc;
   2500   }
   2501 
   2502   /// \brief If this variable template specialization is an instantiation of
   2503   /// a template (rather than an explicit specialization), return the
   2504   /// variable template or variable template partial specialization from which
   2505   /// it was instantiated.
   2506   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
   2507   getInstantiatedFrom() const {
   2508     if (getSpecializationKind() != TSK_ImplicitInstantiation &&
   2509         getSpecializationKind() != TSK_ExplicitInstantiationDefinition &&
   2510         getSpecializationKind() != TSK_ExplicitInstantiationDeclaration)
   2511       return llvm::PointerUnion<VarTemplateDecl *,
   2512                                 VarTemplatePartialSpecializationDecl *>();
   2513 
   2514     if (SpecializedPartialSpecialization *PartialSpec =
   2515             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
   2516       return PartialSpec->PartialSpecialization;
   2517 
   2518     return SpecializedTemplate.get<VarTemplateDecl *>();
   2519   }
   2520 
   2521   /// \brief Retrieve the variable template or variable template partial
   2522   /// specialization which was specialized by this.
   2523   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
   2524   getSpecializedTemplateOrPartial() const {
   2525     if (SpecializedPartialSpecialization *PartialSpec =
   2526             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
   2527       return PartialSpec->PartialSpecialization;
   2528 
   2529     return SpecializedTemplate.get<VarTemplateDecl *>();
   2530   }
   2531 
   2532   /// \brief Retrieve the set of template arguments that should be used
   2533   /// to instantiate the initializer of the variable template or variable
   2534   /// template partial specialization from which this variable template
   2535   /// specialization was instantiated.
   2536   ///
   2537   /// \returns For a variable template specialization instantiated from the
   2538   /// primary template, this function will return the same template arguments
   2539   /// as getTemplateArgs(). For a variable template specialization instantiated
   2540   /// from a variable template partial specialization, this function will the
   2541   /// return deduced template arguments for the variable template partial
   2542   /// specialization itself.
   2543   const TemplateArgumentList &getTemplateInstantiationArgs() const {
   2544     if (SpecializedPartialSpecialization *PartialSpec =
   2545             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
   2546       return *PartialSpec->TemplateArgs;
   2547 
   2548     return getTemplateArgs();
   2549   }
   2550 
   2551   /// \brief Note that this variable template specialization is actually an
   2552   /// instantiation of the given variable template partial specialization whose
   2553   /// template arguments have been deduced.
   2554   void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
   2555                           const TemplateArgumentList *TemplateArgs) {
   2556     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
   2557            "Already set to a variable template partial specialization!");
   2558     SpecializedPartialSpecialization *PS =
   2559         new (getASTContext()) SpecializedPartialSpecialization();
   2560     PS->PartialSpecialization = PartialSpec;
   2561     PS->TemplateArgs = TemplateArgs;
   2562     SpecializedTemplate = PS;
   2563   }
   2564 
   2565   /// \brief Note that this variable template specialization is an instantiation
   2566   /// of the given variable template.
   2567   void setInstantiationOf(VarTemplateDecl *TemplDecl) {
   2568     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
   2569            "Previously set to a variable template partial specialization!");
   2570     SpecializedTemplate = TemplDecl;
   2571   }
   2572 
   2573   /// \brief Sets the type of this specialization as it was written by
   2574   /// the user.
   2575   void setTypeAsWritten(TypeSourceInfo *T) {
   2576     if (!ExplicitInfo)
   2577       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   2578     ExplicitInfo->TypeAsWritten = T;
   2579   }
   2580   /// \brief Gets the type of this specialization as it was written by
   2581   /// the user, if it was so written.
   2582   TypeSourceInfo *getTypeAsWritten() const {
   2583     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
   2584   }
   2585 
   2586   /// \brief Gets the location of the extern keyword, if present.
   2587   SourceLocation getExternLoc() const {
   2588     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
   2589   }
   2590   /// \brief Sets the location of the extern keyword.
   2591   void setExternLoc(SourceLocation Loc) {
   2592     if (!ExplicitInfo)
   2593       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   2594     ExplicitInfo->ExternLoc = Loc;
   2595   }
   2596 
   2597   /// \brief Sets the location of the template keyword.
   2598   void setTemplateKeywordLoc(SourceLocation Loc) {
   2599     if (!ExplicitInfo)
   2600       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   2601     ExplicitInfo->TemplateKeywordLoc = Loc;
   2602   }
   2603   /// \brief Gets the location of the template keyword, if present.
   2604   SourceLocation getTemplateKeywordLoc() const {
   2605     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
   2606   }
   2607 
   2608   void Profile(llvm::FoldingSetNodeID &ID) const {
   2609     Profile(ID, TemplateArgs->asArray(), getASTContext());
   2610   }
   2611 
   2612   static void Profile(llvm::FoldingSetNodeID &ID,
   2613                       ArrayRef<TemplateArgument> TemplateArgs,
   2614                       ASTContext &Context) {
   2615     ID.AddInteger(TemplateArgs.size());
   2616     for (unsigned Arg = 0; Arg != TemplateArgs.size(); ++Arg)
   2617       TemplateArgs[Arg].Profile(ID, Context);
   2618   }
   2619 
   2620   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2621   static bool classofKind(Kind K) {
   2622     return K >= firstVarTemplateSpecialization &&
   2623            K <= lastVarTemplateSpecialization;
   2624   }
   2625 
   2626   friend class ASTDeclReader;
   2627   friend class ASTDeclWriter;
   2628 };
   2629 
   2630 class VarTemplatePartialSpecializationDecl
   2631     : public VarTemplateSpecializationDecl {
   2632   void anchor() override;
   2633 
   2634   /// \brief The list of template parameters
   2635   TemplateParameterList *TemplateParams;
   2636 
   2637   /// \brief The source info for the template arguments as written.
   2638   /// FIXME: redundant with TypeAsWritten?
   2639   const ASTTemplateArgumentListInfo *ArgsAsWritten;
   2640 
   2641   /// \brief The variable template partial specialization from which this
   2642   /// variable template partial specialization was instantiated.
   2643   ///
   2644   /// The boolean value will be true to indicate that this variable template
   2645   /// partial specialization was specialized at this level.
   2646   llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
   2647   InstantiatedFromMember;
   2648 
   2649   VarTemplatePartialSpecializationDecl(
   2650       ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
   2651       SourceLocation IdLoc, TemplateParameterList *Params,
   2652       VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
   2653       StorageClass S, const TemplateArgument *Args, unsigned NumArgs,
   2654       const ASTTemplateArgumentListInfo *ArgInfos);
   2655 
   2656   VarTemplatePartialSpecializationDecl(ASTContext &Context)
   2657     : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization, Context),
   2658       TemplateParams(nullptr), ArgsAsWritten(nullptr),
   2659       InstantiatedFromMember(nullptr, false) {}
   2660 
   2661 public:
   2662   static VarTemplatePartialSpecializationDecl *
   2663   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
   2664          SourceLocation IdLoc, TemplateParameterList *Params,
   2665          VarTemplateDecl *SpecializedTemplate, QualType T,
   2666          TypeSourceInfo *TInfo, StorageClass S, const TemplateArgument *Args,
   2667          unsigned NumArgs, const TemplateArgumentListInfo &ArgInfos);
   2668 
   2669   static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
   2670                                                                   unsigned ID);
   2671 
   2672   VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
   2673     return cast<VarTemplatePartialSpecializationDecl>(
   2674              static_cast<VarTemplateSpecializationDecl *>(
   2675                this)->getMostRecentDecl());
   2676   }
   2677 
   2678   /// Get the list of template parameters
   2679   TemplateParameterList *getTemplateParameters() const {
   2680     return TemplateParams;
   2681   }
   2682 
   2683   /// Get the template arguments as written.
   2684   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
   2685     return ArgsAsWritten;
   2686   }
   2687 
   2688   /// \brief Retrieve the member variable template partial specialization from
   2689   /// which this particular variable template partial specialization was
   2690   /// instantiated.
   2691   ///
   2692   /// \code
   2693   /// template<typename T>
   2694   /// struct Outer {
   2695   ///   template<typename U> U Inner;
   2696   ///   template<typename U> U* Inner<U*> = (U*)(0); // #1
   2697   /// };
   2698   ///
   2699   /// template int* Outer<float>::Inner<int*>;
   2700   /// \endcode
   2701   ///
   2702   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
   2703   /// end up instantiating the partial specialization
   2704   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
   2705   /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
   2706   /// \c Outer<float>::Inner<U*>, this function would return
   2707   /// \c Outer<T>::Inner<U*>.
   2708   VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
   2709     const VarTemplatePartialSpecializationDecl *First =
   2710         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
   2711     return First->InstantiatedFromMember.getPointer();
   2712   }
   2713 
   2714   void
   2715   setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
   2716     VarTemplatePartialSpecializationDecl *First =
   2717         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
   2718     First->InstantiatedFromMember.setPointer(PartialSpec);
   2719   }
   2720 
   2721   /// \brief Determines whether this variable template partial specialization
   2722   /// was a specialization of a member partial specialization.
   2723   ///
   2724   /// In the following example, the member template partial specialization
   2725   /// \c X<int>::Inner<T*> is a member specialization.
   2726   ///
   2727   /// \code
   2728   /// template<typename T>
   2729   /// struct X {
   2730   ///   template<typename U> U Inner;
   2731   ///   template<typename U> U* Inner<U*> = (U*)(0);
   2732   /// };
   2733   ///
   2734   /// template<> template<typename T>
   2735   /// U* X<int>::Inner<T*> = (T*)(0) + 1;
   2736   /// \endcode
   2737   bool isMemberSpecialization() {
   2738     VarTemplatePartialSpecializationDecl *First =
   2739         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
   2740     return First->InstantiatedFromMember.getInt();
   2741   }
   2742 
   2743   /// \brief Note that this member template is a specialization.
   2744   void setMemberSpecialization() {
   2745     VarTemplatePartialSpecializationDecl *First =
   2746         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
   2747     assert(First->InstantiatedFromMember.getPointer() &&
   2748            "Only member templates can be member template specializations");
   2749     return First->InstantiatedFromMember.setInt(true);
   2750   }
   2751 
   2752   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2753   static bool classofKind(Kind K) {
   2754     return K == VarTemplatePartialSpecialization;
   2755   }
   2756 
   2757   friend class ASTDeclReader;
   2758   friend class ASTDeclWriter;
   2759 };
   2760 
   2761 /// Declaration of a variable template.
   2762 class VarTemplateDecl : public RedeclarableTemplateDecl {
   2763   static void DeallocateCommon(void *Ptr);
   2764 
   2765 protected:
   2766   /// \brief Data that is common to all of the declarations of a given
   2767   /// variable template.
   2768   struct Common : CommonBase {
   2769     Common() : LazySpecializations() {}
   2770 
   2771     /// \brief The variable template specializations for this variable
   2772     /// template, including explicit specializations and instantiations.
   2773     llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
   2774 
   2775     /// \brief The variable template partial specializations for this variable
   2776     /// template.
   2777     llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
   2778     PartialSpecializations;
   2779 
   2780     /// \brief If non-null, points to an array of specializations (including
   2781     /// partial specializations) known ownly by their external declaration IDs.
   2782     ///
   2783     /// The first value in the array is the number of of specializations/
   2784     /// partial specializations that follow.
   2785     uint32_t *LazySpecializations;
   2786   };
   2787 
   2788   /// \brief Retrieve the set of specializations of this variable template.
   2789   llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
   2790   getSpecializations() const;
   2791 
   2792   /// \brief Retrieve the set of partial specializations of this class
   2793   /// template.
   2794   llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
   2795   getPartialSpecializations();
   2796 
   2797   VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
   2798                   DeclarationName Name, TemplateParameterList *Params,
   2799                   NamedDecl *Decl)
   2800       : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
   2801 
   2802   CommonBase *newCommon(ASTContext &C) const override;
   2803 
   2804   Common *getCommonPtr() const {
   2805     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
   2806   }
   2807 
   2808 public:
   2809   /// \brief Load any lazily-loaded specializations from the external source.
   2810   void LoadLazySpecializations() const;
   2811 
   2812   /// \brief Get the underlying variable declarations of the template.
   2813   VarDecl *getTemplatedDecl() const {
   2814     return static_cast<VarDecl *>(TemplatedDecl);
   2815   }
   2816 
   2817   /// \brief Returns whether this template declaration defines the primary
   2818   /// variable pattern.
   2819   bool isThisDeclarationADefinition() const {
   2820     return getTemplatedDecl()->isThisDeclarationADefinition();
   2821   }
   2822 
   2823   VarTemplateDecl *getDefinition();
   2824 
   2825   /// \brief Create a variable template node.
   2826   static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
   2827                                  SourceLocation L, DeclarationName Name,
   2828                                  TemplateParameterList *Params,
   2829                                  VarDecl *Decl);
   2830 
   2831   /// \brief Create an empty variable template node.
   2832   static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2833 
   2834   /// \brief Return the specialization with the provided arguments if it exists,
   2835   /// otherwise return the insertion point.
   2836   VarTemplateSpecializationDecl *
   2837   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
   2838 
   2839   /// \brief Insert the specified specialization knowing that it is not already
   2840   /// in. InsertPos must be obtained from findSpecialization.
   2841   void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
   2842 
   2843   VarTemplateDecl *getCanonicalDecl() override {
   2844     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
   2845   }
   2846   const VarTemplateDecl *getCanonicalDecl() const {
   2847     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
   2848   }
   2849 
   2850   /// \brief Retrieve the previous declaration of this variable template, or
   2851   /// NULL if no such declaration exists.
   2852   VarTemplateDecl *getPreviousDecl() {
   2853     return cast_or_null<VarTemplateDecl>(
   2854         static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
   2855   }
   2856 
   2857   /// \brief Retrieve the previous declaration of this variable template, or
   2858   /// NULL if no such declaration exists.
   2859   const VarTemplateDecl *getPreviousDecl() const {
   2860     return cast_or_null<VarTemplateDecl>(
   2861             static_cast<const RedeclarableTemplateDecl *>(
   2862               this)->getPreviousDecl());
   2863   }
   2864 
   2865   VarTemplateDecl *getMostRecentDecl() {
   2866     return cast<VarTemplateDecl>(
   2867         static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
   2868   }
   2869   const VarTemplateDecl *getMostRecentDecl() const {
   2870     return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
   2871   }
   2872 
   2873   VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
   2874     return cast_or_null<VarTemplateDecl>(
   2875         RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
   2876   }
   2877 
   2878   /// \brief Return the partial specialization with the provided arguments if it
   2879   /// exists, otherwise return the insertion point.
   2880   VarTemplatePartialSpecializationDecl *
   2881   findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
   2882 
   2883   /// \brief Insert the specified partial specialization knowing that it is not
   2884   /// already in. InsertPos must be obtained from findPartialSpecialization.
   2885   void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
   2886                                 void *InsertPos);
   2887 
   2888   /// \brief Retrieve the partial specializations as an ordered list.
   2889   void getPartialSpecializations(
   2890       SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
   2891 
   2892   /// \brief Find a variable template partial specialization which was
   2893   /// instantiated
   2894   /// from the given member partial specialization.
   2895   ///
   2896   /// \param D a member variable template partial specialization.
   2897   ///
   2898   /// \returns the variable template partial specialization which was
   2899   /// instantiated
   2900   /// from the given member partial specialization, or NULL if no such partial
   2901   /// specialization exists.
   2902   VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
   2903       VarTemplatePartialSpecializationDecl *D);
   2904 
   2905   typedef SpecIterator<VarTemplateSpecializationDecl> spec_iterator;
   2906   typedef llvm::iterator_range<spec_iterator> spec_range;
   2907 
   2908   spec_range specializations() const {
   2909     return spec_range(spec_begin(), spec_end());
   2910   }
   2911 
   2912   spec_iterator spec_begin() const {
   2913     return makeSpecIterator(getSpecializations(), false);
   2914   }
   2915 
   2916   spec_iterator spec_end() const {
   2917     return makeSpecIterator(getSpecializations(), true);
   2918   }
   2919 
   2920   // Implement isa/cast/dyncast support
   2921   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2922   static bool classofKind(Kind K) { return K == VarTemplate; }
   2923 
   2924   friend class ASTDeclReader;
   2925   friend class ASTDeclWriter;
   2926 };
   2927 
   2928 } /* end of namespace clang */
   2929 
   2930 #endif
   2931