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 <limits>
     24 
     25 namespace clang {
     26 
     27 class TemplateParameterList;
     28 class TemplateDecl;
     29 class RedeclarableTemplateDecl;
     30 class FunctionTemplateDecl;
     31 class ClassTemplateDecl;
     32 class ClassTemplatePartialSpecializationDecl;
     33 class TemplateTypeParmDecl;
     34 class NonTypeTemplateParmDecl;
     35 class TemplateTemplateParmDecl;
     36 class TypeAliasTemplateDecl;
     37 
     38 /// \brief Stores a template parameter of any kind.
     39 typedef llvm::PointerUnion3<TemplateTypeParmDecl*, NonTypeTemplateParmDecl*,
     40                             TemplateTemplateParmDecl*> TemplateParameter;
     41 
     42 /// \brief Stores a list of template parameters for a TemplateDecl and its
     43 /// derived classes.
     44 class TemplateParameterList {
     45   /// The location of the 'template' keyword.
     46   SourceLocation TemplateLoc;
     47 
     48   /// The locations of the '<' and '>' angle brackets.
     49   SourceLocation LAngleLoc, RAngleLoc;
     50 
     51   /// The number of template parameters in this template
     52   /// parameter list.
     53   unsigned NumParams : 31;
     54 
     55   /// Whether this template parameter list contains an unexpanded parameter
     56   /// pack.
     57   unsigned ContainsUnexpandedParameterPack : 1;
     58 
     59 protected:
     60   TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
     61                         NamedDecl **Params, unsigned NumParams,
     62                         SourceLocation RAngleLoc);
     63 
     64 public:
     65   static TemplateParameterList *Create(const ASTContext &C,
     66                                        SourceLocation TemplateLoc,
     67                                        SourceLocation LAngleLoc,
     68                                        NamedDecl **Params,
     69                                        unsigned NumParams,
     70                                        SourceLocation RAngleLoc);
     71 
     72   /// \brief Iterates through the template parameters in this list.
     73   typedef NamedDecl** iterator;
     74 
     75   /// \brief Iterates through the template parameters in this list.
     76   typedef NamedDecl* const* const_iterator;
     77 
     78   iterator begin() { return reinterpret_cast<NamedDecl **>(this + 1); }
     79   const_iterator begin() const {
     80     return reinterpret_cast<NamedDecl * const *>(this + 1);
     81   }
     82   iterator end() { return begin() + NumParams; }
     83   const_iterator end() const { return begin() + NumParams; }
     84 
     85   unsigned size() const { return NumParams; }
     86 
     87   llvm::ArrayRef<NamedDecl*> asArray() {
     88     return llvm::ArrayRef<NamedDecl*>(begin(), size());
     89   }
     90   llvm::ArrayRef<const NamedDecl*> asArray() const {
     91     return llvm::ArrayRef<const NamedDecl*>(begin(), size());
     92   }
     93 
     94   NamedDecl* getParam(unsigned Idx) {
     95     assert(Idx < size() && "Template parameter index out-of-range");
     96     return begin()[Idx];
     97   }
     98 
     99   const NamedDecl* getParam(unsigned Idx) const {
    100     assert(Idx < size() && "Template parameter index out-of-range");
    101     return begin()[Idx];
    102   }
    103 
    104   /// \brief Returns the minimum number of arguments needed to form a
    105   /// template specialization.
    106   ///
    107   /// This may be fewer than the number of template parameters, if some of
    108   /// the parameters have default arguments or if there is a parameter pack.
    109   unsigned getMinRequiredArguments() const;
    110 
    111   /// \brief Get the depth of this template parameter list in the set of
    112   /// template parameter lists.
    113   ///
    114   /// The first template parameter list in a declaration will have depth 0,
    115   /// the second template parameter list will have depth 1, etc.
    116   unsigned getDepth() const;
    117 
    118   /// \brief Determine whether this template parameter list contains an
    119   /// unexpanded parameter pack.
    120   bool containsUnexpandedParameterPack() const {
    121     return ContainsUnexpandedParameterPack;
    122   }
    123 
    124   SourceLocation getTemplateLoc() const { return TemplateLoc; }
    125   SourceLocation getLAngleLoc() const { return LAngleLoc; }
    126   SourceLocation getRAngleLoc() const { return RAngleLoc; }
    127 
    128   SourceRange getSourceRange() const LLVM_READONLY {
    129     return SourceRange(TemplateLoc, RAngleLoc);
    130   }
    131 };
    132 
    133 /// \brief Stores a list of template parameters for a TemplateDecl and its
    134 /// derived classes. Suitable for creating on the stack.
    135 template<size_t N>
    136 class FixedSizeTemplateParameterList : public TemplateParameterList {
    137   NamedDecl *Params[N];
    138 
    139 public:
    140   FixedSizeTemplateParameterList(SourceLocation TemplateLoc,
    141                                  SourceLocation LAngleLoc,
    142                                  NamedDecl **Params, SourceLocation RAngleLoc) :
    143     TemplateParameterList(TemplateLoc, LAngleLoc, Params, N, RAngleLoc) {
    144   }
    145 };
    146 
    147 /// \brief A template argument list.
    148 class TemplateArgumentList {
    149   /// \brief The template argument list.
    150   ///
    151   /// The integer value will be non-zero to indicate that this
    152   /// template argument list does own the pointer.
    153   llvm::PointerIntPair<const TemplateArgument *, 1> Arguments;
    154 
    155   /// \brief The number of template arguments in this template
    156   /// argument list.
    157   unsigned NumArguments;
    158 
    159   TemplateArgumentList(const TemplateArgumentList &Other) LLVM_DELETED_FUNCTION;
    160   void operator=(const TemplateArgumentList &Other) LLVM_DELETED_FUNCTION;
    161 
    162   TemplateArgumentList(const TemplateArgument *Args, unsigned NumArgs,
    163                        bool Owned)
    164     : Arguments(Args, Owned), NumArguments(NumArgs) { }
    165 
    166 public:
    167   /// \brief Type used to indicate that the template argument list itself is a
    168   /// stack object. It does not own its template arguments.
    169   enum OnStackType { OnStack };
    170 
    171   /// \brief Create a new template argument list that copies the given set of
    172   /// template arguments.
    173   static TemplateArgumentList *CreateCopy(ASTContext &Context,
    174                                           const TemplateArgument *Args,
    175                                           unsigned NumArgs);
    176 
    177   /// \brief Construct a new, temporary template argument list on the stack.
    178   ///
    179   /// The template argument list does not own the template arguments
    180   /// provided.
    181   explicit TemplateArgumentList(OnStackType,
    182                                 const TemplateArgument *Args, unsigned NumArgs)
    183     : Arguments(Args, false), NumArguments(NumArgs) { }
    184 
    185   /// \brief Produces a shallow copy of the given template argument list.
    186   ///
    187   /// This operation assumes that the input argument list outlives it.
    188   /// This takes the list as a pointer to avoid looking like a copy
    189   /// constructor, since this really really isn't safe to use that
    190   /// way.
    191   explicit TemplateArgumentList(const TemplateArgumentList *Other)
    192     : Arguments(Other->data(), false), NumArguments(Other->size()) { }
    193 
    194   /// \brief Retrieve the template argument at a given index.
    195   const TemplateArgument &get(unsigned Idx) const {
    196     assert(Idx < NumArguments && "Invalid template argument index");
    197     return data()[Idx];
    198   }
    199 
    200   /// \brief Retrieve the template argument at a given index.
    201   const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
    202 
    203   /// \brief Produce this as an array ref.
    204   llvm::ArrayRef<TemplateArgument> asArray() const {
    205     return llvm::ArrayRef<TemplateArgument>(data(), size());
    206   }
    207 
    208   /// \brief Retrieve the number of template arguments in this
    209   /// template argument list.
    210   unsigned size() const { return NumArguments; }
    211 
    212   /// \brief Retrieve a pointer to the template argument list.
    213   const TemplateArgument *data() const {
    214     return Arguments.getPointer();
    215   }
    216 };
    217 
    218 //===----------------------------------------------------------------------===//
    219 // Kinds of Templates
    220 //===----------------------------------------------------------------------===//
    221 
    222 /// \brief The base class of all kinds of template declarations (e.g.,
    223 /// class, function, etc.).
    224 ///
    225 /// The TemplateDecl class stores the list of template parameters and a
    226 /// reference to the templated scoped declaration: the underlying AST node.
    227 class TemplateDecl : public NamedDecl {
    228   virtual void anchor();
    229 protected:
    230   // This is probably never used.
    231   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
    232                DeclarationName Name)
    233     : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(0) { }
    234 
    235   // Construct a template decl with the given name and parameters.
    236   // Used when there is not templated element (tt-params, alias?).
    237   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
    238                DeclarationName Name, TemplateParameterList *Params)
    239     : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(Params) { }
    240 
    241   // Construct a template decl with name, parameters, and templated element.
    242   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
    243                DeclarationName Name, TemplateParameterList *Params,
    244                NamedDecl *Decl)
    245     : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
    246       TemplateParams(Params) { }
    247 public:
    248   /// Get the list of template parameters
    249   TemplateParameterList *getTemplateParameters() const {
    250     return TemplateParams;
    251   }
    252 
    253   /// Get the underlying, templated declaration.
    254   NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
    255 
    256   // Implement isa/cast/dyncast/etc.
    257   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    258   static bool classofKind(Kind K) {
    259     return K >= firstTemplate && K <= lastTemplate;
    260   }
    261 
    262   SourceRange getSourceRange() const LLVM_READONLY {
    263     return SourceRange(TemplateParams->getTemplateLoc(),
    264                        TemplatedDecl->getSourceRange().getEnd());
    265   }
    266 
    267 protected:
    268   NamedDecl *TemplatedDecl;
    269   TemplateParameterList* TemplateParams;
    270 
    271 public:
    272   /// \brief Initialize the underlying templated declaration and
    273   /// template parameters.
    274   void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
    275     assert(TemplatedDecl == 0 && "TemplatedDecl already set!");
    276     assert(TemplateParams == 0 && "TemplateParams already set!");
    277     TemplatedDecl = templatedDecl;
    278     TemplateParams = templateParams;
    279   }
    280 };
    281 
    282 /// \brief Provides information about a function template specialization,
    283 /// which is a FunctionDecl that has been explicitly specialization or
    284 /// instantiated from a function template.
    285 class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
    286   FunctionTemplateSpecializationInfo(FunctionDecl *FD,
    287                                      FunctionTemplateDecl *Template,
    288                                      TemplateSpecializationKind TSK,
    289                                      const TemplateArgumentList *TemplateArgs,
    290                        const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
    291                                      SourceLocation POI)
    292   : Function(FD),
    293     Template(Template, TSK - 1),
    294     TemplateArguments(TemplateArgs),
    295     TemplateArgumentsAsWritten(TemplateArgsAsWritten),
    296     PointOfInstantiation(POI) { }
    297 
    298 public:
    299   static FunctionTemplateSpecializationInfo *
    300   Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
    301          TemplateSpecializationKind TSK,
    302          const TemplateArgumentList *TemplateArgs,
    303          const TemplateArgumentListInfo *TemplateArgsAsWritten,
    304          SourceLocation POI);
    305 
    306   /// \brief The function template specialization that this structure
    307   /// describes.
    308   FunctionDecl *Function;
    309 
    310   /// \brief The function template from which this function template
    311   /// specialization was generated.
    312   ///
    313   /// The two bits are contain the top 4 values of TemplateSpecializationKind.
    314   llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
    315 
    316   /// \brief The template arguments used to produce the function template
    317   /// specialization from the function template.
    318   const TemplateArgumentList *TemplateArguments;
    319 
    320   /// \brief The template arguments as written in the sources, if provided.
    321   const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
    322 
    323   /// \brief The point at which this function template specialization was
    324   /// first instantiated.
    325   SourceLocation PointOfInstantiation;
    326 
    327   /// \brief Retrieve the template from which this function was specialized.
    328   FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
    329 
    330   /// \brief Determine what kind of template specialization this is.
    331   TemplateSpecializationKind getTemplateSpecializationKind() const {
    332     return (TemplateSpecializationKind)(Template.getInt() + 1);
    333   }
    334 
    335   bool isExplicitSpecialization() const {
    336     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
    337   }
    338 
    339   /// \brief True if this declaration is an explicit specialization,
    340   /// explicit instantiation declaration, or explicit instantiation
    341   /// definition.
    342   bool isExplicitInstantiationOrSpecialization() const {
    343     switch (getTemplateSpecializationKind()) {
    344     case TSK_ExplicitSpecialization:
    345     case TSK_ExplicitInstantiationDeclaration:
    346     case TSK_ExplicitInstantiationDefinition:
    347       return true;
    348 
    349     case TSK_Undeclared:
    350     case TSK_ImplicitInstantiation:
    351       return false;
    352     }
    353     llvm_unreachable("bad template specialization kind");
    354   }
    355 
    356   /// \brief Set the template specialization kind.
    357   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
    358     assert(TSK != TSK_Undeclared &&
    359          "Cannot encode TSK_Undeclared for a function template specialization");
    360     Template.setInt(TSK - 1);
    361   }
    362 
    363   /// \brief Retrieve the first point of instantiation of this function
    364   /// template specialization.
    365   ///
    366   /// The point of instantiation may be an invalid source location if this
    367   /// function has yet to be instantiated.
    368   SourceLocation getPointOfInstantiation() const {
    369     return PointOfInstantiation;
    370   }
    371 
    372   /// \brief Set the (first) point of instantiation of this function template
    373   /// specialization.
    374   void setPointOfInstantiation(SourceLocation POI) {
    375     PointOfInstantiation = POI;
    376   }
    377 
    378   void Profile(llvm::FoldingSetNodeID &ID) {
    379     Profile(ID, TemplateArguments->data(),
    380             TemplateArguments->size(),
    381             Function->getASTContext());
    382   }
    383 
    384   static void
    385   Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs,
    386           unsigned NumTemplateArgs, ASTContext &Context) {
    387     ID.AddInteger(NumTemplateArgs);
    388     for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg)
    389       TemplateArgs[Arg].Profile(ID, Context);
    390   }
    391 };
    392 
    393 /// \brief Provides information a specialization of a member of a class
    394 /// template, which may be a member function, static data member,
    395 /// member class or member enumeration.
    396 class MemberSpecializationInfo {
    397   // The member declaration from which this member was instantiated, and the
    398   // manner in which the instantiation occurred (in the lower two bits).
    399   llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
    400 
    401   // The point at which this member was first instantiated.
    402   SourceLocation PointOfInstantiation;
    403 
    404 public:
    405   explicit
    406   MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
    407                            SourceLocation POI = SourceLocation())
    408     : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
    409     assert(TSK != TSK_Undeclared &&
    410            "Cannot encode undeclared template specializations for members");
    411   }
    412 
    413   /// \brief Retrieve the member declaration from which this member was
    414   /// instantiated.
    415   NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
    416 
    417   /// \brief Determine what kind of template specialization this is.
    418   TemplateSpecializationKind getTemplateSpecializationKind() const {
    419     return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
    420   }
    421 
    422   bool isExplicitSpecialization() const {
    423     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
    424   }
    425 
    426   /// \brief Set the template specialization kind.
    427   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
    428     assert(TSK != TSK_Undeclared &&
    429            "Cannot encode undeclared template specializations for members");
    430     MemberAndTSK.setInt(TSK - 1);
    431   }
    432 
    433   /// \brief Retrieve the first point of instantiation of this member.
    434   /// If the point of instantiation is an invalid location, then this member
    435   /// has not yet been instantiated.
    436   SourceLocation getPointOfInstantiation() const {
    437     return PointOfInstantiation;
    438   }
    439 
    440   /// \brief Set the first point of instantiation.
    441   void setPointOfInstantiation(SourceLocation POI) {
    442     PointOfInstantiation = POI;
    443   }
    444 };
    445 
    446 /// \brief Provides information about a dependent function-template
    447 /// specialization declaration.
    448 ///
    449 /// Since explicit function template specialization and instantiation
    450 /// declarations can only appear in namespace scope, and you can only
    451 /// specialize a member of a fully-specialized class, the only way to
    452 /// get one of these is in a friend declaration like the following:
    453 ///
    454 /// \code
    455 ///   template \<class T> void foo(T);
    456 ///   template \<class T> class A {
    457 ///     friend void foo<>(T);
    458 ///   };
    459 /// \endcode
    460 class DependentFunctionTemplateSpecializationInfo {
    461   struct CA {
    462     /// The number of potential template candidates.
    463     unsigned NumTemplates;
    464 
    465     /// The number of template arguments.
    466     unsigned NumArgs;
    467   };
    468 
    469   union {
    470     // Force sizeof to be a multiple of sizeof(void*) so that the
    471     // trailing data is aligned.
    472     void *Aligner;
    473     struct CA d;
    474   };
    475 
    476   /// The locations of the left and right angle brackets.
    477   SourceRange AngleLocs;
    478 
    479   FunctionTemplateDecl * const *getTemplates() const {
    480     return reinterpret_cast<FunctionTemplateDecl*const*>(this+1);
    481   }
    482 
    483 public:
    484   DependentFunctionTemplateSpecializationInfo(
    485                                  const UnresolvedSetImpl &Templates,
    486                                  const TemplateArgumentListInfo &TemplateArgs);
    487 
    488   /// \brief Returns the number of function templates that this might
    489   /// be a specialization of.
    490   unsigned getNumTemplates() const {
    491     return d.NumTemplates;
    492   }
    493 
    494   /// \brief Returns the i'th template candidate.
    495   FunctionTemplateDecl *getTemplate(unsigned I) const {
    496     assert(I < getNumTemplates() && "template index out of range");
    497     return getTemplates()[I];
    498   }
    499 
    500   /// \brief Returns the explicit template arguments that were given.
    501   const TemplateArgumentLoc *getTemplateArgs() const {
    502     return reinterpret_cast<const TemplateArgumentLoc*>(
    503                                             &getTemplates()[getNumTemplates()]);
    504   }
    505 
    506   /// \brief Returns the number of explicit template arguments that were given.
    507   unsigned getNumTemplateArgs() const {
    508     return d.NumArgs;
    509   }
    510 
    511   /// \brief Returns the nth template argument.
    512   const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
    513     assert(I < getNumTemplateArgs() && "template arg index out of range");
    514     return getTemplateArgs()[I];
    515   }
    516 
    517   SourceLocation getLAngleLoc() const {
    518     return AngleLocs.getBegin();
    519   }
    520 
    521   SourceLocation getRAngleLoc() const {
    522     return AngleLocs.getEnd();
    523   }
    524 };
    525 
    526 /// Declaration of a redeclarable template.
    527 class RedeclarableTemplateDecl : public TemplateDecl,
    528                                  public Redeclarable<RedeclarableTemplateDecl>
    529 {
    530   typedef Redeclarable<RedeclarableTemplateDecl> redeclarable_base;
    531   virtual RedeclarableTemplateDecl *getNextRedeclaration() {
    532     return RedeclLink.getNext();
    533   }
    534   virtual RedeclarableTemplateDecl *getPreviousDeclImpl() {
    535     return getPreviousDecl();
    536   }
    537   virtual RedeclarableTemplateDecl *getMostRecentDeclImpl() {
    538     return getMostRecentDecl();
    539   }
    540 
    541 protected:
    542   template <typename EntryType> struct SpecEntryTraits {
    543     typedef EntryType DeclType;
    544 
    545     static DeclType *getMostRecentDecl(EntryType *D) {
    546       return D->getMostRecentDecl();
    547     }
    548   };
    549 
    550   template <typename EntryType,
    551             typename _SETraits = SpecEntryTraits<EntryType>,
    552             typename _DeclType = typename _SETraits::DeclType>
    553   class SpecIterator : public std::iterator<std::forward_iterator_tag,
    554                                             _DeclType*, ptrdiff_t,
    555                                             _DeclType*, _DeclType*> {
    556     typedef _SETraits SETraits;
    557     typedef _DeclType DeclType;
    558 
    559     typedef typename llvm::FoldingSetVector<EntryType>::iterator
    560       SetIteratorType;
    561 
    562     SetIteratorType SetIter;
    563 
    564   public:
    565     SpecIterator() : SetIter() {}
    566     SpecIterator(SetIteratorType SetIter) : SetIter(SetIter) {}
    567 
    568     DeclType *operator*() const {
    569       return SETraits::getMostRecentDecl(&*SetIter);
    570     }
    571     DeclType *operator->() const { return **this; }
    572 
    573     SpecIterator &operator++() { ++SetIter; return *this; }
    574     SpecIterator operator++(int) {
    575       SpecIterator tmp(*this);
    576       ++(*this);
    577       return tmp;
    578     }
    579 
    580     bool operator==(SpecIterator Other) const {
    581       return SetIter == Other.SetIter;
    582     }
    583     bool operator!=(SpecIterator Other) const {
    584       return SetIter != Other.SetIter;
    585     }
    586   };
    587 
    588   template <typename EntryType>
    589   static SpecIterator<EntryType>
    590   makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
    591     return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
    592   }
    593 
    594   template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
    595   findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
    596                          const TemplateArgument *Args, unsigned NumArgs,
    597                          void *&InsertPos);
    598 
    599   struct CommonBase {
    600     CommonBase() : InstantiatedFromMember(0, false) { }
    601 
    602     /// \brief The template from which this was most
    603     /// directly instantiated (or null).
    604     ///
    605     /// The boolean value indicates whether this template
    606     /// was explicitly specialized.
    607     llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
    608       InstantiatedFromMember;
    609   };
    610 
    611   /// \brief Pointer to the common data shared by all declarations of this
    612   /// template.
    613   mutable CommonBase *Common;
    614 
    615   /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
    616   /// the same template. Calling this routine may implicitly allocate memory
    617   /// for the common pointer.
    618   CommonBase *getCommonPtr() const;
    619 
    620   virtual CommonBase *newCommon(ASTContext &C) const = 0;
    621 
    622   // Construct a template decl with name, parameters, and templated element.
    623   RedeclarableTemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
    624                            DeclarationName Name, TemplateParameterList *Params,
    625                            NamedDecl *Decl)
    626     : TemplateDecl(DK, DC, L, Name, Params, Decl), Common() { }
    627 
    628 public:
    629   template <class decl_type> friend class RedeclarableTemplate;
    630 
    631   /// \brief Retrieves the canonical declaration of this template.
    632   RedeclarableTemplateDecl *getCanonicalDecl() { return getFirstDeclaration(); }
    633   const RedeclarableTemplateDecl *getCanonicalDecl() const {
    634     return getFirstDeclaration();
    635   }
    636 
    637   /// \brief Determines whether this template was a specialization of a
    638   /// member template.
    639   ///
    640   /// In the following example, the function template \c X<int>::f and the
    641   /// member template \c X<int>::Inner are member specializations.
    642   ///
    643   /// \code
    644   /// template<typename T>
    645   /// struct X {
    646   ///   template<typename U> void f(T, U);
    647   ///   template<typename U> struct Inner;
    648   /// };
    649   ///
    650   /// template<> template<typename T>
    651   /// void X<int>::f(int, T);
    652   /// template<> template<typename T>
    653   /// struct X<int>::Inner { /* ... */ };
    654   /// \endcode
    655   bool isMemberSpecialization() const {
    656     return getCommonPtr()->InstantiatedFromMember.getInt();
    657   }
    658 
    659   /// \brief Note that this member template is a specialization.
    660   void setMemberSpecialization() {
    661     assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
    662            "Only member templates can be member template specializations");
    663     getCommonPtr()->InstantiatedFromMember.setInt(true);
    664   }
    665 
    666   /// \brief Retrieve the member template from which this template was
    667   /// instantiated, or NULL if this template was not instantiated from a
    668   /// member template.
    669   ///
    670   /// A template is instantiated from a member template when the member
    671   /// template itself is part of a class template (or member thereof). For
    672   /// example, given
    673   ///
    674   /// \code
    675   /// template<typename T>
    676   /// struct X {
    677   ///   template<typename U> void f(T, U);
    678   /// };
    679   ///
    680   /// void test(X<int> x) {
    681   ///   x.f(1, 'a');
    682   /// };
    683   /// \endcode
    684   ///
    685   /// \c X<int>::f is a FunctionTemplateDecl that describes the function
    686   /// template
    687   ///
    688   /// \code
    689   /// template<typename U> void X<int>::f(int, U);
    690   /// \endcode
    691   ///
    692   /// which was itself created during the instantiation of \c X<int>. Calling
    693   /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
    694   /// retrieve the FunctionTemplateDecl for the original template \c f within
    695   /// the class template \c X<T>, i.e.,
    696   ///
    697   /// \code
    698   /// template<typename T>
    699   /// template<typename U>
    700   /// void X<T>::f(T, U);
    701   /// \endcode
    702   RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
    703     return getCommonPtr()->InstantiatedFromMember.getPointer();
    704   }
    705 
    706   void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
    707     assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
    708     getCommonPtr()->InstantiatedFromMember.setPointer(TD);
    709   }
    710 
    711   typedef redeclarable_base::redecl_iterator redecl_iterator;
    712   using redeclarable_base::redecls_begin;
    713   using redeclarable_base::redecls_end;
    714   using redeclarable_base::getPreviousDecl;
    715   using redeclarable_base::getMostRecentDecl;
    716 
    717   // Implement isa/cast/dyncast/etc.
    718   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    719   static bool classofKind(Kind K) {
    720     return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
    721   }
    722 
    723   friend class ASTReader;
    724   friend class ASTDeclReader;
    725   friend class ASTDeclWriter;
    726 };
    727 
    728 template <> struct RedeclarableTemplateDecl::
    729 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
    730   typedef FunctionDecl DeclType;
    731 
    732   static DeclType *
    733   getMostRecentDecl(FunctionTemplateSpecializationInfo *I) {
    734     return I->Function->getMostRecentDecl();
    735   }
    736 };
    737 
    738 /// Declaration of a template function.
    739 class FunctionTemplateDecl : public RedeclarableTemplateDecl {
    740   static void DeallocateCommon(void *Ptr);
    741 
    742 protected:
    743   /// \brief Data that is common to all of the declarations of a given
    744   /// function template.
    745   struct Common : CommonBase {
    746     Common() : InjectedArgs(0) { }
    747 
    748     /// \brief The function template specializations for this function
    749     /// template, including explicit specializations and instantiations.
    750     llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
    751 
    752     /// \brief The set of "injected" template arguments used within this
    753     /// function template.
    754     ///
    755     /// This pointer refers to the template arguments (there are as
    756     /// many template arguments as template parameaters) for the function
    757     /// template, and is allocated lazily, since most function templates do not
    758     /// require the use of this information.
    759     TemplateArgument *InjectedArgs;
    760   };
    761 
    762   FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
    763                        TemplateParameterList *Params, NamedDecl *Decl)
    764     : RedeclarableTemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl) { }
    765 
    766   CommonBase *newCommon(ASTContext &C) const;
    767 
    768   Common *getCommonPtr() const {
    769     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
    770   }
    771 
    772   friend class FunctionDecl;
    773 
    774   /// \brief Retrieve the set of function template specializations of this
    775   /// function template.
    776   llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
    777   getSpecializations() const {
    778     return getCommonPtr()->Specializations;
    779   }
    780 
    781   /// \brief Add a specialization of this function template.
    782   ///
    783   /// \param InsertPos Insert position in the FoldingSetVector, must have been
    784   ///        retrieved by an earlier call to findSpecialization().
    785   void addSpecialization(FunctionTemplateSpecializationInfo* Info,
    786                          void *InsertPos);
    787 
    788 public:
    789   /// Get the underlying function declaration of the template.
    790   FunctionDecl *getTemplatedDecl() const {
    791     return static_cast<FunctionDecl*>(TemplatedDecl);
    792   }
    793 
    794   /// Returns whether this template declaration defines the primary
    795   /// pattern.
    796   bool isThisDeclarationADefinition() const {
    797     return getTemplatedDecl()->isThisDeclarationADefinition();
    798   }
    799 
    800   /// \brief Return the specialization with the provided arguments if it exists,
    801   /// otherwise return the insertion point.
    802   FunctionDecl *findSpecialization(const TemplateArgument *Args,
    803                                    unsigned NumArgs, void *&InsertPos);
    804 
    805   FunctionTemplateDecl *getCanonicalDecl() {
    806     return cast<FunctionTemplateDecl>(
    807              RedeclarableTemplateDecl::getCanonicalDecl());
    808   }
    809   const FunctionTemplateDecl *getCanonicalDecl() const {
    810     return cast<FunctionTemplateDecl>(
    811              RedeclarableTemplateDecl::getCanonicalDecl());
    812   }
    813 
    814   /// \brief Retrieve the previous declaration of this function template, or
    815   /// NULL if no such declaration exists.
    816   FunctionTemplateDecl *getPreviousDecl() {
    817     return cast_or_null<FunctionTemplateDecl>(
    818              RedeclarableTemplateDecl::getPreviousDecl());
    819   }
    820 
    821   /// \brief Retrieve the previous declaration of this function template, or
    822   /// NULL if no such declaration exists.
    823   const FunctionTemplateDecl *getPreviousDecl() const {
    824     return cast_or_null<FunctionTemplateDecl>(
    825              RedeclarableTemplateDecl::getPreviousDecl());
    826   }
    827 
    828   FunctionTemplateDecl *getInstantiatedFromMemberTemplate() {
    829     return cast_or_null<FunctionTemplateDecl>(
    830              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
    831   }
    832 
    833   typedef SpecIterator<FunctionTemplateSpecializationInfo> spec_iterator;
    834 
    835   spec_iterator spec_begin() const {
    836     return makeSpecIterator(getSpecializations(), false);
    837   }
    838 
    839   spec_iterator spec_end() const {
    840     return makeSpecIterator(getSpecializations(), true);
    841   }
    842 
    843   /// \brief Retrieve the "injected" template arguments that correspond to the
    844   /// template parameters of this function template.
    845   ///
    846   /// Although the C++ standard has no notion of the "injected" template
    847   /// arguments for a function template, the notion is convenient when
    848   /// we need to perform substitutions inside the definition of a function
    849   /// template.
    850   std::pair<const TemplateArgument *, unsigned> getInjectedTemplateArgs();
    851 
    852   /// \brief Create a function template node.
    853   static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
    854                                       SourceLocation L,
    855                                       DeclarationName Name,
    856                                       TemplateParameterList *Params,
    857                                       NamedDecl *Decl);
    858 
    859   /// \brief Create an empty function template node.
    860   static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
    861 
    862   // Implement isa/cast/dyncast support
    863   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    864   static bool classofKind(Kind K) { return K == FunctionTemplate; }
    865 
    866   friend class ASTDeclReader;
    867   friend class ASTDeclWriter;
    868 };
    869 
    870 //===----------------------------------------------------------------------===//
    871 // Kinds of Template Parameters
    872 //===----------------------------------------------------------------------===//
    873 
    874 /// \brief Defines the position of a template parameter within a template
    875 /// parameter list.
    876 ///
    877 /// Because template parameter can be listed
    878 /// sequentially for out-of-line template members, each template parameter is
    879 /// given a Depth - the nesting of template parameter scopes - and a Position -
    880 /// the occurrence within the parameter list.
    881 /// This class is inheritedly privately by different kinds of template
    882 /// parameters and is not part of the Decl hierarchy. Just a facility.
    883 class TemplateParmPosition {
    884 protected:
    885   // FIXME: This should probably never be called, but it's here as
    886   TemplateParmPosition()
    887     : Depth(0), Position(0)
    888   { /* llvm_unreachable("Cannot create positionless template parameter"); */ }
    889 
    890   TemplateParmPosition(unsigned D, unsigned P)
    891     : Depth(D), Position(P)
    892   { }
    893 
    894   // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
    895   // position? Maybe?
    896   unsigned Depth;
    897   unsigned Position;
    898 
    899 public:
    900   /// Get the nesting depth of the template parameter.
    901   unsigned getDepth() const { return Depth; }
    902   void setDepth(unsigned D) { Depth = D; }
    903 
    904   /// Get the position of the template parameter within its parameter list.
    905   unsigned getPosition() const { return Position; }
    906   void setPosition(unsigned P) { Position = P; }
    907 
    908   /// Get the index of the template parameter within its parameter list.
    909   unsigned getIndex() const { return Position; }
    910 };
    911 
    912 /// \brief Declaration of a template type parameter.
    913 ///
    914 /// For example, "T" in
    915 /// \code
    916 /// template<typename T> class vector;
    917 /// \endcode
    918 class TemplateTypeParmDecl : public TypeDecl {
    919   /// \brief Whether this template type parameter was declaration with
    920   /// the 'typename' keyword.
    921   ///
    922   /// If false, it was declared with the 'class' keyword.
    923   bool Typename : 1;
    924 
    925   /// \brief Whether this template type parameter inherited its
    926   /// default argument.
    927   bool InheritedDefault : 1;
    928 
    929   /// \brief The default template argument, if any.
    930   TypeSourceInfo *DefaultArgument;
    931 
    932   TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
    933                        SourceLocation IdLoc, IdentifierInfo *Id,
    934                        bool Typename)
    935     : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
    936       InheritedDefault(false), DefaultArgument() { }
    937 
    938   /// Sema creates these on the stack during auto type deduction.
    939   friend class Sema;
    940 
    941 public:
    942   static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
    943                                       SourceLocation KeyLoc,
    944                                       SourceLocation NameLoc,
    945                                       unsigned D, unsigned P,
    946                                       IdentifierInfo *Id, bool Typename,
    947                                       bool ParameterPack);
    948   static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
    949                                                   unsigned ID);
    950 
    951   /// \brief Whether this template type parameter was declared with
    952   /// the 'typename' keyword.
    953   ///
    954   /// If not, it was declared with the 'class' keyword.
    955   bool wasDeclaredWithTypename() const { return Typename; }
    956 
    957   /// \brief Determine whether this template parameter has a default
    958   /// argument.
    959   bool hasDefaultArgument() const { return DefaultArgument != 0; }
    960 
    961   /// \brief Retrieve the default argument, if any.
    962   QualType getDefaultArgument() const { return DefaultArgument->getType(); }
    963 
    964   /// \brief Retrieves the default argument's source information, if any.
    965   TypeSourceInfo *getDefaultArgumentInfo() const { return DefaultArgument; }
    966 
    967   /// \brief Retrieves the location of the default argument declaration.
    968   SourceLocation getDefaultArgumentLoc() const;
    969 
    970   /// \brief Determines whether the default argument was inherited
    971   /// from a previous declaration of this template.
    972   bool defaultArgumentWasInherited() const { return InheritedDefault; }
    973 
    974   /// \brief Set the default argument for this template parameter, and
    975   /// whether that default argument was inherited from another
    976   /// declaration.
    977   void setDefaultArgument(TypeSourceInfo *DefArg, bool Inherited) {
    978     DefaultArgument = DefArg;
    979     InheritedDefault = Inherited;
    980   }
    981 
    982   /// \brief Removes the default argument of this template parameter.
    983   void removeDefaultArgument() {
    984     DefaultArgument = 0;
    985     InheritedDefault = false;
    986   }
    987 
    988   /// \brief Set whether this template type parameter was declared with
    989   /// the 'typename' or 'class' keyword.
    990   void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
    991 
    992   /// \brief Retrieve the depth of the template parameter.
    993   unsigned getDepth() const;
    994 
    995   /// \brief Retrieve the index of the template parameter.
    996   unsigned getIndex() const;
    997 
    998   /// \brief Returns whether this is a parameter pack.
    999   bool isParameterPack() const;
   1000 
   1001   SourceRange getSourceRange() const LLVM_READONLY;
   1002 
   1003   // Implement isa/cast/dyncast/etc.
   1004   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1005   static bool classofKind(Kind K) { return K == TemplateTypeParm; }
   1006 };
   1007 
   1008 /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
   1009 /// e.g., "Size" in
   1010 /// @code
   1011 /// template<int Size> class array { };
   1012 /// @endcode
   1013 class NonTypeTemplateParmDecl
   1014   : public DeclaratorDecl, protected TemplateParmPosition {
   1015   /// \brief The default template argument, if any, and whether or not
   1016   /// it was inherited.
   1017   llvm::PointerIntPair<Expr*, 1, bool> DefaultArgumentAndInherited;
   1018 
   1019   // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
   1020   // down here to save memory.
   1021 
   1022   /// \brief Whether this non-type template parameter is a parameter pack.
   1023   bool ParameterPack;
   1024 
   1025   /// \brief Whether this non-type template parameter is an "expanded"
   1026   /// parameter pack, meaning that its type is a pack expansion and we
   1027   /// already know the set of types that expansion expands to.
   1028   bool ExpandedParameterPack;
   1029 
   1030   /// \brief The number of types in an expanded parameter pack.
   1031   unsigned NumExpandedTypes;
   1032 
   1033   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
   1034                           SourceLocation IdLoc, unsigned D, unsigned P,
   1035                           IdentifierInfo *Id, QualType T,
   1036                           bool ParameterPack, TypeSourceInfo *TInfo)
   1037     : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
   1038       TemplateParmPosition(D, P), DefaultArgumentAndInherited(0, false),
   1039       ParameterPack(ParameterPack), ExpandedParameterPack(false),
   1040       NumExpandedTypes(0)
   1041   { }
   1042 
   1043   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
   1044                           SourceLocation IdLoc, unsigned D, unsigned P,
   1045                           IdentifierInfo *Id, QualType T,
   1046                           TypeSourceInfo *TInfo,
   1047                           const QualType *ExpandedTypes,
   1048                           unsigned NumExpandedTypes,
   1049                           TypeSourceInfo **ExpandedTInfos);
   1050 
   1051   friend class ASTDeclReader;
   1052 
   1053 public:
   1054   static NonTypeTemplateParmDecl *
   1055   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
   1056          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
   1057          QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
   1058 
   1059   static NonTypeTemplateParmDecl *
   1060   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
   1061          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
   1062          QualType T, TypeSourceInfo *TInfo,
   1063          const QualType *ExpandedTypes, unsigned NumExpandedTypes,
   1064          TypeSourceInfo **ExpandedTInfos);
   1065 
   1066   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1067                                                      unsigned ID);
   1068   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1069                                                      unsigned ID,
   1070                                                      unsigned NumExpandedTypes);
   1071 
   1072   using TemplateParmPosition::getDepth;
   1073   using TemplateParmPosition::setDepth;
   1074   using TemplateParmPosition::getPosition;
   1075   using TemplateParmPosition::setPosition;
   1076   using TemplateParmPosition::getIndex;
   1077 
   1078   SourceRange getSourceRange() const LLVM_READONLY;
   1079 
   1080   /// \brief Determine whether this template parameter has a default
   1081   /// argument.
   1082   bool hasDefaultArgument() const {
   1083     return DefaultArgumentAndInherited.getPointer() != 0;
   1084   }
   1085 
   1086   /// \brief Retrieve the default argument, if any.
   1087   Expr *getDefaultArgument() const {
   1088     return DefaultArgumentAndInherited.getPointer();
   1089   }
   1090 
   1091   /// \brief Retrieve the location of the default argument, if any.
   1092   SourceLocation getDefaultArgumentLoc() const;
   1093 
   1094   /// \brief Determines whether the default argument was inherited
   1095   /// from a previous declaration of this template.
   1096   bool defaultArgumentWasInherited() const {
   1097     return DefaultArgumentAndInherited.getInt();
   1098   }
   1099 
   1100   /// \brief Set the default argument for this template parameter, and
   1101   /// whether that default argument was inherited from another
   1102   /// declaration.
   1103   void setDefaultArgument(Expr *DefArg, bool Inherited) {
   1104     DefaultArgumentAndInherited.setPointer(DefArg);
   1105     DefaultArgumentAndInherited.setInt(Inherited);
   1106   }
   1107 
   1108   /// \brief Removes the default argument of this template parameter.
   1109   void removeDefaultArgument() {
   1110     DefaultArgumentAndInherited.setPointer(0);
   1111     DefaultArgumentAndInherited.setInt(false);
   1112   }
   1113 
   1114   /// \brief Whether this parameter is a non-type template parameter pack.
   1115   ///
   1116   /// If the parameter is a parameter pack, the type may be a
   1117   /// \c PackExpansionType. In the following example, the \c Dims parameter
   1118   /// is a parameter pack (whose type is 'unsigned').
   1119   ///
   1120   /// \code
   1121   /// template<typename T, unsigned ...Dims> struct multi_array;
   1122   /// \endcode
   1123   bool isParameterPack() const { return ParameterPack; }
   1124 
   1125   /// \brief Whether this parameter pack is a pack expansion.
   1126   ///
   1127   /// A non-type template parameter pack is a pack expansion if its type
   1128   /// contains an unexpanded parameter pack. In this case, we will have
   1129   /// built a PackExpansionType wrapping the type.
   1130   bool isPackExpansion() const {
   1131     return ParameterPack && getType()->getAs<PackExpansionType>();
   1132   }
   1133 
   1134   /// \brief Whether this parameter is a non-type template parameter pack
   1135   /// that has a known list of different types at different positions.
   1136   ///
   1137   /// A parameter pack is an expanded parameter pack when the original
   1138   /// parameter pack's type was itself a pack expansion, and that expansion
   1139   /// has already been expanded. For example, given:
   1140   ///
   1141   /// \code
   1142   /// template<typename ...Types>
   1143   /// struct X {
   1144   ///   template<Types ...Values>
   1145   ///   struct Y { /* ... */ };
   1146   /// };
   1147   /// \endcode
   1148   ///
   1149   /// The parameter pack \c Values has a \c PackExpansionType as its type,
   1150   /// which expands \c Types. When \c Types is supplied with template arguments
   1151   /// by instantiating \c X, the instantiation of \c Values becomes an
   1152   /// expanded parameter pack. For example, instantiating
   1153   /// \c X<int, unsigned int> results in \c Values being an expanded parameter
   1154   /// pack with expansion types \c int and \c unsigned int.
   1155   ///
   1156   /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
   1157   /// return the expansion types.
   1158   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
   1159 
   1160   /// \brief Retrieves the number of expansion types in an expanded parameter
   1161   /// pack.
   1162   unsigned getNumExpansionTypes() const {
   1163     assert(ExpandedParameterPack && "Not an expansion parameter pack");
   1164     return NumExpandedTypes;
   1165   }
   1166 
   1167   /// \brief Retrieve a particular expansion type within an expanded parameter
   1168   /// pack.
   1169   QualType getExpansionType(unsigned I) const {
   1170     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
   1171     void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
   1172     return QualType::getFromOpaquePtr(TypesAndInfos[2*I]);
   1173   }
   1174 
   1175   /// \brief Retrieve a particular expansion type source info within an
   1176   /// expanded parameter pack.
   1177   TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
   1178     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
   1179     void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
   1180     return static_cast<TypeSourceInfo *>(TypesAndInfos[2*I+1]);
   1181   }
   1182 
   1183   // Implement isa/cast/dyncast/etc.
   1184   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1185   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
   1186 };
   1187 
   1188 /// TemplateTemplateParmDecl - Declares a template template parameter,
   1189 /// e.g., "T" in
   1190 /// @code
   1191 /// template <template <typename> class T> class container { };
   1192 /// @endcode
   1193 /// A template template parameter is a TemplateDecl because it defines the
   1194 /// name of a template and the template parameters allowable for substitution.
   1195 class TemplateTemplateParmDecl : public TemplateDecl,
   1196                                  protected TemplateParmPosition
   1197 {
   1198   virtual void anchor();
   1199 
   1200   /// DefaultArgument - The default template argument, if any.
   1201   TemplateArgumentLoc DefaultArgument;
   1202   /// Whether or not the default argument was inherited.
   1203   bool DefaultArgumentWasInherited;
   1204 
   1205   /// \brief Whether this parameter is a parameter pack.
   1206   bool ParameterPack;
   1207 
   1208   /// \brief Whether this template template parameter is an "expanded"
   1209   /// parameter pack, meaning that it is a pack expansion and we
   1210   /// already know the set of template parameters that expansion expands to.
   1211   bool ExpandedParameterPack;
   1212 
   1213   /// \brief The number of parameters in an expanded parameter pack.
   1214   unsigned NumExpandedParams;
   1215 
   1216   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
   1217                            unsigned D, unsigned P, bool ParameterPack,
   1218                            IdentifierInfo *Id, TemplateParameterList *Params)
   1219     : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
   1220       TemplateParmPosition(D, P), DefaultArgument(),
   1221       DefaultArgumentWasInherited(false), ParameterPack(ParameterPack),
   1222       ExpandedParameterPack(false), NumExpandedParams(0)
   1223     { }
   1224 
   1225   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
   1226                            unsigned D, unsigned P,
   1227                            IdentifierInfo *Id, TemplateParameterList *Params,
   1228                            unsigned NumExpansions,
   1229                            TemplateParameterList * const *Expansions);
   1230 
   1231 public:
   1232   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
   1233                                           SourceLocation L, unsigned D,
   1234                                           unsigned P, bool ParameterPack,
   1235                                           IdentifierInfo *Id,
   1236                                           TemplateParameterList *Params);
   1237   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
   1238                                           SourceLocation L, unsigned D,
   1239                                           unsigned P,
   1240                                           IdentifierInfo *Id,
   1241                                           TemplateParameterList *Params,
   1242                                  ArrayRef<TemplateParameterList *> Expansions);
   1243 
   1244   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1245                                                       unsigned ID);
   1246   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1247                                                       unsigned ID,
   1248                                                       unsigned NumExpansions);
   1249 
   1250   using TemplateParmPosition::getDepth;
   1251   using TemplateParmPosition::getPosition;
   1252   using TemplateParmPosition::getIndex;
   1253 
   1254   /// \brief Whether this template template parameter is a template
   1255   /// parameter pack.
   1256   ///
   1257   /// \code
   1258   /// template<template <class T> ...MetaFunctions> struct Apply;
   1259   /// \endcode
   1260   bool isParameterPack() const { return ParameterPack; }
   1261 
   1262   /// \brief Whether this parameter pack is a pack expansion.
   1263   ///
   1264   /// A template template parameter pack is a pack expansion if its template
   1265   /// parameter list contains an unexpanded parameter pack.
   1266   bool isPackExpansion() const {
   1267     return ParameterPack &&
   1268            getTemplateParameters()->containsUnexpandedParameterPack();
   1269   }
   1270 
   1271   /// \brief Whether this parameter is a template template parameter pack that
   1272   /// has a known list of different template parameter lists at different
   1273   /// positions.
   1274   ///
   1275   /// A parameter pack is an expanded parameter pack when the original parameter
   1276   /// pack's template parameter list was itself a pack expansion, and that
   1277   /// expansion has already been expanded. For exampe, given:
   1278   ///
   1279   /// \code
   1280   /// template<typename...Types> struct Outer {
   1281   ///   template<template<Types> class...Templates> struct Inner;
   1282   /// };
   1283   /// \endcode
   1284   ///
   1285   /// The parameter pack \c Templates is a pack expansion, which expands the
   1286   /// pack \c Types. When \c Types is supplied with template arguments by
   1287   /// instantiating \c Outer, the instantiation of \c Templates is an expanded
   1288   /// parameter pack.
   1289   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
   1290 
   1291   /// \brief Retrieves the number of expansion template parameters in
   1292   /// an expanded parameter pack.
   1293   unsigned getNumExpansionTemplateParameters() const {
   1294     assert(ExpandedParameterPack && "Not an expansion parameter pack");
   1295     return NumExpandedParams;
   1296   }
   1297 
   1298   /// \brief Retrieve a particular expansion type within an expanded parameter
   1299   /// pack.
   1300   TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
   1301     assert(I < NumExpandedParams && "Out-of-range expansion type index");
   1302     return reinterpret_cast<TemplateParameterList *const *>(this + 1)[I];
   1303   }
   1304 
   1305   /// \brief Determine whether this template parameter has a default
   1306   /// argument.
   1307   bool hasDefaultArgument() const {
   1308     return !DefaultArgument.getArgument().isNull();
   1309   }
   1310 
   1311   /// \brief Retrieve the default argument, if any.
   1312   const TemplateArgumentLoc &getDefaultArgument() const {
   1313     return DefaultArgument;
   1314   }
   1315 
   1316   /// \brief Retrieve the location of the default argument, if any.
   1317   SourceLocation getDefaultArgumentLoc() const;
   1318 
   1319   /// \brief Determines whether the default argument was inherited
   1320   /// from a previous declaration of this template.
   1321   bool defaultArgumentWasInherited() const {
   1322     return DefaultArgumentWasInherited;
   1323   }
   1324 
   1325   /// \brief Set the default argument for this template parameter, and
   1326   /// whether that default argument was inherited from another
   1327   /// declaration.
   1328   void setDefaultArgument(const TemplateArgumentLoc &DefArg, bool Inherited) {
   1329     DefaultArgument = DefArg;
   1330     DefaultArgumentWasInherited = Inherited;
   1331   }
   1332 
   1333   /// \brief Removes the default argument of this template parameter.
   1334   void removeDefaultArgument() {
   1335     DefaultArgument = TemplateArgumentLoc();
   1336     DefaultArgumentWasInherited = false;
   1337   }
   1338 
   1339   SourceRange getSourceRange() const LLVM_READONLY {
   1340     SourceLocation End = getLocation();
   1341     if (hasDefaultArgument() && !defaultArgumentWasInherited())
   1342       End = getDefaultArgument().getSourceRange().getEnd();
   1343     return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
   1344   }
   1345 
   1346   // Implement isa/cast/dyncast/etc.
   1347   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1348   static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
   1349 
   1350   friend class ASTDeclReader;
   1351   friend class ASTDeclWriter;
   1352 };
   1353 
   1354 /// \brief Represents a class template specialization, which refers to
   1355 /// a class template with a given set of template arguments.
   1356 ///
   1357 /// Class template specializations represent both explicit
   1358 /// specialization of class templates, as in the example below, and
   1359 /// implicit instantiations of class templates.
   1360 ///
   1361 /// \code
   1362 /// template<typename T> class array;
   1363 ///
   1364 /// template<>
   1365 /// class array<bool> { }; // class template specialization array<bool>
   1366 /// \endcode
   1367 class ClassTemplateSpecializationDecl
   1368   : public CXXRecordDecl, public llvm::FoldingSetNode {
   1369 
   1370   /// \brief Structure that stores information about a class template
   1371   /// specialization that was instantiated from a class template partial
   1372   /// specialization.
   1373   struct SpecializedPartialSpecialization {
   1374     /// \brief The class template partial specialization from which this
   1375     /// class template specialization was instantiated.
   1376     ClassTemplatePartialSpecializationDecl *PartialSpecialization;
   1377 
   1378     /// \brief The template argument list deduced for the class template
   1379     /// partial specialization itself.
   1380     TemplateArgumentList *TemplateArgs;
   1381   };
   1382 
   1383   /// \brief The template that this specialization specializes
   1384   llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
   1385     SpecializedTemplate;
   1386 
   1387   /// \brief Further info for explicit template specialization/instantiation.
   1388   struct ExplicitSpecializationInfo {
   1389     /// \brief The type-as-written.
   1390     TypeSourceInfo *TypeAsWritten;
   1391     /// \brief The location of the extern keyword.
   1392     SourceLocation ExternLoc;
   1393     /// \brief The location of the template keyword.
   1394     SourceLocation TemplateKeywordLoc;
   1395 
   1396     ExplicitSpecializationInfo()
   1397       : TypeAsWritten(0), ExternLoc(), TemplateKeywordLoc() {}
   1398   };
   1399 
   1400   /// \brief Further info for explicit template specialization/instantiation.
   1401   /// Does not apply to implicit specializations.
   1402   ExplicitSpecializationInfo *ExplicitInfo;
   1403 
   1404   /// \brief The template arguments used to describe this specialization.
   1405   TemplateArgumentList *TemplateArgs;
   1406 
   1407   /// \brief The point where this template was instantiated (if any)
   1408   SourceLocation PointOfInstantiation;
   1409 
   1410   /// \brief The kind of specialization this declaration refers to.
   1411   /// Really a value of type TemplateSpecializationKind.
   1412   unsigned SpecializationKind : 3;
   1413 
   1414 protected:
   1415   ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
   1416                                   DeclContext *DC, SourceLocation StartLoc,
   1417                                   SourceLocation IdLoc,
   1418                                   ClassTemplateDecl *SpecializedTemplate,
   1419                                   const TemplateArgument *Args,
   1420                                   unsigned NumArgs,
   1421                                   ClassTemplateSpecializationDecl *PrevDecl);
   1422 
   1423   explicit ClassTemplateSpecializationDecl(Kind DK);
   1424 
   1425 public:
   1426   static ClassTemplateSpecializationDecl *
   1427   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
   1428          SourceLocation StartLoc, SourceLocation IdLoc,
   1429          ClassTemplateDecl *SpecializedTemplate,
   1430          const TemplateArgument *Args,
   1431          unsigned NumArgs,
   1432          ClassTemplateSpecializationDecl *PrevDecl);
   1433   static ClassTemplateSpecializationDecl *
   1434   CreateDeserialized(ASTContext &C, unsigned ID);
   1435 
   1436   virtual void getNameForDiagnostic(raw_ostream &OS,
   1437                                     const PrintingPolicy &Policy,
   1438                                     bool Qualified) const;
   1439 
   1440   ClassTemplateSpecializationDecl *getMostRecentDecl() {
   1441     CXXRecordDecl *Recent
   1442         = cast<CXXRecordDecl>(CXXRecordDecl::getMostRecentDecl());
   1443     if (!isa<ClassTemplateSpecializationDecl>(Recent)) {
   1444       // FIXME: Does injected class name need to be in the redeclarations chain?
   1445       assert(Recent->isInjectedClassName() && Recent->getPreviousDecl());
   1446       Recent = Recent->getPreviousDecl();
   1447     }
   1448     return cast<ClassTemplateSpecializationDecl>(Recent);
   1449   }
   1450 
   1451   /// \brief Retrieve the template that this specialization specializes.
   1452   ClassTemplateDecl *getSpecializedTemplate() const;
   1453 
   1454   /// \brief Retrieve the template arguments of the class template
   1455   /// specialization.
   1456   const TemplateArgumentList &getTemplateArgs() const {
   1457     return *TemplateArgs;
   1458   }
   1459 
   1460   /// \brief Determine the kind of specialization that this
   1461   /// declaration represents.
   1462   TemplateSpecializationKind getSpecializationKind() const {
   1463     return static_cast<TemplateSpecializationKind>(SpecializationKind);
   1464   }
   1465 
   1466   bool isExplicitSpecialization() const {
   1467     return getSpecializationKind() == TSK_ExplicitSpecialization;
   1468   }
   1469 
   1470   /// \brief True if this declaration is an explicit specialization,
   1471   /// explicit instantiation declaration, or explicit instantiation
   1472   /// definition.
   1473   bool isExplicitInstantiationOrSpecialization() const {
   1474     switch (getTemplateSpecializationKind()) {
   1475     case TSK_ExplicitSpecialization:
   1476     case TSK_ExplicitInstantiationDeclaration:
   1477     case TSK_ExplicitInstantiationDefinition:
   1478       return true;
   1479 
   1480     case TSK_Undeclared:
   1481     case TSK_ImplicitInstantiation:
   1482       return false;
   1483     }
   1484     llvm_unreachable("bad template specialization kind");
   1485   }
   1486 
   1487   void setSpecializationKind(TemplateSpecializationKind TSK) {
   1488     SpecializationKind = TSK;
   1489   }
   1490 
   1491   /// \brief Get the point of instantiation (if any), or null if none.
   1492   SourceLocation getPointOfInstantiation() const {
   1493     return PointOfInstantiation;
   1494   }
   1495 
   1496   void setPointOfInstantiation(SourceLocation Loc) {
   1497     assert(Loc.isValid() && "point of instantiation must be valid!");
   1498     PointOfInstantiation = Loc;
   1499   }
   1500 
   1501   /// \brief If this class template specialization is an instantiation of
   1502   /// a template (rather than an explicit specialization), return the
   1503   /// class template or class template partial specialization from which it
   1504   /// was instantiated.
   1505   llvm::PointerUnion<ClassTemplateDecl *,
   1506                      ClassTemplatePartialSpecializationDecl *>
   1507   getInstantiatedFrom() const {
   1508     if (getSpecializationKind() != TSK_ImplicitInstantiation &&
   1509         getSpecializationKind() != TSK_ExplicitInstantiationDefinition &&
   1510         getSpecializationKind() != TSK_ExplicitInstantiationDeclaration)
   1511       return llvm::PointerUnion<ClassTemplateDecl *,
   1512                                 ClassTemplatePartialSpecializationDecl *>();
   1513 
   1514     if (SpecializedPartialSpecialization *PartialSpec
   1515           = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
   1516       return PartialSpec->PartialSpecialization;
   1517 
   1518     return SpecializedTemplate.get<ClassTemplateDecl*>();
   1519   }
   1520 
   1521   /// \brief Retrieve the class template or class template partial
   1522   /// specialization which was specialized by this.
   1523   llvm::PointerUnion<ClassTemplateDecl *,
   1524                      ClassTemplatePartialSpecializationDecl *>
   1525   getSpecializedTemplateOrPartial() const {
   1526     if (SpecializedPartialSpecialization *PartialSpec
   1527           = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
   1528       return PartialSpec->PartialSpecialization;
   1529 
   1530     return SpecializedTemplate.get<ClassTemplateDecl*>();
   1531   }
   1532 
   1533   /// \brief Retrieve the set of template arguments that should be used
   1534   /// to instantiate members of the class template or class template partial
   1535   /// specialization from which this class template specialization was
   1536   /// instantiated.
   1537   ///
   1538   /// \returns For a class template specialization instantiated from the primary
   1539   /// template, this function will return the same template arguments as
   1540   /// getTemplateArgs(). For a class template specialization instantiated from
   1541   /// a class template partial specialization, this function will return the
   1542   /// deduced template arguments for the class template partial specialization
   1543   /// itself.
   1544   const TemplateArgumentList &getTemplateInstantiationArgs() const {
   1545     if (SpecializedPartialSpecialization *PartialSpec
   1546         = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
   1547       return *PartialSpec->TemplateArgs;
   1548 
   1549     return getTemplateArgs();
   1550   }
   1551 
   1552   /// \brief Note that this class template specialization is actually an
   1553   /// instantiation of the given class template partial specialization whose
   1554   /// template arguments have been deduced.
   1555   void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
   1556                           TemplateArgumentList *TemplateArgs) {
   1557     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
   1558            "Already set to a class template partial specialization!");
   1559     SpecializedPartialSpecialization *PS
   1560       = new (getASTContext()) SpecializedPartialSpecialization();
   1561     PS->PartialSpecialization = PartialSpec;
   1562     PS->TemplateArgs = TemplateArgs;
   1563     SpecializedTemplate = PS;
   1564   }
   1565 
   1566   /// \brief Note that this class template specialization is an instantiation
   1567   /// of the given class template.
   1568   void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
   1569     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
   1570            "Previously set to a class template partial specialization!");
   1571     SpecializedTemplate = TemplDecl;
   1572   }
   1573 
   1574   /// \brief Sets the type of this specialization as it was written by
   1575   /// the user. This will be a class template specialization type.
   1576   void setTypeAsWritten(TypeSourceInfo *T) {
   1577     if (!ExplicitInfo)
   1578       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   1579     ExplicitInfo->TypeAsWritten = T;
   1580   }
   1581   /// \brief Gets the type of this specialization as it was written by
   1582   /// the user, if it was so written.
   1583   TypeSourceInfo *getTypeAsWritten() const {
   1584     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : 0;
   1585   }
   1586 
   1587   /// \brief Gets the location of the extern keyword, if present.
   1588   SourceLocation getExternLoc() const {
   1589     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
   1590   }
   1591   /// \brief Sets the location of the extern keyword.
   1592   void setExternLoc(SourceLocation Loc) {
   1593     if (!ExplicitInfo)
   1594       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   1595     ExplicitInfo->ExternLoc = Loc;
   1596   }
   1597 
   1598   /// \brief Sets the location of the template keyword.
   1599   void setTemplateKeywordLoc(SourceLocation Loc) {
   1600     if (!ExplicitInfo)
   1601       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   1602     ExplicitInfo->TemplateKeywordLoc = Loc;
   1603   }
   1604   /// \brief Gets the location of the template keyword, if present.
   1605   SourceLocation getTemplateKeywordLoc() const {
   1606     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
   1607   }
   1608 
   1609   SourceRange getSourceRange() const LLVM_READONLY;
   1610 
   1611   void Profile(llvm::FoldingSetNodeID &ID) const {
   1612     Profile(ID, TemplateArgs->data(), TemplateArgs->size(), getASTContext());
   1613   }
   1614 
   1615   static void
   1616   Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs,
   1617           unsigned NumTemplateArgs, ASTContext &Context) {
   1618     ID.AddInteger(NumTemplateArgs);
   1619     for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg)
   1620       TemplateArgs[Arg].Profile(ID, Context);
   1621   }
   1622 
   1623   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1624   static bool classofKind(Kind K) {
   1625     return K >= firstClassTemplateSpecialization &&
   1626            K <= lastClassTemplateSpecialization;
   1627   }
   1628 
   1629   friend class ASTDeclReader;
   1630   friend class ASTDeclWriter;
   1631 };
   1632 
   1633 class ClassTemplatePartialSpecializationDecl
   1634   : public ClassTemplateSpecializationDecl {
   1635   virtual void anchor();
   1636 
   1637   /// \brief The list of template parameters
   1638   TemplateParameterList* TemplateParams;
   1639 
   1640   /// \brief The source info for the template arguments as written.
   1641   /// FIXME: redundant with TypeAsWritten?
   1642   TemplateArgumentLoc *ArgsAsWritten;
   1643   unsigned NumArgsAsWritten;
   1644 
   1645   /// \brief Sequence number indicating when this class template partial
   1646   /// specialization was added to the set of partial specializations for
   1647   /// its owning class template.
   1648   unsigned SequenceNumber;
   1649 
   1650   /// \brief The class template partial specialization from which this
   1651   /// class template partial specialization was instantiated.
   1652   ///
   1653   /// The boolean value will be true to indicate that this class template
   1654   /// partial specialization was specialized at this level.
   1655   llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
   1656       InstantiatedFromMember;
   1657 
   1658   ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
   1659                                          DeclContext *DC,
   1660                                          SourceLocation StartLoc,
   1661                                          SourceLocation IdLoc,
   1662                                          TemplateParameterList *Params,
   1663                                          ClassTemplateDecl *SpecializedTemplate,
   1664                                          const TemplateArgument *Args,
   1665                                          unsigned NumArgs,
   1666                                          TemplateArgumentLoc *ArgInfos,
   1667                                          unsigned NumArgInfos,
   1668                                ClassTemplatePartialSpecializationDecl *PrevDecl,
   1669                                          unsigned SequenceNumber);
   1670 
   1671   ClassTemplatePartialSpecializationDecl()
   1672     : ClassTemplateSpecializationDecl(ClassTemplatePartialSpecialization),
   1673       TemplateParams(0), ArgsAsWritten(0),
   1674       NumArgsAsWritten(0), SequenceNumber(0),
   1675       InstantiatedFromMember(0, false) { }
   1676 
   1677 public:
   1678   static ClassTemplatePartialSpecializationDecl *
   1679   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
   1680          SourceLocation StartLoc, SourceLocation IdLoc,
   1681          TemplateParameterList *Params,
   1682          ClassTemplateDecl *SpecializedTemplate,
   1683          const TemplateArgument *Args,
   1684          unsigned NumArgs,
   1685          const TemplateArgumentListInfo &ArgInfos,
   1686          QualType CanonInjectedType,
   1687          ClassTemplatePartialSpecializationDecl *PrevDecl,
   1688          unsigned SequenceNumber);
   1689 
   1690   static ClassTemplatePartialSpecializationDecl *
   1691   CreateDeserialized(ASTContext &C, unsigned ID);
   1692 
   1693   ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
   1694     return cast<ClassTemplatePartialSpecializationDecl>(
   1695                    ClassTemplateSpecializationDecl::getMostRecentDecl());
   1696   }
   1697 
   1698   /// Get the list of template parameters
   1699   TemplateParameterList *getTemplateParameters() const {
   1700     return TemplateParams;
   1701   }
   1702 
   1703   /// Get the template arguments as written.
   1704   TemplateArgumentLoc *getTemplateArgsAsWritten() const {
   1705     return ArgsAsWritten;
   1706   }
   1707 
   1708   /// Get the number of template arguments as written.
   1709   unsigned getNumTemplateArgsAsWritten() const {
   1710     return NumArgsAsWritten;
   1711   }
   1712 
   1713   /// \brief Get the sequence number for this class template partial
   1714   /// specialization.
   1715   unsigned getSequenceNumber() const { return SequenceNumber; }
   1716 
   1717   /// \brief Retrieve the member class template partial specialization from
   1718   /// which this particular class template partial specialization was
   1719   /// instantiated.
   1720   ///
   1721   /// \code
   1722   /// template<typename T>
   1723   /// struct Outer {
   1724   ///   template<typename U> struct Inner;
   1725   ///   template<typename U> struct Inner<U*> { }; // #1
   1726   /// };
   1727   ///
   1728   /// Outer<float>::Inner<int*> ii;
   1729   /// \endcode
   1730   ///
   1731   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
   1732   /// end up instantiating the partial specialization
   1733   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
   1734   /// template partial specialization \c Outer<T>::Inner<U*>. Given
   1735   /// \c Outer<float>::Inner<U*>, this function would return
   1736   /// \c Outer<T>::Inner<U*>.
   1737   ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() {
   1738     ClassTemplatePartialSpecializationDecl *First
   1739       = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
   1740     return First->InstantiatedFromMember.getPointer();
   1741   }
   1742 
   1743   void setInstantiatedFromMember(
   1744                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
   1745     ClassTemplatePartialSpecializationDecl *First
   1746       = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
   1747     First->InstantiatedFromMember.setPointer(PartialSpec);
   1748   }
   1749 
   1750   /// \brief Determines whether this class template partial specialization
   1751   /// template was a specialization of a member partial specialization.
   1752   ///
   1753   /// In the following example, the member template partial specialization
   1754   /// \c X<int>::Inner<T*> is a member specialization.
   1755   ///
   1756   /// \code
   1757   /// template<typename T>
   1758   /// struct X {
   1759   ///   template<typename U> struct Inner;
   1760   ///   template<typename U> struct Inner<U*>;
   1761   /// };
   1762   ///
   1763   /// template<> template<typename T>
   1764   /// struct X<int>::Inner<T*> { /* ... */ };
   1765   /// \endcode
   1766   bool isMemberSpecialization() {
   1767     ClassTemplatePartialSpecializationDecl *First
   1768       = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
   1769     return First->InstantiatedFromMember.getInt();
   1770   }
   1771 
   1772   /// \brief Note that this member template is a specialization.
   1773   void setMemberSpecialization() {
   1774     ClassTemplatePartialSpecializationDecl *First
   1775       = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
   1776     assert(First->InstantiatedFromMember.getPointer() &&
   1777            "Only member templates can be member template specializations");
   1778     return First->InstantiatedFromMember.setInt(true);
   1779   }
   1780 
   1781   /// Retrieves the injected specialization type for this partial
   1782   /// specialization.  This is not the same as the type-decl-type for
   1783   /// this partial specialization, which is an InjectedClassNameType.
   1784   QualType getInjectedSpecializationType() const {
   1785     assert(getTypeForDecl() && "partial specialization has no type set!");
   1786     return cast<InjectedClassNameType>(getTypeForDecl())
   1787              ->getInjectedSpecializationType();
   1788   }
   1789 
   1790   // FIXME: Add Profile support!
   1791 
   1792   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1793   static bool classofKind(Kind K) {
   1794     return K == ClassTemplatePartialSpecialization;
   1795   }
   1796 
   1797   friend class ASTDeclReader;
   1798   friend class ASTDeclWriter;
   1799 };
   1800 
   1801 /// Declaration of a class template.
   1802 class ClassTemplateDecl : public RedeclarableTemplateDecl {
   1803   static void DeallocateCommon(void *Ptr);
   1804 
   1805 protected:
   1806   /// \brief Data that is common to all of the declarations of a given
   1807   /// class template.
   1808   struct Common : CommonBase {
   1809     Common() : LazySpecializations() { }
   1810 
   1811     /// \brief The class template specializations for this class
   1812     /// template, including explicit specializations and instantiations.
   1813     llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
   1814 
   1815     /// \brief The class template partial specializations for this class
   1816     /// template.
   1817     llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
   1818       PartialSpecializations;
   1819 
   1820     /// \brief The injected-class-name type for this class template.
   1821     QualType InjectedClassNameType;
   1822 
   1823     /// \brief If non-null, points to an array of specializations (including
   1824     /// partial specializations) known ownly by their external declaration IDs.
   1825     ///
   1826     /// The first value in the array is the number of of specializations/
   1827     /// partial specializations that follow.
   1828     uint32_t *LazySpecializations;
   1829   };
   1830 
   1831   /// \brief Load any lazily-loaded specializations from the external source.
   1832   void LoadLazySpecializations() const;
   1833 
   1834   /// \brief Retrieve the set of specializations of this class template.
   1835   llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
   1836   getSpecializations() const;
   1837 
   1838   /// \brief Retrieve the set of partial specializations of this class
   1839   /// template.
   1840   llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
   1841   getPartialSpecializations();
   1842 
   1843   ClassTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
   1844                     TemplateParameterList *Params, NamedDecl *Decl)
   1845     : RedeclarableTemplateDecl(ClassTemplate, DC, L, Name, Params, Decl) { }
   1846 
   1847   ClassTemplateDecl(EmptyShell Empty)
   1848     : RedeclarableTemplateDecl(ClassTemplate, 0, SourceLocation(),
   1849                                DeclarationName(), 0, 0) { }
   1850 
   1851   CommonBase *newCommon(ASTContext &C) const;
   1852 
   1853   Common *getCommonPtr() const {
   1854     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
   1855   }
   1856 
   1857 public:
   1858   /// \brief Get the underlying class declarations of the template.
   1859   CXXRecordDecl *getTemplatedDecl() const {
   1860     return static_cast<CXXRecordDecl *>(TemplatedDecl);
   1861   }
   1862 
   1863   /// \brief Returns whether this template declaration defines the primary
   1864   /// class pattern.
   1865   bool isThisDeclarationADefinition() const {
   1866     return getTemplatedDecl()->isThisDeclarationADefinition();
   1867   }
   1868 
   1869   /// \brief Create a class template node.
   1870   static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
   1871                                    SourceLocation L,
   1872                                    DeclarationName Name,
   1873                                    TemplateParameterList *Params,
   1874                                    NamedDecl *Decl,
   1875                                    ClassTemplateDecl *PrevDecl);
   1876 
   1877   /// \brief Create an empty class template node.
   1878   static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   1879 
   1880   /// \brief Return the specialization with the provided arguments if it exists,
   1881   /// otherwise return the insertion point.
   1882   ClassTemplateSpecializationDecl *
   1883   findSpecialization(const TemplateArgument *Args, unsigned NumArgs,
   1884                      void *&InsertPos);
   1885 
   1886   /// \brief Insert the specified specialization knowing that it is not already
   1887   /// in. InsertPos must be obtained from findSpecialization.
   1888   void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
   1889 
   1890   ClassTemplateDecl *getCanonicalDecl() {
   1891     return cast<ClassTemplateDecl>(
   1892              RedeclarableTemplateDecl::getCanonicalDecl());
   1893   }
   1894   const ClassTemplateDecl *getCanonicalDecl() const {
   1895     return cast<ClassTemplateDecl>(
   1896              RedeclarableTemplateDecl::getCanonicalDecl());
   1897   }
   1898 
   1899   /// \brief Retrieve the previous declaration of this class template, or
   1900   /// NULL if no such declaration exists.
   1901   ClassTemplateDecl *getPreviousDecl() {
   1902     return cast_or_null<ClassTemplateDecl>(
   1903              RedeclarableTemplateDecl::getPreviousDecl());
   1904   }
   1905 
   1906   /// \brief Retrieve the previous declaration of this class template, or
   1907   /// NULL if no such declaration exists.
   1908   const ClassTemplateDecl *getPreviousDecl() const {
   1909     return cast_or_null<ClassTemplateDecl>(
   1910              RedeclarableTemplateDecl::getPreviousDecl());
   1911   }
   1912 
   1913   ClassTemplateDecl *getInstantiatedFromMemberTemplate() {
   1914     return cast_or_null<ClassTemplateDecl>(
   1915              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
   1916   }
   1917 
   1918   /// \brief Return the partial specialization with the provided arguments if it
   1919   /// exists, otherwise return the insertion point.
   1920   ClassTemplatePartialSpecializationDecl *
   1921   findPartialSpecialization(const TemplateArgument *Args, unsigned NumArgs,
   1922                             void *&InsertPos);
   1923 
   1924   /// \brief Insert the specified partial specialization knowing that it is not
   1925   /// already in. InsertPos must be obtained from findPartialSpecialization.
   1926   void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
   1927                                 void *InsertPos);
   1928 
   1929   /// \brief Return the next partial specialization sequence number.
   1930   unsigned getNextPartialSpecSequenceNumber() {
   1931     return getPartialSpecializations().size();
   1932   }
   1933 
   1934   /// \brief Retrieve the partial specializations as an ordered list.
   1935   void getPartialSpecializations(
   1936           SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
   1937 
   1938   /// \brief Find a class template partial specialization with the given
   1939   /// type T.
   1940   ///
   1941   /// \param T a dependent type that names a specialization of this class
   1942   /// template.
   1943   ///
   1944   /// \returns the class template partial specialization that exactly matches
   1945   /// the type \p T, or NULL if no such partial specialization exists.
   1946   ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
   1947 
   1948   /// \brief Find a class template partial specialization which was instantiated
   1949   /// from the given member partial specialization.
   1950   ///
   1951   /// \param D a member class template partial specialization.
   1952   ///
   1953   /// \returns the class template partial specialization which was instantiated
   1954   /// from the given member partial specialization, or NULL if no such partial
   1955   /// specialization exists.
   1956   ClassTemplatePartialSpecializationDecl *
   1957   findPartialSpecInstantiatedFromMember(
   1958                                      ClassTemplatePartialSpecializationDecl *D);
   1959 
   1960   /// \brief Retrieve the template specialization type of the
   1961   /// injected-class-name for this class template.
   1962   ///
   1963   /// The injected-class-name for a class template \c X is \c
   1964   /// X<template-args>, where \c template-args is formed from the
   1965   /// template arguments that correspond to the template parameters of
   1966   /// \c X. For example:
   1967   ///
   1968   /// \code
   1969   /// template<typename T, int N>
   1970   /// struct array {
   1971   ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
   1972   /// };
   1973   /// \endcode
   1974   QualType getInjectedClassNameSpecialization();
   1975 
   1976   typedef SpecIterator<ClassTemplateSpecializationDecl> spec_iterator;
   1977 
   1978   spec_iterator spec_begin() const {
   1979     return makeSpecIterator(getSpecializations(), false);
   1980   }
   1981 
   1982   spec_iterator spec_end() const {
   1983     return makeSpecIterator(getSpecializations(), true);
   1984   }
   1985 
   1986   typedef SpecIterator<ClassTemplatePartialSpecializationDecl>
   1987           partial_spec_iterator;
   1988 
   1989   partial_spec_iterator partial_spec_begin() {
   1990     return makeSpecIterator(getPartialSpecializations(), false);
   1991   }
   1992 
   1993   partial_spec_iterator partial_spec_end() {
   1994     return makeSpecIterator(getPartialSpecializations(), true);
   1995   }
   1996 
   1997   // Implement isa/cast/dyncast support
   1998   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1999   static bool classofKind(Kind K) { return K == ClassTemplate; }
   2000 
   2001   friend class ASTDeclReader;
   2002   friend class ASTDeclWriter;
   2003 };
   2004 
   2005 /// \brief Declaration of a friend template.
   2006 ///
   2007 /// For example:
   2008 /// \code
   2009 /// template \<typename T> class A {
   2010 ///   friend class MyVector<T>; // not a friend template
   2011 ///   template \<typename U> friend class B; // not a friend template
   2012 ///   template \<typename U> friend class Foo<T>::Nested; // friend template
   2013 /// };
   2014 /// \endcode
   2015 ///
   2016 /// \note This class is not currently in use.  All of the above
   2017 /// will yield a FriendDecl, not a FriendTemplateDecl.
   2018 class FriendTemplateDecl : public Decl {
   2019   virtual void anchor();
   2020 public:
   2021   typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
   2022 
   2023 private:
   2024   // The number of template parameters;  always non-zero.
   2025   unsigned NumParams;
   2026 
   2027   // The parameter list.
   2028   TemplateParameterList **Params;
   2029 
   2030   // The declaration that's a friend of this class.
   2031   FriendUnion Friend;
   2032 
   2033   // Location of the 'friend' specifier.
   2034   SourceLocation FriendLoc;
   2035 
   2036 
   2037   FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
   2038                      unsigned NParams,
   2039                      TemplateParameterList **Params,
   2040                      FriendUnion Friend,
   2041                      SourceLocation FriendLoc)
   2042     : Decl(Decl::FriendTemplate, DC, Loc),
   2043       NumParams(NParams),
   2044       Params(Params),
   2045       Friend(Friend),
   2046       FriendLoc(FriendLoc)
   2047   {}
   2048 
   2049   FriendTemplateDecl(EmptyShell Empty)
   2050     : Decl(Decl::FriendTemplate, Empty),
   2051       NumParams(0),
   2052       Params(0)
   2053   {}
   2054 
   2055 public:
   2056   static FriendTemplateDecl *Create(ASTContext &Context,
   2057                                     DeclContext *DC, SourceLocation Loc,
   2058                                     unsigned NParams,
   2059                                     TemplateParameterList **Params,
   2060                                     FriendUnion Friend,
   2061                                     SourceLocation FriendLoc);
   2062 
   2063   static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2064 
   2065   /// If this friend declaration names a templated type (or
   2066   /// a dependent member type of a templated type), return that
   2067   /// type;  otherwise return null.
   2068   TypeSourceInfo *getFriendType() const {
   2069     return Friend.dyn_cast<TypeSourceInfo*>();
   2070   }
   2071 
   2072   /// If this friend declaration names a templated function (or
   2073   /// a member function of a templated type), return that type;
   2074   /// otherwise return null.
   2075   NamedDecl *getFriendDecl() const {
   2076     return Friend.dyn_cast<NamedDecl*>();
   2077   }
   2078 
   2079   /// \brief Retrieves the location of the 'friend' keyword.
   2080   SourceLocation getFriendLoc() const {
   2081     return FriendLoc;
   2082   }
   2083 
   2084   TemplateParameterList *getTemplateParameterList(unsigned i) const {
   2085     assert(i <= NumParams);
   2086     return Params[i];
   2087   }
   2088 
   2089   unsigned getNumTemplateParameters() const {
   2090     return NumParams;
   2091   }
   2092 
   2093   // Implement isa/cast/dyncast/etc.
   2094   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2095   static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
   2096 
   2097   friend class ASTDeclReader;
   2098 };
   2099 
   2100 /// \brief Declaration of an alias template.
   2101 ///
   2102 /// For example:
   2103 /// \code
   2104 /// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
   2105 /// \endcode
   2106 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
   2107   static void DeallocateCommon(void *Ptr);
   2108 
   2109 protected:
   2110   typedef CommonBase Common;
   2111 
   2112   TypeAliasTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
   2113                         TemplateParameterList *Params, NamedDecl *Decl)
   2114     : RedeclarableTemplateDecl(TypeAliasTemplate, DC, L, Name, Params, Decl) { }
   2115 
   2116   CommonBase *newCommon(ASTContext &C) const;
   2117 
   2118   Common *getCommonPtr() {
   2119     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
   2120   }
   2121 
   2122 public:
   2123   /// Get the underlying function declaration of the template.
   2124   TypeAliasDecl *getTemplatedDecl() const {
   2125     return static_cast<TypeAliasDecl*>(TemplatedDecl);
   2126   }
   2127 
   2128 
   2129   TypeAliasTemplateDecl *getCanonicalDecl() {
   2130     return cast<TypeAliasTemplateDecl>(
   2131              RedeclarableTemplateDecl::getCanonicalDecl());
   2132   }
   2133   const TypeAliasTemplateDecl *getCanonicalDecl() const {
   2134     return cast<TypeAliasTemplateDecl>(
   2135              RedeclarableTemplateDecl::getCanonicalDecl());
   2136   }
   2137 
   2138   /// \brief Retrieve the previous declaration of this function template, or
   2139   /// NULL if no such declaration exists.
   2140   TypeAliasTemplateDecl *getPreviousDecl() {
   2141     return cast_or_null<TypeAliasTemplateDecl>(
   2142              RedeclarableTemplateDecl::getPreviousDecl());
   2143   }
   2144 
   2145   /// \brief Retrieve the previous declaration of this function template, or
   2146   /// NULL if no such declaration exists.
   2147   const TypeAliasTemplateDecl *getPreviousDecl() const {
   2148     return cast_or_null<TypeAliasTemplateDecl>(
   2149              RedeclarableTemplateDecl::getPreviousDecl());
   2150   }
   2151 
   2152   TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() {
   2153     return cast_or_null<TypeAliasTemplateDecl>(
   2154              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
   2155   }
   2156 
   2157 
   2158   /// \brief Create a function template node.
   2159   static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
   2160                                        SourceLocation L,
   2161                                        DeclarationName Name,
   2162                                        TemplateParameterList *Params,
   2163                                        NamedDecl *Decl);
   2164 
   2165   /// \brief Create an empty alias template node.
   2166   static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2167 
   2168   // Implement isa/cast/dyncast support
   2169   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2170   static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
   2171 
   2172   friend class ASTDeclReader;
   2173   friend class ASTDeclWriter;
   2174 };
   2175 
   2176 /// \brief Declaration of a function specialization at template class scope.
   2177 ///
   2178 /// This is a non standard extension needed to support MSVC.
   2179 ///
   2180 /// For example:
   2181 /// \code
   2182 /// template <class T>
   2183 /// class A {
   2184 ///    template <class U> void foo(U a) { }
   2185 ///    template<> void foo(int a) { }
   2186 /// }
   2187 /// \endcode
   2188 ///
   2189 /// "template<> foo(int a)" will be saved in Specialization as a normal
   2190 /// CXXMethodDecl. Then during an instantiation of class A, it will be
   2191 /// transformed into an actual function specialization.
   2192 class ClassScopeFunctionSpecializationDecl : public Decl {
   2193   virtual void anchor();
   2194 
   2195   ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
   2196                                        CXXMethodDecl *FD, bool Args,
   2197                                        TemplateArgumentListInfo TemplArgs)
   2198     : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
   2199       Specialization(FD), HasExplicitTemplateArgs(Args),
   2200       TemplateArgs(TemplArgs) {}
   2201 
   2202   ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
   2203     : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
   2204 
   2205   CXXMethodDecl *Specialization;
   2206   bool HasExplicitTemplateArgs;
   2207   TemplateArgumentListInfo TemplateArgs;
   2208 
   2209 public:
   2210   CXXMethodDecl *getSpecialization() const { return Specialization; }
   2211   bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
   2212   const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
   2213 
   2214   static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
   2215                                                       DeclContext *DC,
   2216                                                       SourceLocation Loc,
   2217                                                       CXXMethodDecl *FD,
   2218                                                    bool HasExplicitTemplateArgs,
   2219                                         TemplateArgumentListInfo TemplateArgs) {
   2220     return new (C) ClassScopeFunctionSpecializationDecl(DC , Loc, FD,
   2221                                                         HasExplicitTemplateArgs,
   2222                                                         TemplateArgs);
   2223   }
   2224 
   2225   static ClassScopeFunctionSpecializationDecl *
   2226   CreateDeserialized(ASTContext &Context, unsigned ID);
   2227 
   2228   // Implement isa/cast/dyncast/etc.
   2229   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2230   static bool classofKind(Kind K) {
   2231     return K == Decl::ClassScopeFunctionSpecialization;
   2232   }
   2233 
   2234   friend class ASTDeclReader;
   2235   friend class ASTDeclWriter;
   2236 };
   2237 
   2238 /// Implementation of inline functions that require the template declarations
   2239 inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
   2240   : Function(FTD) { }
   2241 
   2242 } /* end of namespace clang */
   2243 
   2244 #endif
   2245