clang API Documentation

DeclTemplate.h
Go to the documentation of this file.
00001 //===-- DeclTemplate.h - Classes for representing C++ templates -*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 ///
00010 /// \file
00011 /// \brief Defines the C++ template declaration subclasses.
00012 ///
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
00016 #define LLVM_CLANG_AST_DECLTEMPLATE_H
00017 
00018 #include "clang/AST/DeclCXX.h"
00019 #include "clang/AST/Redeclarable.h"
00020 #include "clang/AST/TemplateBase.h"
00021 #include "llvm/ADT/PointerUnion.h"
00022 #include "llvm/Support/Compiler.h"
00023 #include <limits>
00024 
00025 namespace clang {
00026 
00027 class TemplateParameterList;
00028 class TemplateDecl;
00029 class RedeclarableTemplateDecl;
00030 class FunctionTemplateDecl;
00031 class ClassTemplateDecl;
00032 class ClassTemplatePartialSpecializationDecl;
00033 class TemplateTypeParmDecl;
00034 class NonTypeTemplateParmDecl;
00035 class TemplateTemplateParmDecl;
00036 class TypeAliasTemplateDecl;
00037 class VarTemplateDecl;
00038 class VarTemplatePartialSpecializationDecl;
00039 
00040 /// \brief Stores a template parameter of any kind.
00041 typedef llvm::PointerUnion3<TemplateTypeParmDecl*, NonTypeTemplateParmDecl*,
00042                             TemplateTemplateParmDecl*> TemplateParameter;
00043 
00044 /// \brief Stores a list of template parameters for a TemplateDecl and its
00045 /// derived classes.
00046 class TemplateParameterList {
00047   /// The location of the 'template' keyword.
00048   SourceLocation TemplateLoc;
00049 
00050   /// The locations of the '<' and '>' angle brackets.
00051   SourceLocation LAngleLoc, RAngleLoc;
00052 
00053   /// The number of template parameters in this template
00054   /// parameter list.
00055   unsigned NumParams : 31;
00056 
00057   /// Whether this template parameter list contains an unexpanded parameter
00058   /// pack.
00059   unsigned ContainsUnexpandedParameterPack : 1;
00060 
00061 protected:
00062   TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
00063                         NamedDecl **Params, unsigned NumParams,
00064                         SourceLocation RAngleLoc);
00065 
00066 public:
00067   static TemplateParameterList *Create(const ASTContext &C,
00068                                        SourceLocation TemplateLoc,
00069                                        SourceLocation LAngleLoc,
00070                                        NamedDecl **Params,
00071                                        unsigned NumParams,
00072                                        SourceLocation RAngleLoc);
00073 
00074   /// \brief Iterates through the template parameters in this list.
00075   typedef NamedDecl** iterator;
00076 
00077   /// \brief Iterates through the template parameters in this list.
00078   typedef NamedDecl* const* const_iterator;
00079 
00080   iterator begin() { return reinterpret_cast<NamedDecl **>(this + 1); }
00081   const_iterator begin() const {
00082     return reinterpret_cast<NamedDecl * const *>(this + 1);
00083   }
00084   iterator end() { return begin() + NumParams; }
00085   const_iterator end() const { return begin() + NumParams; }
00086 
00087   unsigned size() const { return NumParams; }
00088 
00089   ArrayRef<NamedDecl*> asArray() {
00090     return llvm::makeArrayRef(begin(), end());
00091   }
00092   ArrayRef<const NamedDecl*> asArray() const {
00093     return llvm::makeArrayRef(begin(), size());
00094   }
00095 
00096   NamedDecl* getParam(unsigned Idx) {
00097     assert(Idx < size() && "Template parameter index out-of-range");
00098     return begin()[Idx];
00099   }
00100 
00101   const NamedDecl* getParam(unsigned Idx) const {
00102     assert(Idx < size() && "Template parameter index out-of-range");
00103     return begin()[Idx];
00104   }
00105 
00106   /// \brief Returns the minimum number of arguments needed to form a
00107   /// template specialization.
00108   ///
00109   /// This may be fewer than the number of template parameters, if some of
00110   /// the parameters have default arguments or if there is a parameter pack.
00111   unsigned getMinRequiredArguments() const;
00112 
00113   /// \brief Get the depth of this template parameter list in the set of
00114   /// template parameter lists.
00115   ///
00116   /// The first template parameter list in a declaration will have depth 0,
00117   /// the second template parameter list will have depth 1, etc.
00118   unsigned getDepth() const;
00119 
00120   /// \brief Determine whether this template parameter list contains an
00121   /// unexpanded parameter pack.
00122   bool containsUnexpandedParameterPack() const {
00123     return ContainsUnexpandedParameterPack;
00124   }
00125 
00126   SourceLocation getTemplateLoc() const { return TemplateLoc; }
00127   SourceLocation getLAngleLoc() const { return LAngleLoc; }
00128   SourceLocation getRAngleLoc() const { return RAngleLoc; }
00129 
00130   SourceRange getSourceRange() const LLVM_READONLY {
00131     return SourceRange(TemplateLoc, RAngleLoc);
00132   }
00133 };
00134 
00135 /// \brief Stores a list of template parameters for a TemplateDecl and its
00136 /// derived classes. Suitable for creating on the stack.
00137 template<size_t N>
00138 class FixedSizeTemplateParameterList : public TemplateParameterList {
00139   NamedDecl *Params[N];
00140 
00141 public:
00142   FixedSizeTemplateParameterList(SourceLocation TemplateLoc,
00143                                  SourceLocation LAngleLoc,
00144                                  NamedDecl **Params, SourceLocation RAngleLoc) :
00145     TemplateParameterList(TemplateLoc, LAngleLoc, Params, N, RAngleLoc) {
00146   }
00147 };
00148 
00149 /// \brief A template argument list.
00150 class TemplateArgumentList {
00151   /// \brief The template argument list.
00152   ///
00153   /// The integer value will be non-zero to indicate that this
00154   /// template argument list does own the pointer.
00155   llvm::PointerIntPair<const TemplateArgument *, 1> Arguments;
00156 
00157   /// \brief The number of template arguments in this template
00158   /// argument list.
00159   unsigned NumArguments;
00160 
00161   TemplateArgumentList(const TemplateArgumentList &Other) LLVM_DELETED_FUNCTION;
00162   void operator=(const TemplateArgumentList &Other) LLVM_DELETED_FUNCTION;
00163 
00164   TemplateArgumentList(const TemplateArgument *Args, unsigned NumArgs,
00165                        bool Owned)
00166     : Arguments(Args, Owned), NumArguments(NumArgs) { }
00167 
00168 public:
00169   /// \brief Type used to indicate that the template argument list itself is a
00170   /// stack object. It does not own its template arguments.
00171   enum OnStackType { OnStack };
00172 
00173   /// \brief Create a new template argument list that copies the given set of
00174   /// template arguments.
00175   static TemplateArgumentList *CreateCopy(ASTContext &Context,
00176                                           const TemplateArgument *Args,
00177                                           unsigned NumArgs);
00178 
00179   /// \brief Construct a new, temporary template argument list on the stack.
00180   ///
00181   /// The template argument list does not own the template arguments
00182   /// provided.
00183   explicit TemplateArgumentList(OnStackType,
00184                                 const TemplateArgument *Args, unsigned NumArgs)
00185     : Arguments(Args, false), NumArguments(NumArgs) { }
00186 
00187   /// \brief Produces a shallow copy of the given template argument list.
00188   ///
00189   /// This operation assumes that the input argument list outlives it.
00190   /// This takes the list as a pointer to avoid looking like a copy
00191   /// constructor, since this really really isn't safe to use that
00192   /// way.
00193   explicit TemplateArgumentList(const TemplateArgumentList *Other)
00194     : Arguments(Other->data(), false), NumArguments(Other->size()) { }
00195 
00196   /// \brief Retrieve the template argument at a given index.
00197   const TemplateArgument &get(unsigned Idx) const {
00198     assert(Idx < NumArguments && "Invalid template argument index");
00199     return data()[Idx];
00200   }
00201 
00202   /// \brief Retrieve the template argument at a given index.
00203   const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
00204 
00205   /// \brief Produce this as an array ref.
00206   ArrayRef<TemplateArgument> asArray() const {
00207     return llvm::makeArrayRef(data(), size());
00208   }
00209 
00210   /// \brief Retrieve the number of template arguments in this
00211   /// template argument list.
00212   unsigned size() const { return NumArguments; }
00213 
00214   /// \brief Retrieve a pointer to the template argument list.
00215   const TemplateArgument *data() const {
00216     return Arguments.getPointer();
00217   }
00218 };
00219 
00220 //===----------------------------------------------------------------------===//
00221 // Kinds of Templates
00222 //===----------------------------------------------------------------------===//
00223 
00224 /// \brief The base class of all kinds of template declarations (e.g.,
00225 /// class, function, etc.).
00226 ///
00227 /// The TemplateDecl class stores the list of template parameters and a
00228 /// reference to the templated scoped declaration: the underlying AST node.
00229 class TemplateDecl : public NamedDecl {
00230   void anchor() override;
00231 protected:
00232   // This is probably never used.
00233   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
00234                DeclarationName Name)
00235     : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
00236       TemplateParams(nullptr) {}
00237 
00238   // Construct a template decl with the given name and parameters.
00239   // Used when there is not templated element (tt-params).
00240   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
00241                DeclarationName Name, TemplateParameterList *Params)
00242     : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
00243       TemplateParams(Params) {}
00244 
00245   // Construct a template decl with name, parameters, and templated element.
00246   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
00247                DeclarationName Name, TemplateParameterList *Params,
00248                NamedDecl *Decl)
00249     : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
00250       TemplateParams(Params) { }
00251 public:
00252   /// Get the list of template parameters
00253   TemplateParameterList *getTemplateParameters() const {
00254     return TemplateParams;
00255   }
00256 
00257   /// Get the underlying, templated declaration.
00258   NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
00259 
00260   // Implement isa/cast/dyncast/etc.
00261   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
00262   static bool classofKind(Kind K) {
00263     return K >= firstTemplate && K <= lastTemplate;
00264   }
00265 
00266   SourceRange getSourceRange() const override LLVM_READONLY {
00267     return SourceRange(TemplateParams->getTemplateLoc(),
00268                        TemplatedDecl->getSourceRange().getEnd());
00269   }
00270 
00271 protected:
00272   NamedDecl *TemplatedDecl;
00273   TemplateParameterList* TemplateParams;
00274 
00275 public:
00276   /// \brief Initialize the underlying templated declaration and
00277   /// template parameters.
00278   void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
00279     assert(!TemplatedDecl && "TemplatedDecl already set!");
00280     assert(!TemplateParams && "TemplateParams already set!");
00281     TemplatedDecl = templatedDecl;
00282     TemplateParams = templateParams;
00283   }
00284 };
00285 
00286 /// \brief Provides information about a function template specialization,
00287 /// which is a FunctionDecl that has been explicitly specialization or
00288 /// instantiated from a function template.
00289 class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
00290   FunctionTemplateSpecializationInfo(FunctionDecl *FD,
00291                                      FunctionTemplateDecl *Template,
00292                                      TemplateSpecializationKind TSK,
00293                                      const TemplateArgumentList *TemplateArgs,
00294                        const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
00295                                      SourceLocation POI)
00296   : Function(FD),
00297     Template(Template, TSK - 1),
00298     TemplateArguments(TemplateArgs),
00299     TemplateArgumentsAsWritten(TemplateArgsAsWritten),
00300     PointOfInstantiation(POI) { }
00301 
00302 public:
00303   static FunctionTemplateSpecializationInfo *
00304   Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
00305          TemplateSpecializationKind TSK,
00306          const TemplateArgumentList *TemplateArgs,
00307          const TemplateArgumentListInfo *TemplateArgsAsWritten,
00308          SourceLocation POI);
00309 
00310   /// \brief The function template specialization that this structure
00311   /// describes.
00312   FunctionDecl *Function;
00313 
00314   /// \brief The function template from which this function template
00315   /// specialization was generated.
00316   ///
00317   /// The two bits are contain the top 4 values of TemplateSpecializationKind.
00318   llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
00319 
00320   /// \brief The template arguments used to produce the function template
00321   /// specialization from the function template.
00322   const TemplateArgumentList *TemplateArguments;
00323 
00324   /// \brief The template arguments as written in the sources, if provided.
00325   const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
00326 
00327   /// \brief The point at which this function template specialization was
00328   /// first instantiated.
00329   SourceLocation PointOfInstantiation;
00330 
00331   /// \brief Retrieve the template from which this function was specialized.
00332   FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
00333 
00334   /// \brief Determine what kind of template specialization this is.
00335   TemplateSpecializationKind getTemplateSpecializationKind() const {
00336     return (TemplateSpecializationKind)(Template.getInt() + 1);
00337   }
00338 
00339   bool isExplicitSpecialization() const {
00340     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
00341   }
00342 
00343   /// \brief True if this declaration is an explicit specialization,
00344   /// explicit instantiation declaration, or explicit instantiation
00345   /// definition.
00346   bool isExplicitInstantiationOrSpecialization() const {
00347     switch (getTemplateSpecializationKind()) {
00348     case TSK_ExplicitSpecialization:
00349     case TSK_ExplicitInstantiationDeclaration:
00350     case TSK_ExplicitInstantiationDefinition:
00351       return true;
00352 
00353     case TSK_Undeclared:
00354     case TSK_ImplicitInstantiation:
00355       return false;
00356     }
00357     llvm_unreachable("bad template specialization kind");
00358   }
00359 
00360   /// \brief Set the template specialization kind.
00361   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
00362     assert(TSK != TSK_Undeclared &&
00363          "Cannot encode TSK_Undeclared for a function template specialization");
00364     Template.setInt(TSK - 1);
00365   }
00366 
00367   /// \brief Retrieve the first point of instantiation of this function
00368   /// template specialization.
00369   ///
00370   /// The point of instantiation may be an invalid source location if this
00371   /// function has yet to be instantiated.
00372   SourceLocation getPointOfInstantiation() const {
00373     return PointOfInstantiation;
00374   }
00375 
00376   /// \brief Set the (first) point of instantiation of this function template
00377   /// specialization.
00378   void setPointOfInstantiation(SourceLocation POI) {
00379     PointOfInstantiation = POI;
00380   }
00381 
00382   void Profile(llvm::FoldingSetNodeID &ID) {
00383     Profile(ID, TemplateArguments->asArray(),
00384             Function->getASTContext());
00385   }
00386 
00387   static void
00388   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
00389           ASTContext &Context) {
00390     ID.AddInteger(TemplateArgs.size());
00391     for (unsigned Arg = 0; Arg != TemplateArgs.size(); ++Arg)
00392       TemplateArgs[Arg].Profile(ID, Context);
00393   }
00394 };
00395 
00396 /// \brief Provides information a specialization of a member of a class
00397 /// template, which may be a member function, static data member,
00398 /// member class or member enumeration.
00399 class MemberSpecializationInfo {
00400   // The member declaration from which this member was instantiated, and the
00401   // manner in which the instantiation occurred (in the lower two bits).
00402   llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
00403 
00404   // The point at which this member was first instantiated.
00405   SourceLocation PointOfInstantiation;
00406 
00407 public:
00408   explicit
00409   MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
00410                            SourceLocation POI = SourceLocation())
00411     : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
00412     assert(TSK != TSK_Undeclared &&
00413            "Cannot encode undeclared template specializations for members");
00414   }
00415 
00416   /// \brief Retrieve the member declaration from which this member was
00417   /// instantiated.
00418   NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
00419 
00420   /// \brief Determine what kind of template specialization this is.
00421   TemplateSpecializationKind getTemplateSpecializationKind() const {
00422     return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
00423   }
00424 
00425   bool isExplicitSpecialization() const {
00426     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
00427   }
00428 
00429   /// \brief Set the template specialization kind.
00430   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
00431     assert(TSK != TSK_Undeclared &&
00432            "Cannot encode undeclared template specializations for members");
00433     MemberAndTSK.setInt(TSK - 1);
00434   }
00435 
00436   /// \brief Retrieve the first point of instantiation of this member.
00437   /// If the point of instantiation is an invalid location, then this member
00438   /// has not yet been instantiated.
00439   SourceLocation getPointOfInstantiation() const {
00440     return PointOfInstantiation;
00441   }
00442 
00443   /// \brief Set the first point of instantiation.
00444   void setPointOfInstantiation(SourceLocation POI) {
00445     PointOfInstantiation = POI;
00446   }
00447 };
00448 
00449 /// \brief Provides information about a dependent function-template
00450 /// specialization declaration.
00451 ///
00452 /// Since explicit function template specialization and instantiation
00453 /// declarations can only appear in namespace scope, and you can only
00454 /// specialize a member of a fully-specialized class, the only way to
00455 /// get one of these is in a friend declaration like the following:
00456 ///
00457 /// \code
00458 ///   template <class T> void foo(T);
00459 ///   template <class T> class A {
00460 ///     friend void foo<>(T);
00461 ///   };
00462 /// \endcode
00463 class DependentFunctionTemplateSpecializationInfo {
00464   struct CA {
00465     /// The number of potential template candidates.
00466     unsigned NumTemplates;
00467 
00468     /// The number of template arguments.
00469     unsigned NumArgs;
00470   };
00471 
00472   union {
00473     // Force sizeof to be a multiple of sizeof(void*) so that the
00474     // trailing data is aligned.
00475     void *Aligner;
00476     struct CA d;
00477   };
00478 
00479   /// The locations of the left and right angle brackets.
00480   SourceRange AngleLocs;
00481 
00482   FunctionTemplateDecl * const *getTemplates() const {
00483     return reinterpret_cast<FunctionTemplateDecl*const*>(this+1);
00484   }
00485 
00486 public:
00487   DependentFunctionTemplateSpecializationInfo(
00488                                  const UnresolvedSetImpl &Templates,
00489                                  const TemplateArgumentListInfo &TemplateArgs);
00490 
00491   /// \brief Returns the number of function templates that this might
00492   /// be a specialization of.
00493   unsigned getNumTemplates() const {
00494     return d.NumTemplates;
00495   }
00496 
00497   /// \brief Returns the i'th template candidate.
00498   FunctionTemplateDecl *getTemplate(unsigned I) const {
00499     assert(I < getNumTemplates() && "template index out of range");
00500     return getTemplates()[I];
00501   }
00502 
00503   /// \brief Returns the explicit template arguments that were given.
00504   const TemplateArgumentLoc *getTemplateArgs() const {
00505     return reinterpret_cast<const TemplateArgumentLoc*>(
00506                                             &getTemplates()[getNumTemplates()]);
00507   }
00508 
00509   /// \brief Returns the number of explicit template arguments that were given.
00510   unsigned getNumTemplateArgs() const {
00511     return d.NumArgs;
00512   }
00513 
00514   /// \brief Returns the nth template argument.
00515   const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
00516     assert(I < getNumTemplateArgs() && "template arg index out of range");
00517     return getTemplateArgs()[I];
00518   }
00519 
00520   SourceLocation getLAngleLoc() const {
00521     return AngleLocs.getBegin();
00522   }
00523 
00524   SourceLocation getRAngleLoc() const {
00525     return AngleLocs.getEnd();
00526   }
00527 };
00528 
00529 /// Declaration of a redeclarable template.
00530 class RedeclarableTemplateDecl : public TemplateDecl, 
00531                                  public Redeclarable<RedeclarableTemplateDecl> 
00532 {
00533   typedef Redeclarable<RedeclarableTemplateDecl> redeclarable_base;
00534   RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
00535     return getNextRedeclaration();
00536   }
00537   RedeclarableTemplateDecl *getPreviousDeclImpl() override {
00538     return getPreviousDecl();
00539   }
00540   RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
00541     return getMostRecentDecl();
00542   }
00543 
00544 protected:
00545   template <typename EntryType> struct SpecEntryTraits {
00546     typedef EntryType DeclType;
00547 
00548     static DeclType *getMostRecentDecl(EntryType *D) {
00549       return D->getMostRecentDecl();
00550     }
00551   };
00552 
00553   template <typename EntryType,
00554             typename _SETraits = SpecEntryTraits<EntryType>,
00555             typename _DeclType = typename _SETraits::DeclType>
00556   class SpecIterator : public std::iterator<std::forward_iterator_tag,
00557                                             _DeclType*, ptrdiff_t,
00558                                             _DeclType*, _DeclType*> {
00559     typedef _SETraits SETraits;
00560     typedef _DeclType DeclType;
00561 
00562     typedef typename llvm::FoldingSetVector<EntryType>::iterator
00563       SetIteratorType;
00564 
00565     SetIteratorType SetIter;
00566 
00567   public:
00568     SpecIterator() : SetIter() {}
00569     SpecIterator(SetIteratorType SetIter) : SetIter(SetIter) {}
00570 
00571     DeclType *operator*() const {
00572       return SETraits::getMostRecentDecl(&*SetIter);
00573     }
00574     DeclType *operator->() const { return **this; }
00575 
00576     SpecIterator &operator++() { ++SetIter; return *this; }
00577     SpecIterator operator++(int) {
00578       SpecIterator tmp(*this);
00579       ++(*this);
00580       return tmp;
00581     }
00582 
00583     bool operator==(SpecIterator Other) const {
00584       return SetIter == Other.SetIter;
00585     }
00586     bool operator!=(SpecIterator Other) const {
00587       return SetIter != Other.SetIter;
00588     }
00589   };
00590 
00591   template <typename EntryType>
00592   static SpecIterator<EntryType>
00593   makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
00594     return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
00595   }
00596 
00597   template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
00598   findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
00599                          ArrayRef<TemplateArgument> Args, void *&InsertPos);
00600 
00601   struct CommonBase {
00602     CommonBase() : InstantiatedFromMember(nullptr, false) { }
00603 
00604     /// \brief The template from which this was most
00605     /// directly instantiated (or null).
00606     ///
00607     /// The boolean value indicates whether this template
00608     /// was explicitly specialized.
00609     llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
00610       InstantiatedFromMember;
00611   };
00612 
00613   /// \brief Pointer to the common data shared by all declarations of this
00614   /// template.
00615   mutable CommonBase *Common;
00616   
00617   /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
00618   /// the same template. Calling this routine may implicitly allocate memory
00619   /// for the common pointer.
00620   CommonBase *getCommonPtr() const;
00621 
00622   virtual CommonBase *newCommon(ASTContext &C) const = 0;
00623 
00624   // Construct a template decl with name, parameters, and templated element.
00625   RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
00626                            SourceLocation L, DeclarationName Name,
00627                            TemplateParameterList *Params, NamedDecl *Decl)
00628       : TemplateDecl(DK, DC, L, Name, Params, Decl), redeclarable_base(C),
00629         Common() {}
00630 
00631 public:
00632   template <class decl_type> friend class RedeclarableTemplate;
00633 
00634   /// \brief Retrieves the canonical declaration of this template.
00635   RedeclarableTemplateDecl *getCanonicalDecl() override {
00636     return getFirstDecl();
00637   }
00638   const RedeclarableTemplateDecl *getCanonicalDecl() const {
00639     return getFirstDecl();
00640   }
00641 
00642   /// \brief Determines whether this template was a specialization of a
00643   /// member template.
00644   ///
00645   /// In the following example, the function template \c X<int>::f and the
00646   /// member template \c X<int>::Inner are member specializations.
00647   ///
00648   /// \code
00649   /// template<typename T>
00650   /// struct X {
00651   ///   template<typename U> void f(T, U);
00652   ///   template<typename U> struct Inner;
00653   /// };
00654   ///
00655   /// template<> template<typename T>
00656   /// void X<int>::f(int, T);
00657   /// template<> template<typename T>
00658   /// struct X<int>::Inner { /* ... */ };
00659   /// \endcode
00660   bool isMemberSpecialization() const {
00661     return getCommonPtr()->InstantiatedFromMember.getInt();
00662   }
00663 
00664   /// \brief Note that this member template is a specialization.
00665   void setMemberSpecialization() {
00666     assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
00667            "Only member templates can be member template specializations");
00668     getCommonPtr()->InstantiatedFromMember.setInt(true);
00669   }
00670 
00671   /// \brief Retrieve the member template from which this template was
00672   /// instantiated, or NULL if this template was not instantiated from a 
00673   /// member template.
00674   ///
00675   /// A template is instantiated from a member template when the member 
00676   /// template itself is part of a class template (or member thereof). For
00677   /// example, given
00678   ///
00679   /// \code
00680   /// template<typename T>
00681   /// struct X {
00682   ///   template<typename U> void f(T, U);
00683   /// };
00684   ///
00685   /// void test(X<int> x) {
00686   ///   x.f(1, 'a');
00687   /// };
00688   /// \endcode
00689   ///
00690   /// \c X<int>::f is a FunctionTemplateDecl that describes the function
00691   /// template
00692   ///
00693   /// \code
00694   /// template<typename U> void X<int>::f(int, U);
00695   /// \endcode
00696   ///
00697   /// which was itself created during the instantiation of \c X<int>. Calling
00698   /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
00699   /// retrieve the FunctionTemplateDecl for the original template \c f within
00700   /// the class template \c X<T>, i.e.,
00701   ///
00702   /// \code
00703   /// template<typename T>
00704   /// template<typename U>
00705   /// void X<T>::f(T, U);
00706   /// \endcode
00707   RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
00708     return getCommonPtr()->InstantiatedFromMember.getPointer();
00709   }
00710 
00711   void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
00712     assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
00713     getCommonPtr()->InstantiatedFromMember.setPointer(TD);
00714   }
00715 
00716   typedef redeclarable_base::redecl_range redecl_range;
00717   typedef redeclarable_base::redecl_iterator redecl_iterator;
00718   using redeclarable_base::redecls_begin;
00719   using redeclarable_base::redecls_end;
00720   using redeclarable_base::redecls;
00721   using redeclarable_base::getPreviousDecl;
00722   using redeclarable_base::getMostRecentDecl;
00723   using redeclarable_base::isFirstDecl;
00724 
00725   // Implement isa/cast/dyncast/etc.
00726   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
00727   static bool classofKind(Kind K) {
00728     return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
00729   }
00730 
00731   friend class ASTReader;
00732   friend class ASTDeclReader;
00733   friend class ASTDeclWriter;
00734 };
00735 
00736 template <> struct RedeclarableTemplateDecl::
00737 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
00738   typedef FunctionDecl DeclType;
00739 
00740   static DeclType *
00741   getMostRecentDecl(FunctionTemplateSpecializationInfo *I) {
00742     return I->Function->getMostRecentDecl();
00743   }
00744 };
00745 
00746 /// Declaration of a template function.
00747 class FunctionTemplateDecl : public RedeclarableTemplateDecl {
00748   static void DeallocateCommon(void *Ptr);
00749 
00750 protected:
00751   /// \brief Data that is common to all of the declarations of a given
00752   /// function template.
00753   struct Common : CommonBase {
00754     Common() : InjectedArgs(), LazySpecializations() { }
00755 
00756     /// \brief The function template specializations for this function
00757     /// template, including explicit specializations and instantiations.
00758     llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
00759 
00760     /// \brief The set of "injected" template arguments used within this
00761     /// function template.
00762     ///
00763     /// This pointer refers to the template arguments (there are as
00764     /// many template arguments as template parameaters) for the function
00765     /// template, and is allocated lazily, since most function templates do not
00766     /// require the use of this information.
00767     TemplateArgument *InjectedArgs;
00768 
00769     /// \brief If non-null, points to an array of specializations known only
00770     /// by their external declaration IDs.
00771     ///
00772     /// The first value in the array is the number of of specializations
00773     /// that follow.
00774     uint32_t *LazySpecializations;
00775   };
00776 
00777   FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
00778                        DeclarationName Name, TemplateParameterList *Params,
00779                        NamedDecl *Decl)
00780       : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
00781                                  Decl) {}
00782 
00783   CommonBase *newCommon(ASTContext &C) const override;
00784 
00785   Common *getCommonPtr() const {
00786     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
00787   }
00788 
00789   friend class FunctionDecl;
00790 
00791   /// \brief Load any lazily-loaded specializations from the external source.
00792   void LoadLazySpecializations() const;
00793 
00794   /// \brief Retrieve the set of function template specializations of this
00795   /// function template.
00796   llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
00797   getSpecializations() const;
00798 
00799   /// \brief Add a specialization of this function template.
00800   ///
00801   /// \param InsertPos Insert position in the FoldingSetVector, must have been
00802   ///        retrieved by an earlier call to findSpecialization().
00803   void addSpecialization(FunctionTemplateSpecializationInfo* Info,
00804                          void *InsertPos);
00805 
00806 public:
00807   /// Get the underlying function declaration of the template.
00808   FunctionDecl *getTemplatedDecl() const {
00809     return static_cast<FunctionDecl*>(TemplatedDecl);
00810   }
00811 
00812   /// Returns whether this template declaration defines the primary
00813   /// pattern.
00814   bool isThisDeclarationADefinition() const {
00815     return getTemplatedDecl()->isThisDeclarationADefinition();
00816   }
00817 
00818   /// \brief Return the specialization with the provided arguments if it exists,
00819   /// otherwise return the insertion point.
00820   FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
00821                                    void *&InsertPos);
00822 
00823   FunctionTemplateDecl *getCanonicalDecl() override {
00824     return cast<FunctionTemplateDecl>(
00825              RedeclarableTemplateDecl::getCanonicalDecl());
00826   }
00827   const FunctionTemplateDecl *getCanonicalDecl() const {
00828     return cast<FunctionTemplateDecl>(
00829              RedeclarableTemplateDecl::getCanonicalDecl());
00830   }
00831 
00832   /// \brief Retrieve the previous declaration of this function template, or
00833   /// NULL if no such declaration exists.
00834   FunctionTemplateDecl *getPreviousDecl() {
00835     return cast_or_null<FunctionTemplateDecl>(
00836              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
00837   }
00838 
00839   /// \brief Retrieve the previous declaration of this function template, or
00840   /// NULL if no such declaration exists.
00841   const FunctionTemplateDecl *getPreviousDecl() const {
00842     return cast_or_null<FunctionTemplateDecl>(
00843        static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
00844   }
00845 
00846   FunctionTemplateDecl *getInstantiatedFromMemberTemplate() {
00847     return cast_or_null<FunctionTemplateDecl>(
00848              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
00849   }
00850 
00851   typedef SpecIterator<FunctionTemplateSpecializationInfo> spec_iterator;
00852   typedef llvm::iterator_range<spec_iterator> spec_range;
00853 
00854   spec_range specializations() const {
00855     return spec_range(spec_begin(), spec_end());
00856   }
00857   spec_iterator spec_begin() const {
00858     return makeSpecIterator(getSpecializations(), false);
00859   }
00860 
00861   spec_iterator spec_end() const {
00862     return makeSpecIterator(getSpecializations(), true);
00863   }
00864 
00865   /// \brief Retrieve the "injected" template arguments that correspond to the
00866   /// template parameters of this function template.
00867   ///
00868   /// Although the C++ standard has no notion of the "injected" template
00869   /// arguments for a function template, the notion is convenient when
00870   /// we need to perform substitutions inside the definition of a function
00871   /// template.
00872   ArrayRef<TemplateArgument> getInjectedTemplateArgs();
00873 
00874   /// \brief Create a function template node.
00875   static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
00876                                       SourceLocation L,
00877                                       DeclarationName Name,
00878                                       TemplateParameterList *Params,
00879                                       NamedDecl *Decl);
00880 
00881   /// \brief Create an empty function template node.
00882   static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
00883 
00884   // Implement isa/cast/dyncast support
00885   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
00886   static bool classofKind(Kind K) { return K == FunctionTemplate; }
00887 
00888   friend class ASTDeclReader;
00889   friend class ASTDeclWriter;
00890 };
00891 
00892 //===----------------------------------------------------------------------===//
00893 // Kinds of Template Parameters
00894 //===----------------------------------------------------------------------===//
00895 
00896 /// \brief Defines the position of a template parameter within a template
00897 /// parameter list.
00898 ///
00899 /// Because template parameter can be listed
00900 /// sequentially for out-of-line template members, each template parameter is
00901 /// given a Depth - the nesting of template parameter scopes - and a Position -
00902 /// the occurrence within the parameter list.
00903 /// This class is inheritedly privately by different kinds of template
00904 /// parameters and is not part of the Decl hierarchy. Just a facility.
00905 class TemplateParmPosition {
00906   TemplateParmPosition() LLVM_DELETED_FUNCTION;
00907 
00908 protected:
00909   TemplateParmPosition(unsigned D, unsigned P)
00910     : Depth(D), Position(P)
00911   { }
00912 
00913   // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
00914   // position? Maybe?
00915   unsigned Depth;
00916   unsigned Position;
00917 
00918 public:
00919   /// Get the nesting depth of the template parameter.
00920   unsigned getDepth() const { return Depth; }
00921   void setDepth(unsigned D) { Depth = D; }
00922 
00923   /// Get the position of the template parameter within its parameter list.
00924   unsigned getPosition() const { return Position; }
00925   void setPosition(unsigned P) { Position = P; }
00926 
00927   /// Get the index of the template parameter within its parameter list.
00928   unsigned getIndex() const { return Position; }
00929 };
00930 
00931 /// \brief Declaration of a template type parameter.
00932 ///
00933 /// For example, "T" in
00934 /// \code
00935 /// template<typename T> class vector;
00936 /// \endcode
00937 class TemplateTypeParmDecl : public TypeDecl {
00938   /// \brief Whether this template type parameter was declaration with
00939   /// the 'typename' keyword.
00940   ///
00941   /// If false, it was declared with the 'class' keyword.
00942   bool Typename : 1;
00943 
00944   /// \brief Whether this template type parameter inherited its
00945   /// default argument.
00946   bool InheritedDefault : 1;
00947 
00948   /// \brief The default template argument, if any.
00949   TypeSourceInfo *DefaultArgument;
00950 
00951   TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
00952                        SourceLocation IdLoc, IdentifierInfo *Id,
00953                        bool Typename)
00954     : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
00955       InheritedDefault(false), DefaultArgument() { }
00956 
00957   /// Sema creates these on the stack during auto type deduction.
00958   friend class Sema;
00959 
00960 public:
00961   static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
00962                                       SourceLocation KeyLoc,
00963                                       SourceLocation NameLoc,
00964                                       unsigned D, unsigned P,
00965                                       IdentifierInfo *Id, bool Typename,
00966                                       bool ParameterPack);
00967   static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, 
00968                                                   unsigned ID);
00969 
00970   /// \brief Whether this template type parameter was declared with
00971   /// the 'typename' keyword.
00972   ///
00973   /// If not, it was declared with the 'class' keyword.
00974   bool wasDeclaredWithTypename() const { return Typename; }
00975 
00976   /// \brief Determine whether this template parameter has a default
00977   /// argument.
00978   bool hasDefaultArgument() const { return DefaultArgument != nullptr; }
00979 
00980   /// \brief Retrieve the default argument, if any.
00981   QualType getDefaultArgument() const { return DefaultArgument->getType(); }
00982 
00983   /// \brief Retrieves the default argument's source information, if any.
00984   TypeSourceInfo *getDefaultArgumentInfo() const { return DefaultArgument; }
00985 
00986   /// \brief Retrieves the location of the default argument declaration.
00987   SourceLocation getDefaultArgumentLoc() const;
00988 
00989   /// \brief Determines whether the default argument was inherited
00990   /// from a previous declaration of this template.
00991   bool defaultArgumentWasInherited() const { return InheritedDefault; }
00992 
00993   /// \brief Set the default argument for this template parameter, and
00994   /// whether that default argument was inherited from another
00995   /// declaration.
00996   void setDefaultArgument(TypeSourceInfo *DefArg, bool Inherited) {
00997     DefaultArgument = DefArg;
00998     InheritedDefault = Inherited;
00999   }
01000 
01001   /// \brief Removes the default argument of this template parameter.
01002   void removeDefaultArgument() {
01003     DefaultArgument = nullptr;
01004     InheritedDefault = false;
01005   }
01006 
01007   /// \brief Set whether this template type parameter was declared with
01008   /// the 'typename' or 'class' keyword.
01009   void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
01010 
01011   /// \brief Retrieve the depth of the template parameter.
01012   unsigned getDepth() const;
01013 
01014   /// \brief Retrieve the index of the template parameter.
01015   unsigned getIndex() const;
01016 
01017   /// \brief Returns whether this is a parameter pack.
01018   bool isParameterPack() const;
01019 
01020   SourceRange getSourceRange() const override LLVM_READONLY;
01021 
01022   // Implement isa/cast/dyncast/etc.
01023   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01024   static bool classofKind(Kind K) { return K == TemplateTypeParm; }
01025 };
01026 
01027 /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
01028 /// e.g., "Size" in
01029 /// @code
01030 /// template<int Size> class array { };
01031 /// @endcode
01032 class NonTypeTemplateParmDecl
01033   : public DeclaratorDecl, protected TemplateParmPosition {
01034   /// \brief The default template argument, if any, and whether or not
01035   /// it was inherited.
01036   llvm::PointerIntPair<Expr*, 1, bool> DefaultArgumentAndInherited;
01037 
01038   // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
01039   // down here to save memory.
01040 
01041   /// \brief Whether this non-type template parameter is a parameter pack.
01042   bool ParameterPack;
01043 
01044   /// \brief Whether this non-type template parameter is an "expanded"
01045   /// parameter pack, meaning that its type is a pack expansion and we
01046   /// already know the set of types that expansion expands to.
01047   bool ExpandedParameterPack;
01048 
01049   /// \brief The number of types in an expanded parameter pack.
01050   unsigned NumExpandedTypes;
01051 
01052   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
01053                           SourceLocation IdLoc, unsigned D, unsigned P,
01054                           IdentifierInfo *Id, QualType T,
01055                           bool ParameterPack, TypeSourceInfo *TInfo)
01056     : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
01057       TemplateParmPosition(D, P), DefaultArgumentAndInherited(nullptr, false),
01058       ParameterPack(ParameterPack), ExpandedParameterPack(false),
01059       NumExpandedTypes(0)
01060   { }
01061 
01062   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
01063                           SourceLocation IdLoc, unsigned D, unsigned P,
01064                           IdentifierInfo *Id, QualType T,
01065                           TypeSourceInfo *TInfo,
01066                           const QualType *ExpandedTypes,
01067                           unsigned NumExpandedTypes,
01068                           TypeSourceInfo **ExpandedTInfos);
01069 
01070   friend class ASTDeclReader;
01071 
01072 public:
01073   static NonTypeTemplateParmDecl *
01074   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
01075          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
01076          QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
01077 
01078   static NonTypeTemplateParmDecl *
01079   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
01080          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
01081          QualType T, TypeSourceInfo *TInfo,
01082          const QualType *ExpandedTypes, unsigned NumExpandedTypes,
01083          TypeSourceInfo **ExpandedTInfos);
01084 
01085   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, 
01086                                                      unsigned ID);
01087   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, 
01088                                                      unsigned ID,
01089                                                      unsigned NumExpandedTypes);
01090     
01091   using TemplateParmPosition::getDepth;
01092   using TemplateParmPosition::setDepth;
01093   using TemplateParmPosition::getPosition;
01094   using TemplateParmPosition::setPosition;
01095   using TemplateParmPosition::getIndex;
01096 
01097   SourceRange getSourceRange() const override LLVM_READONLY;
01098 
01099   /// \brief Determine whether this template parameter has a default
01100   /// argument.
01101   bool hasDefaultArgument() const {
01102     return DefaultArgumentAndInherited.getPointer() != nullptr;
01103   }
01104 
01105   /// \brief Retrieve the default argument, if any.
01106   Expr *getDefaultArgument() const {
01107     return DefaultArgumentAndInherited.getPointer();
01108   }
01109 
01110   /// \brief Retrieve the location of the default argument, if any.
01111   SourceLocation getDefaultArgumentLoc() const;
01112 
01113   /// \brief Determines whether the default argument was inherited
01114   /// from a previous declaration of this template.
01115   bool defaultArgumentWasInherited() const {
01116     return DefaultArgumentAndInherited.getInt();
01117   }
01118 
01119   /// \brief Set the default argument for this template parameter, and
01120   /// whether that default argument was inherited from another
01121   /// declaration.
01122   void setDefaultArgument(Expr *DefArg, bool Inherited) {
01123     DefaultArgumentAndInherited.setPointer(DefArg);
01124     DefaultArgumentAndInherited.setInt(Inherited);
01125   }
01126 
01127   /// \brief Removes the default argument of this template parameter.
01128   void removeDefaultArgument() {
01129     DefaultArgumentAndInherited.setPointer(nullptr);
01130     DefaultArgumentAndInherited.setInt(false);
01131   }
01132 
01133   /// \brief Whether this parameter is a non-type template parameter pack.
01134   ///
01135   /// If the parameter is a parameter pack, the type may be a
01136   /// \c PackExpansionType. In the following example, the \c Dims parameter
01137   /// is a parameter pack (whose type is 'unsigned').
01138   ///
01139   /// \code
01140   /// template<typename T, unsigned ...Dims> struct multi_array;
01141   /// \endcode
01142   bool isParameterPack() const { return ParameterPack; }
01143 
01144   /// \brief Whether this parameter pack is a pack expansion.
01145   ///
01146   /// A non-type template parameter pack is a pack expansion if its type
01147   /// contains an unexpanded parameter pack. In this case, we will have
01148   /// built a PackExpansionType wrapping the type.
01149   bool isPackExpansion() const {
01150     return ParameterPack && getType()->getAs<PackExpansionType>();
01151   }
01152 
01153   /// \brief Whether this parameter is a non-type template parameter pack
01154   /// that has a known list of different types at different positions.
01155   ///
01156   /// A parameter pack is an expanded parameter pack when the original
01157   /// parameter pack's type was itself a pack expansion, and that expansion
01158   /// has already been expanded. For example, given:
01159   ///
01160   /// \code
01161   /// template<typename ...Types>
01162   /// struct X {
01163   ///   template<Types ...Values>
01164   ///   struct Y { /* ... */ };
01165   /// };
01166   /// \endcode
01167   ///
01168   /// The parameter pack \c Values has a \c PackExpansionType as its type,
01169   /// which expands \c Types. When \c Types is supplied with template arguments
01170   /// by instantiating \c X, the instantiation of \c Values becomes an
01171   /// expanded parameter pack. For example, instantiating
01172   /// \c X<int, unsigned int> results in \c Values being an expanded parameter
01173   /// pack with expansion types \c int and \c unsigned int.
01174   ///
01175   /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
01176   /// return the expansion types.
01177   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
01178 
01179   /// \brief Retrieves the number of expansion types in an expanded parameter
01180   /// pack.
01181   unsigned getNumExpansionTypes() const {
01182     assert(ExpandedParameterPack && "Not an expansion parameter pack");
01183     return NumExpandedTypes;
01184   }
01185 
01186   /// \brief Retrieve a particular expansion type within an expanded parameter
01187   /// pack.
01188   QualType getExpansionType(unsigned I) const {
01189     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
01190     void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
01191     return QualType::getFromOpaquePtr(TypesAndInfos[2*I]);
01192   }
01193 
01194   /// \brief Retrieve a particular expansion type source info within an
01195   /// expanded parameter pack.
01196   TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
01197     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
01198     void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
01199     return static_cast<TypeSourceInfo *>(TypesAndInfos[2*I+1]);
01200   }
01201 
01202   // Implement isa/cast/dyncast/etc.
01203   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01204   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
01205 };
01206 
01207 /// TemplateTemplateParmDecl - Declares a template template parameter,
01208 /// e.g., "T" in
01209 /// @code
01210 /// template <template <typename> class T> class container { };
01211 /// @endcode
01212 /// A template template parameter is a TemplateDecl because it defines the
01213 /// name of a template and the template parameters allowable for substitution.
01214 class TemplateTemplateParmDecl : public TemplateDecl, 
01215                                  protected TemplateParmPosition 
01216 {
01217   void anchor() override;
01218 
01219   /// DefaultArgument - The default template argument, if any.
01220   TemplateArgumentLoc DefaultArgument;
01221   /// Whether or not the default argument was inherited.
01222   bool DefaultArgumentWasInherited;
01223 
01224   /// \brief Whether this parameter is a parameter pack.
01225   bool ParameterPack;
01226 
01227   /// \brief Whether this template template parameter is an "expanded"
01228   /// parameter pack, meaning that it is a pack expansion and we
01229   /// already know the set of template parameters that expansion expands to.
01230   bool ExpandedParameterPack;
01231 
01232   /// \brief The number of parameters in an expanded parameter pack.
01233   unsigned NumExpandedParams;
01234 
01235   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
01236                            unsigned D, unsigned P, bool ParameterPack,
01237                            IdentifierInfo *Id, TemplateParameterList *Params)
01238     : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
01239       TemplateParmPosition(D, P), DefaultArgument(),
01240       DefaultArgumentWasInherited(false), ParameterPack(ParameterPack),
01241       ExpandedParameterPack(false), NumExpandedParams(0)
01242     { }
01243 
01244   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
01245                            unsigned D, unsigned P,
01246                            IdentifierInfo *Id, TemplateParameterList *Params,
01247                            unsigned NumExpansions,
01248                            TemplateParameterList * const *Expansions);
01249 
01250 public:
01251   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
01252                                           SourceLocation L, unsigned D,
01253                                           unsigned P, bool ParameterPack,
01254                                           IdentifierInfo *Id,
01255                                           TemplateParameterList *Params);
01256   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
01257                                           SourceLocation L, unsigned D,
01258                                           unsigned P,
01259                                           IdentifierInfo *Id,
01260                                           TemplateParameterList *Params,
01261                                  ArrayRef<TemplateParameterList *> Expansions);
01262 
01263   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
01264                                                       unsigned ID);
01265   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
01266                                                       unsigned ID,
01267                                                       unsigned NumExpansions);
01268   
01269   using TemplateParmPosition::getDepth;
01270   using TemplateParmPosition::getPosition;
01271   using TemplateParmPosition::getIndex;
01272 
01273   /// \brief Whether this template template parameter is a template
01274   /// parameter pack.
01275   ///
01276   /// \code
01277   /// template<template <class T> ...MetaFunctions> struct Apply;
01278   /// \endcode
01279   bool isParameterPack() const { return ParameterPack; }
01280 
01281   /// \brief Whether this parameter pack is a pack expansion.
01282   ///
01283   /// A template template parameter pack is a pack expansion if its template
01284   /// parameter list contains an unexpanded parameter pack.
01285   bool isPackExpansion() const {
01286     return ParameterPack &&
01287            getTemplateParameters()->containsUnexpandedParameterPack();
01288   }
01289 
01290   /// \brief Whether this parameter is a template template parameter pack that
01291   /// has a known list of different template parameter lists at different
01292   /// positions.
01293   ///
01294   /// A parameter pack is an expanded parameter pack when the original parameter
01295   /// pack's template parameter list was itself a pack expansion, and that
01296   /// expansion has already been expanded. For exampe, given:
01297   ///
01298   /// \code
01299   /// template<typename...Types> struct Outer {
01300   ///   template<template<Types> class...Templates> struct Inner;
01301   /// };
01302   /// \endcode
01303   ///
01304   /// The parameter pack \c Templates is a pack expansion, which expands the
01305   /// pack \c Types. When \c Types is supplied with template arguments by
01306   /// instantiating \c Outer, the instantiation of \c Templates is an expanded
01307   /// parameter pack.
01308   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
01309 
01310   /// \brief Retrieves the number of expansion template parameters in
01311   /// an expanded parameter pack.
01312   unsigned getNumExpansionTemplateParameters() const {
01313     assert(ExpandedParameterPack && "Not an expansion parameter pack");
01314     return NumExpandedParams;
01315   }
01316 
01317   /// \brief Retrieve a particular expansion type within an expanded parameter
01318   /// pack.
01319   TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
01320     assert(I < NumExpandedParams && "Out-of-range expansion type index");
01321     return reinterpret_cast<TemplateParameterList *const *>(this + 1)[I];
01322   }
01323 
01324   /// \brief Determine whether this template parameter has a default
01325   /// argument.
01326   bool hasDefaultArgument() const {
01327     return !DefaultArgument.getArgument().isNull();
01328   }
01329 
01330   /// \brief Retrieve the default argument, if any.
01331   const TemplateArgumentLoc &getDefaultArgument() const {
01332     return DefaultArgument;
01333   }
01334 
01335   /// \brief Retrieve the location of the default argument, if any.
01336   SourceLocation getDefaultArgumentLoc() const;
01337 
01338   /// \brief Determines whether the default argument was inherited
01339   /// from a previous declaration of this template.
01340   bool defaultArgumentWasInherited() const {
01341     return DefaultArgumentWasInherited;
01342   }
01343 
01344   /// \brief Set the default argument for this template parameter, and
01345   /// whether that default argument was inherited from another
01346   /// declaration.
01347   void setDefaultArgument(const TemplateArgumentLoc &DefArg, bool Inherited) {
01348     DefaultArgument = DefArg;
01349     DefaultArgumentWasInherited = Inherited;
01350   }
01351 
01352   /// \brief Removes the default argument of this template parameter.
01353   void removeDefaultArgument() {
01354     DefaultArgument = TemplateArgumentLoc();
01355     DefaultArgumentWasInherited = false;
01356   }
01357 
01358   SourceRange getSourceRange() const override LLVM_READONLY {
01359     SourceLocation End = getLocation();
01360     if (hasDefaultArgument() && !defaultArgumentWasInherited())
01361       End = getDefaultArgument().getSourceRange().getEnd();
01362     return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
01363   }
01364 
01365   // Implement isa/cast/dyncast/etc.
01366   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01367   static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
01368 
01369   friend class ASTDeclReader;
01370   friend class ASTDeclWriter;
01371 };
01372 
01373 /// \brief Represents a class template specialization, which refers to
01374 /// a class template with a given set of template arguments.
01375 ///
01376 /// Class template specializations represent both explicit
01377 /// specialization of class templates, as in the example below, and
01378 /// implicit instantiations of class templates.
01379 ///
01380 /// \code
01381 /// template<typename T> class array;
01382 ///
01383 /// template<>
01384 /// class array<bool> { }; // class template specialization array<bool>
01385 /// \endcode
01386 class ClassTemplateSpecializationDecl
01387   : public CXXRecordDecl, public llvm::FoldingSetNode {
01388 
01389   /// \brief Structure that stores information about a class template
01390   /// specialization that was instantiated from a class template partial
01391   /// specialization.
01392   struct SpecializedPartialSpecialization {
01393     /// \brief The class template partial specialization from which this
01394     /// class template specialization was instantiated.
01395     ClassTemplatePartialSpecializationDecl *PartialSpecialization;
01396 
01397     /// \brief The template argument list deduced for the class template
01398     /// partial specialization itself.
01399     const TemplateArgumentList *TemplateArgs;
01400   };
01401 
01402   /// \brief The template that this specialization specializes
01403   llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
01404     SpecializedTemplate;
01405 
01406   /// \brief Further info for explicit template specialization/instantiation.
01407   struct ExplicitSpecializationInfo {
01408     /// \brief The type-as-written.
01409     TypeSourceInfo *TypeAsWritten;
01410     /// \brief The location of the extern keyword.
01411     SourceLocation ExternLoc;
01412     /// \brief The location of the template keyword.
01413     SourceLocation TemplateKeywordLoc;
01414 
01415     ExplicitSpecializationInfo()
01416       : TypeAsWritten(nullptr), ExternLoc(), TemplateKeywordLoc() {}
01417   };
01418 
01419   /// \brief Further info for explicit template specialization/instantiation.
01420   /// Does not apply to implicit specializations.
01421   ExplicitSpecializationInfo *ExplicitInfo;
01422 
01423   /// \brief The template arguments used to describe this specialization.
01424   const TemplateArgumentList *TemplateArgs;
01425 
01426   /// \brief The point where this template was instantiated (if any)
01427   SourceLocation PointOfInstantiation;
01428 
01429   /// \brief The kind of specialization this declaration refers to.
01430   /// Really a value of type TemplateSpecializationKind.
01431   unsigned SpecializationKind : 3;
01432 
01433 protected:
01434   ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
01435                                   DeclContext *DC, SourceLocation StartLoc,
01436                                   SourceLocation IdLoc,
01437                                   ClassTemplateDecl *SpecializedTemplate,
01438                                   const TemplateArgument *Args,
01439                                   unsigned NumArgs,
01440                                   ClassTemplateSpecializationDecl *PrevDecl);
01441 
01442   explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
01443 
01444 public:
01445   static ClassTemplateSpecializationDecl *
01446   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
01447          SourceLocation StartLoc, SourceLocation IdLoc,
01448          ClassTemplateDecl *SpecializedTemplate,
01449          const TemplateArgument *Args,
01450          unsigned NumArgs,
01451          ClassTemplateSpecializationDecl *PrevDecl);
01452   static ClassTemplateSpecializationDecl *
01453   CreateDeserialized(ASTContext &C, unsigned ID);
01454 
01455   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
01456                             bool Qualified) const override;
01457 
01458   // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
01459   // different "most recent" declaration from this function for the same
01460   // declaration, because we don't override getMostRecentDeclImpl(). But
01461   // it's not clear that we should override that, because the most recent
01462   // declaration as a CXXRecordDecl sometimes is the injected-class-name.
01463   ClassTemplateSpecializationDecl *getMostRecentDecl() {
01464     CXXRecordDecl *Recent = static_cast<CXXRecordDecl *>(
01465                               this)->getMostRecentDecl();
01466     while (!isa<ClassTemplateSpecializationDecl>(Recent)) {
01467       // FIXME: Does injected class name need to be in the redeclarations chain?
01468       assert(Recent->isInjectedClassName() && Recent->getPreviousDecl());
01469       Recent = Recent->getPreviousDecl();
01470     }
01471     return cast<ClassTemplateSpecializationDecl>(Recent);
01472   }
01473 
01474   /// \brief Retrieve the template that this specialization specializes.
01475   ClassTemplateDecl *getSpecializedTemplate() const;
01476 
01477   /// \brief Retrieve the template arguments of the class template
01478   /// specialization.
01479   const TemplateArgumentList &getTemplateArgs() const {
01480     return *TemplateArgs;
01481   }
01482 
01483   /// \brief Determine the kind of specialization that this
01484   /// declaration represents.
01485   TemplateSpecializationKind getSpecializationKind() const {
01486     return static_cast<TemplateSpecializationKind>(SpecializationKind);
01487   }
01488 
01489   bool isExplicitSpecialization() const {
01490     return getSpecializationKind() == TSK_ExplicitSpecialization;
01491   }
01492 
01493   /// \brief True if this declaration is an explicit specialization,
01494   /// explicit instantiation declaration, or explicit instantiation
01495   /// definition.
01496   bool isExplicitInstantiationOrSpecialization() const {
01497     switch (getTemplateSpecializationKind()) {
01498     case TSK_ExplicitSpecialization:
01499     case TSK_ExplicitInstantiationDeclaration:
01500     case TSK_ExplicitInstantiationDefinition:
01501       return true;
01502 
01503     case TSK_Undeclared:
01504     case TSK_ImplicitInstantiation:
01505       return false;
01506     }
01507     llvm_unreachable("bad template specialization kind");
01508   }
01509 
01510   void setSpecializationKind(TemplateSpecializationKind TSK) {
01511     SpecializationKind = TSK;
01512   }
01513 
01514   /// \brief Get the point of instantiation (if any), or null if none.
01515   SourceLocation getPointOfInstantiation() const {
01516     return PointOfInstantiation;
01517   }
01518 
01519   void setPointOfInstantiation(SourceLocation Loc) {
01520     assert(Loc.isValid() && "point of instantiation must be valid!");
01521     PointOfInstantiation = Loc;
01522   }
01523 
01524   /// \brief If this class template specialization is an instantiation of
01525   /// a template (rather than an explicit specialization), return the
01526   /// class template or class template partial specialization from which it
01527   /// was instantiated.
01528   llvm::PointerUnion<ClassTemplateDecl *,
01529                      ClassTemplatePartialSpecializationDecl *>
01530   getInstantiatedFrom() const {
01531     if (!isTemplateInstantiation(getSpecializationKind()))
01532       return llvm::PointerUnion<ClassTemplateDecl *,
01533                                 ClassTemplatePartialSpecializationDecl *>();
01534 
01535     return getSpecializedTemplateOrPartial();
01536   }
01537 
01538   /// \brief Retrieve the class template or class template partial
01539   /// specialization which was specialized by this.
01540   llvm::PointerUnion<ClassTemplateDecl *,
01541                      ClassTemplatePartialSpecializationDecl *>
01542   getSpecializedTemplateOrPartial() const {
01543     if (SpecializedPartialSpecialization *PartialSpec
01544           = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
01545       return PartialSpec->PartialSpecialization;
01546 
01547     return SpecializedTemplate.get<ClassTemplateDecl*>();
01548   }
01549 
01550   /// \brief Retrieve the set of template arguments that should be used
01551   /// to instantiate members of the class template or class template partial
01552   /// specialization from which this class template specialization was
01553   /// instantiated.
01554   ///
01555   /// \returns For a class template specialization instantiated from the primary
01556   /// template, this function will return the same template arguments as
01557   /// getTemplateArgs(). For a class template specialization instantiated from
01558   /// a class template partial specialization, this function will return the
01559   /// deduced template arguments for the class template partial specialization
01560   /// itself.
01561   const TemplateArgumentList &getTemplateInstantiationArgs() const {
01562     if (SpecializedPartialSpecialization *PartialSpec
01563         = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
01564       return *PartialSpec->TemplateArgs;
01565 
01566     return getTemplateArgs();
01567   }
01568 
01569   /// \brief Note that this class template specialization is actually an
01570   /// instantiation of the given class template partial specialization whose
01571   /// template arguments have been deduced.
01572   void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
01573                           const TemplateArgumentList *TemplateArgs) {
01574     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
01575            "Already set to a class template partial specialization!");
01576     SpecializedPartialSpecialization *PS
01577       = new (getASTContext()) SpecializedPartialSpecialization();
01578     PS->PartialSpecialization = PartialSpec;
01579     PS->TemplateArgs = TemplateArgs;
01580     SpecializedTemplate = PS;
01581   }
01582 
01583   /// \brief Note that this class template specialization is an instantiation
01584   /// of the given class template.
01585   void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
01586     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
01587            "Previously set to a class template partial specialization!");
01588     SpecializedTemplate = TemplDecl;
01589   }
01590 
01591   /// \brief Sets the type of this specialization as it was written by
01592   /// the user. This will be a class template specialization type.
01593   void setTypeAsWritten(TypeSourceInfo *T) {
01594     if (!ExplicitInfo)
01595       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
01596     ExplicitInfo->TypeAsWritten = T;
01597   }
01598   /// \brief Gets the type of this specialization as it was written by
01599   /// the user, if it was so written.
01600   TypeSourceInfo *getTypeAsWritten() const {
01601     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
01602   }
01603 
01604   /// \brief Gets the location of the extern keyword, if present.
01605   SourceLocation getExternLoc() const {
01606     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
01607   }
01608   /// \brief Sets the location of the extern keyword.
01609   void setExternLoc(SourceLocation Loc) {
01610     if (!ExplicitInfo)
01611       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
01612     ExplicitInfo->ExternLoc = Loc;
01613   }
01614 
01615   /// \brief Sets the location of the template keyword.
01616   void setTemplateKeywordLoc(SourceLocation Loc) {
01617     if (!ExplicitInfo)
01618       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
01619     ExplicitInfo->TemplateKeywordLoc = Loc;
01620   }
01621   /// \brief Gets the location of the template keyword, if present.
01622   SourceLocation getTemplateKeywordLoc() const {
01623     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
01624   }
01625 
01626   SourceRange getSourceRange() const override LLVM_READONLY;
01627 
01628   void Profile(llvm::FoldingSetNodeID &ID) const {
01629     Profile(ID, TemplateArgs->asArray(), getASTContext());
01630   }
01631 
01632   static void
01633   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
01634           ASTContext &Context) {
01635     ID.AddInteger(TemplateArgs.size());
01636     for (unsigned Arg = 0; Arg != TemplateArgs.size(); ++Arg)
01637       TemplateArgs[Arg].Profile(ID, Context);
01638   }
01639 
01640   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01641   static bool classofKind(Kind K) {
01642     return K >= firstClassTemplateSpecialization &&
01643            K <= lastClassTemplateSpecialization;
01644   }
01645 
01646   friend class ASTDeclReader;
01647   friend class ASTDeclWriter;
01648 };
01649 
01650 class ClassTemplatePartialSpecializationDecl
01651   : public ClassTemplateSpecializationDecl {
01652   void anchor() override;
01653 
01654   /// \brief The list of template parameters
01655   TemplateParameterList* TemplateParams;
01656 
01657   /// \brief The source info for the template arguments as written.
01658   /// FIXME: redundant with TypeAsWritten?
01659   const ASTTemplateArgumentListInfo *ArgsAsWritten;
01660 
01661   /// \brief The class template partial specialization from which this
01662   /// class template partial specialization was instantiated.
01663   ///
01664   /// The boolean value will be true to indicate that this class template
01665   /// partial specialization was specialized at this level.
01666   llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
01667       InstantiatedFromMember;
01668 
01669   ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
01670                                          DeclContext *DC,
01671                                          SourceLocation StartLoc,
01672                                          SourceLocation IdLoc,
01673                                          TemplateParameterList *Params,
01674                                          ClassTemplateDecl *SpecializedTemplate,
01675                                          const TemplateArgument *Args,
01676                                          unsigned NumArgs,
01677                                const ASTTemplateArgumentListInfo *ArgsAsWritten,
01678                                ClassTemplatePartialSpecializationDecl *PrevDecl);
01679 
01680   ClassTemplatePartialSpecializationDecl(ASTContext &C)
01681     : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
01682       TemplateParams(nullptr), ArgsAsWritten(nullptr),
01683       InstantiatedFromMember(nullptr, false) {}
01684 
01685 public:
01686   static ClassTemplatePartialSpecializationDecl *
01687   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
01688          SourceLocation StartLoc, SourceLocation IdLoc,
01689          TemplateParameterList *Params,
01690          ClassTemplateDecl *SpecializedTemplate,
01691          const TemplateArgument *Args,
01692          unsigned NumArgs,
01693          const TemplateArgumentListInfo &ArgInfos,
01694          QualType CanonInjectedType,
01695          ClassTemplatePartialSpecializationDecl *PrevDecl);
01696 
01697   static ClassTemplatePartialSpecializationDecl *
01698   CreateDeserialized(ASTContext &C, unsigned ID);
01699 
01700   ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
01701     return cast<ClassTemplatePartialSpecializationDecl>(
01702              static_cast<ClassTemplateSpecializationDecl *>(
01703                this)->getMostRecentDecl());
01704   }
01705 
01706   /// Get the list of template parameters
01707   TemplateParameterList *getTemplateParameters() const {
01708     return TemplateParams;
01709   }
01710 
01711   /// Get the template arguments as written.
01712   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
01713     return ArgsAsWritten;
01714   }
01715 
01716   /// \brief Retrieve the member class template partial specialization from
01717   /// which this particular class template partial specialization was
01718   /// instantiated.
01719   ///
01720   /// \code
01721   /// template<typename T>
01722   /// struct Outer {
01723   ///   template<typename U> struct Inner;
01724   ///   template<typename U> struct Inner<U*> { }; // #1
01725   /// };
01726   ///
01727   /// Outer<float>::Inner<int*> ii;
01728   /// \endcode
01729   ///
01730   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
01731   /// end up instantiating the partial specialization
01732   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
01733   /// template partial specialization \c Outer<T>::Inner<U*>. Given
01734   /// \c Outer<float>::Inner<U*>, this function would return
01735   /// \c Outer<T>::Inner<U*>.
01736   ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() {
01737     ClassTemplatePartialSpecializationDecl *First =
01738         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
01739     return First->InstantiatedFromMember.getPointer();
01740   }
01741 
01742   void setInstantiatedFromMember(
01743                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
01744     ClassTemplatePartialSpecializationDecl *First =
01745         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
01746     First->InstantiatedFromMember.setPointer(PartialSpec);
01747   }
01748 
01749   /// \brief Determines whether this class template partial specialization
01750   /// template was a specialization of a member partial specialization.
01751   ///
01752   /// In the following example, the member template partial specialization
01753   /// \c X<int>::Inner<T*> is a member specialization.
01754   ///
01755   /// \code
01756   /// template<typename T>
01757   /// struct X {
01758   ///   template<typename U> struct Inner;
01759   ///   template<typename U> struct Inner<U*>;
01760   /// };
01761   ///
01762   /// template<> template<typename T>
01763   /// struct X<int>::Inner<T*> { /* ... */ };
01764   /// \endcode
01765   bool isMemberSpecialization() {
01766     ClassTemplatePartialSpecializationDecl *First =
01767         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
01768     return First->InstantiatedFromMember.getInt();
01769   }
01770 
01771   /// \brief Note that this member template is a specialization.
01772   void setMemberSpecialization() {
01773     ClassTemplatePartialSpecializationDecl *First =
01774         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
01775     assert(First->InstantiatedFromMember.getPointer() &&
01776            "Only member templates can be member template specializations");
01777     return First->InstantiatedFromMember.setInt(true);
01778   }
01779 
01780   /// Retrieves the injected specialization type for this partial
01781   /// specialization.  This is not the same as the type-decl-type for
01782   /// this partial specialization, which is an InjectedClassNameType.
01783   QualType getInjectedSpecializationType() const {
01784     assert(getTypeForDecl() && "partial specialization has no type set!");
01785     return cast<InjectedClassNameType>(getTypeForDecl())
01786              ->getInjectedSpecializationType();
01787   }
01788 
01789   // FIXME: Add Profile support!
01790 
01791   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01792   static bool classofKind(Kind K) {
01793     return K == ClassTemplatePartialSpecialization;
01794   }
01795 
01796   friend class ASTDeclReader;
01797   friend class ASTDeclWriter;
01798 };
01799 
01800 /// Declaration of a class template.
01801 class ClassTemplateDecl : public RedeclarableTemplateDecl {
01802   static void DeallocateCommon(void *Ptr);
01803 
01804 protected:
01805   /// \brief Data that is common to all of the declarations of a given
01806   /// class template.
01807   struct Common : CommonBase {
01808     Common() : LazySpecializations() { }
01809 
01810     /// \brief The class template specializations for this class
01811     /// template, including explicit specializations and instantiations.
01812     llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
01813 
01814     /// \brief The class template partial specializations for this class
01815     /// template.
01816     llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
01817       PartialSpecializations;
01818 
01819     /// \brief The injected-class-name type for this class template.
01820     QualType InjectedClassNameType;
01821 
01822     /// \brief If non-null, points to an array of specializations (including
01823     /// partial specializations) known only by their external declaration IDs.
01824     ///
01825     /// The first value in the array is the number of of specializations/
01826     /// partial specializations that follow.
01827     uint32_t *LazySpecializations;
01828   };
01829 
01830   /// \brief Load any lazily-loaded specializations from the external source.
01831   void LoadLazySpecializations() const;
01832 
01833   /// \brief Retrieve the set of specializations of this class template.
01834   llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
01835   getSpecializations() const;
01836 
01837   /// \brief Retrieve the set of partial specializations of this class
01838   /// template.
01839   llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
01840   getPartialSpecializations();
01841 
01842   ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
01843                     DeclarationName Name, TemplateParameterList *Params,
01844                     NamedDecl *Decl)
01845       : RedeclarableTemplateDecl(ClassTemplate, C, DC, L, Name, Params, Decl) {}
01846 
01847   CommonBase *newCommon(ASTContext &C) const override;
01848 
01849   Common *getCommonPtr() const {
01850     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
01851   }
01852 
01853 public:
01854   /// \brief Get the underlying class declarations of the template.
01855   CXXRecordDecl *getTemplatedDecl() const {
01856     return static_cast<CXXRecordDecl *>(TemplatedDecl);
01857   }
01858 
01859   /// \brief Returns whether this template declaration defines the primary
01860   /// class pattern.
01861   bool isThisDeclarationADefinition() const {
01862     return getTemplatedDecl()->isThisDeclarationADefinition();
01863   }
01864 
01865   /// \brief Create a class template node.
01866   static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
01867                                    SourceLocation L,
01868                                    DeclarationName Name,
01869                                    TemplateParameterList *Params,
01870                                    NamedDecl *Decl,
01871                                    ClassTemplateDecl *PrevDecl);
01872 
01873   /// \brief Create an empty class template node.
01874   static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
01875 
01876   /// \brief Return the specialization with the provided arguments if it exists,
01877   /// otherwise return the insertion point.
01878   ClassTemplateSpecializationDecl *
01879   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
01880 
01881   /// \brief Insert the specified specialization knowing that it is not already
01882   /// in. InsertPos must be obtained from findSpecialization.
01883   void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
01884 
01885   ClassTemplateDecl *getCanonicalDecl() override {
01886     return cast<ClassTemplateDecl>(
01887              RedeclarableTemplateDecl::getCanonicalDecl());
01888   }
01889   const ClassTemplateDecl *getCanonicalDecl() const {
01890     return cast<ClassTemplateDecl>(
01891              RedeclarableTemplateDecl::getCanonicalDecl());
01892   }
01893 
01894   /// \brief Retrieve the previous declaration of this class template, or
01895   /// NULL if no such declaration exists.
01896   ClassTemplateDecl *getPreviousDecl() {
01897     return cast_or_null<ClassTemplateDecl>(
01898              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
01899   }
01900 
01901   /// \brief Retrieve the previous declaration of this class template, or
01902   /// NULL if no such declaration exists.
01903   const ClassTemplateDecl *getPreviousDecl() const {
01904     return cast_or_null<ClassTemplateDecl>(
01905              static_cast<const RedeclarableTemplateDecl *>(
01906                this)->getPreviousDecl());
01907   }
01908 
01909   ClassTemplateDecl *getMostRecentDecl() {
01910     return cast<ClassTemplateDecl>(
01911         static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
01912   }
01913   const ClassTemplateDecl *getMostRecentDecl() const {
01914     return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
01915   }
01916 
01917   ClassTemplateDecl *getInstantiatedFromMemberTemplate() {
01918     return cast_or_null<ClassTemplateDecl>(
01919              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
01920   }
01921 
01922   /// \brief Return the partial specialization with the provided arguments if it
01923   /// exists, otherwise return the insertion point.
01924   ClassTemplatePartialSpecializationDecl *
01925   findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
01926 
01927   /// \brief Insert the specified partial specialization knowing that it is not
01928   /// already in. InsertPos must be obtained from findPartialSpecialization.
01929   void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
01930                                 void *InsertPos);
01931 
01932   /// \brief Retrieve the partial specializations as an ordered list.
01933   void getPartialSpecializations(
01934           SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
01935 
01936   /// \brief Find a class template partial specialization with the given
01937   /// type T.
01938   ///
01939   /// \param T a dependent type that names a specialization of this class
01940   /// template.
01941   ///
01942   /// \returns the class template partial specialization that exactly matches
01943   /// the type \p T, or NULL if no such partial specialization exists.
01944   ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
01945 
01946   /// \brief Find a class template partial specialization which was instantiated
01947   /// from the given member partial specialization.
01948   ///
01949   /// \param D a member class template partial specialization.
01950   ///
01951   /// \returns the class template partial specialization which was instantiated
01952   /// from the given member partial specialization, or NULL if no such partial
01953   /// specialization exists.
01954   ClassTemplatePartialSpecializationDecl *
01955   findPartialSpecInstantiatedFromMember(
01956                                      ClassTemplatePartialSpecializationDecl *D);
01957 
01958   /// \brief Retrieve the template specialization type of the
01959   /// injected-class-name for this class template.
01960   ///
01961   /// The injected-class-name for a class template \c X is \c
01962   /// X<template-args>, where \c template-args is formed from the
01963   /// template arguments that correspond to the template parameters of
01964   /// \c X. For example:
01965   ///
01966   /// \code
01967   /// template<typename T, int N>
01968   /// struct array {
01969   ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
01970   /// };
01971   /// \endcode
01972   QualType getInjectedClassNameSpecialization();
01973 
01974   typedef SpecIterator<ClassTemplateSpecializationDecl> spec_iterator;
01975   typedef llvm::iterator_range<spec_iterator> spec_range;
01976 
01977   spec_range specializations() const {
01978     return spec_range(spec_begin(), spec_end());
01979   }
01980 
01981   spec_iterator spec_begin() const {
01982     return makeSpecIterator(getSpecializations(), false);
01983   }
01984 
01985   spec_iterator spec_end() const {
01986     return makeSpecIterator(getSpecializations(), true);
01987   }
01988 
01989   // Implement isa/cast/dyncast support
01990   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01991   static bool classofKind(Kind K) { return K == ClassTemplate; }
01992 
01993   friend class ASTDeclReader;
01994   friend class ASTDeclWriter;
01995 };
01996 
01997 /// \brief Declaration of a friend template.
01998 ///
01999 /// For example:
02000 /// \code
02001 /// template <typename T> class A {
02002 ///   friend class MyVector<T>; // not a friend template
02003 ///   template <typename U> friend class B; // not a friend template
02004 ///   template <typename U> friend class Foo<T>::Nested; // friend template
02005 /// };
02006 /// \endcode
02007 ///
02008 /// \note This class is not currently in use.  All of the above
02009 /// will yield a FriendDecl, not a FriendTemplateDecl.
02010 class FriendTemplateDecl : public Decl {
02011   virtual void anchor();
02012 public:
02013   typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
02014 
02015 private:
02016   // The number of template parameters;  always non-zero.
02017   unsigned NumParams;
02018 
02019   // The parameter list.
02020   TemplateParameterList **Params;
02021 
02022   // The declaration that's a friend of this class.
02023   FriendUnion Friend;
02024 
02025   // Location of the 'friend' specifier.
02026   SourceLocation FriendLoc;
02027 
02028 
02029   FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
02030                      unsigned NParams,
02031                      TemplateParameterList **Params,
02032                      FriendUnion Friend,
02033                      SourceLocation FriendLoc)
02034     : Decl(Decl::FriendTemplate, DC, Loc),
02035       NumParams(NParams),
02036       Params(Params),
02037       Friend(Friend),
02038       FriendLoc(FriendLoc)
02039   {}
02040 
02041   FriendTemplateDecl(EmptyShell Empty)
02042     : Decl(Decl::FriendTemplate, Empty),
02043       NumParams(0),
02044       Params(nullptr)
02045   {}
02046 
02047 public:
02048   static FriendTemplateDecl *Create(ASTContext &Context,
02049                                     DeclContext *DC, SourceLocation Loc,
02050                                     unsigned NParams,
02051                                     TemplateParameterList **Params,
02052                                     FriendUnion Friend,
02053                                     SourceLocation FriendLoc);
02054 
02055   static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
02056 
02057   /// If this friend declaration names a templated type (or
02058   /// a dependent member type of a templated type), return that
02059   /// type;  otherwise return null.
02060   TypeSourceInfo *getFriendType() const {
02061     return Friend.dyn_cast<TypeSourceInfo*>();
02062   }
02063 
02064   /// If this friend declaration names a templated function (or
02065   /// a member function of a templated type), return that type;
02066   /// otherwise return null.
02067   NamedDecl *getFriendDecl() const {
02068     return Friend.dyn_cast<NamedDecl*>();
02069   }
02070 
02071   /// \brief Retrieves the location of the 'friend' keyword.
02072   SourceLocation getFriendLoc() const {
02073     return FriendLoc;
02074   }
02075 
02076   TemplateParameterList *getTemplateParameterList(unsigned i) const {
02077     assert(i <= NumParams);
02078     return Params[i];
02079   }
02080 
02081   unsigned getNumTemplateParameters() const {
02082     return NumParams;
02083   }
02084 
02085   // Implement isa/cast/dyncast/etc.
02086   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
02087   static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
02088 
02089   friend class ASTDeclReader;
02090 };
02091 
02092 /// \brief Declaration of an alias template.
02093 ///
02094 /// For example:
02095 /// \code
02096 /// template <typename T> using V = std::map<T*, int, MyCompare<T>>;
02097 /// \endcode
02098 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
02099   static void DeallocateCommon(void *Ptr);
02100 
02101 protected:
02102   typedef CommonBase Common;
02103 
02104   TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
02105                         DeclarationName Name, TemplateParameterList *Params,
02106                         NamedDecl *Decl)
02107       : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
02108                                  Decl) {}
02109 
02110   CommonBase *newCommon(ASTContext &C) const override;
02111 
02112   Common *getCommonPtr() {
02113     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
02114   }
02115 
02116 public:
02117   /// Get the underlying function declaration of the template.
02118   TypeAliasDecl *getTemplatedDecl() const {
02119     return static_cast<TypeAliasDecl*>(TemplatedDecl);
02120   }
02121 
02122 
02123   TypeAliasTemplateDecl *getCanonicalDecl() override {
02124     return cast<TypeAliasTemplateDecl>(
02125              RedeclarableTemplateDecl::getCanonicalDecl());
02126   }
02127   const TypeAliasTemplateDecl *getCanonicalDecl() const {
02128     return cast<TypeAliasTemplateDecl>(
02129              RedeclarableTemplateDecl::getCanonicalDecl());
02130   }
02131 
02132   /// \brief Retrieve the previous declaration of this function template, or
02133   /// NULL if no such declaration exists.
02134   TypeAliasTemplateDecl *getPreviousDecl() {
02135     return cast_or_null<TypeAliasTemplateDecl>(
02136              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
02137   }
02138 
02139   /// \brief Retrieve the previous declaration of this function template, or
02140   /// NULL if no such declaration exists.
02141   const TypeAliasTemplateDecl *getPreviousDecl() const {
02142     return cast_or_null<TypeAliasTemplateDecl>(
02143              static_cast<const RedeclarableTemplateDecl *>(
02144                this)->getPreviousDecl());
02145   }
02146 
02147   TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() {
02148     return cast_or_null<TypeAliasTemplateDecl>(
02149              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
02150   }
02151 
02152 
02153   /// \brief Create a function template node.
02154   static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
02155                                        SourceLocation L,
02156                                        DeclarationName Name,
02157                                        TemplateParameterList *Params,
02158                                        NamedDecl *Decl);
02159 
02160   /// \brief Create an empty alias template node.
02161   static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
02162 
02163   // Implement isa/cast/dyncast support
02164   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
02165   static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
02166 
02167   friend class ASTDeclReader;
02168   friend class ASTDeclWriter;
02169 };
02170 
02171 /// \brief Declaration of a function specialization at template class scope.
02172 ///
02173 /// This is a non-standard extension needed to support MSVC.
02174 ///
02175 /// For example:
02176 /// \code
02177 /// template <class T>
02178 /// class A {
02179 ///    template <class U> void foo(U a) { }
02180 ///    template<> void foo(int a) { }
02181 /// }
02182 /// \endcode
02183 ///
02184 /// "template<> foo(int a)" will be saved in Specialization as a normal
02185 /// CXXMethodDecl. Then during an instantiation of class A, it will be
02186 /// transformed into an actual function specialization.
02187 class ClassScopeFunctionSpecializationDecl : public Decl {
02188   virtual void anchor();
02189 
02190   ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
02191                                        CXXMethodDecl *FD, bool Args,
02192                                        TemplateArgumentListInfo TemplArgs)
02193     : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
02194       Specialization(FD), HasExplicitTemplateArgs(Args),
02195       TemplateArgs(TemplArgs) {}
02196 
02197   ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
02198     : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
02199 
02200   CXXMethodDecl *Specialization;
02201   bool HasExplicitTemplateArgs;
02202   TemplateArgumentListInfo TemplateArgs;
02203 
02204 public:
02205   CXXMethodDecl *getSpecialization() const { return Specialization; }
02206   bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
02207   const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
02208 
02209   static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
02210                                                       DeclContext *DC,
02211                                                       SourceLocation Loc,
02212                                                       CXXMethodDecl *FD,
02213                                                    bool HasExplicitTemplateArgs,
02214                                         TemplateArgumentListInfo TemplateArgs) {
02215     return new (C, DC) ClassScopeFunctionSpecializationDecl(
02216         DC, Loc, FD, HasExplicitTemplateArgs, TemplateArgs);
02217   }
02218 
02219   static ClassScopeFunctionSpecializationDecl *
02220   CreateDeserialized(ASTContext &Context, unsigned ID);
02221   
02222   // Implement isa/cast/dyncast/etc.
02223   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
02224   static bool classofKind(Kind K) {
02225     return K == Decl::ClassScopeFunctionSpecialization;
02226   }
02227 
02228   friend class ASTDeclReader;
02229   friend class ASTDeclWriter;
02230 };
02231 
02232 /// Implementation of inline functions that require the template declarations
02233 inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
02234   : Function(FTD) { }
02235 
02236 /// \brief Represents a variable template specialization, which refers to
02237 /// a variable template with a given set of template arguments.
02238 ///
02239 /// Variable template specializations represent both explicit
02240 /// specializations of variable templates, as in the example below, and
02241 /// implicit instantiations of variable templates.
02242 ///
02243 /// \code
02244 /// template<typename T> constexpr T pi = T(3.1415926535897932385);
02245 ///
02246 /// template<>
02247 /// constexpr float pi<float>; // variable template specialization pi<float>
02248 /// \endcode
02249 class VarTemplateSpecializationDecl : public VarDecl,
02250                                       public llvm::FoldingSetNode {
02251 
02252   /// \brief Structure that stores information about a variable template
02253   /// specialization that was instantiated from a variable template partial
02254   /// specialization.
02255   struct SpecializedPartialSpecialization {
02256     /// \brief The variable template partial specialization from which this
02257     /// variable template specialization was instantiated.
02258     VarTemplatePartialSpecializationDecl *PartialSpecialization;
02259 
02260     /// \brief The template argument list deduced for the variable template
02261     /// partial specialization itself.
02262     const TemplateArgumentList *TemplateArgs;
02263   };
02264 
02265   /// \brief The template that this specialization specializes.
02266   llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
02267   SpecializedTemplate;
02268 
02269   /// \brief Further info for explicit template specialization/instantiation.
02270   struct ExplicitSpecializationInfo {
02271     /// \brief The type-as-written.
02272     TypeSourceInfo *TypeAsWritten;
02273     /// \brief The location of the extern keyword.
02274     SourceLocation ExternLoc;
02275     /// \brief The location of the template keyword.
02276     SourceLocation TemplateKeywordLoc;
02277 
02278     ExplicitSpecializationInfo()
02279         : TypeAsWritten(nullptr), ExternLoc(), TemplateKeywordLoc() {}
02280   };
02281 
02282   /// \brief Further info for explicit template specialization/instantiation.
02283   /// Does not apply to implicit specializations.
02284   ExplicitSpecializationInfo *ExplicitInfo;
02285 
02286   /// \brief The template arguments used to describe this specialization.
02287   const TemplateArgumentList *TemplateArgs;
02288   TemplateArgumentListInfo TemplateArgsInfo;
02289 
02290   /// \brief The point where this template was instantiated (if any).
02291   SourceLocation PointOfInstantiation;
02292 
02293   /// \brief The kind of specialization this declaration refers to.
02294   /// Really a value of type TemplateSpecializationKind.
02295   unsigned SpecializationKind : 3;
02296 
02297 protected:
02298   VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
02299                                 SourceLocation StartLoc, SourceLocation IdLoc,
02300                                 VarTemplateDecl *SpecializedTemplate,
02301                                 QualType T, TypeSourceInfo *TInfo,
02302                                 StorageClass S, const TemplateArgument *Args,
02303                                 unsigned NumArgs);
02304 
02305   explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
02306 
02307 public:
02308   static VarTemplateSpecializationDecl *
02309   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
02310          SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
02311          TypeSourceInfo *TInfo, StorageClass S, const TemplateArgument *Args,
02312          unsigned NumArgs);
02313   static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
02314                                                            unsigned ID);
02315 
02316   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
02317                             bool Qualified) const override;
02318 
02319   VarTemplateSpecializationDecl *getMostRecentDecl() {
02320     VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
02321     return cast<VarTemplateSpecializationDecl>(Recent);
02322   }
02323 
02324   /// \brief Retrieve the template that this specialization specializes.
02325   VarTemplateDecl *getSpecializedTemplate() const;
02326 
02327   /// \brief Retrieve the template arguments of the variable template
02328   /// specialization.
02329   const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
02330 
02331   // TODO: Always set this when creating the new specialization?
02332   void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
02333 
02334   const TemplateArgumentListInfo &getTemplateArgsInfo() const {
02335     return TemplateArgsInfo;
02336   }
02337 
02338   /// \brief Determine the kind of specialization that this
02339   /// declaration represents.
02340   TemplateSpecializationKind getSpecializationKind() const {
02341     return static_cast<TemplateSpecializationKind>(SpecializationKind);
02342   }
02343 
02344   bool isExplicitSpecialization() const {
02345     return getSpecializationKind() == TSK_ExplicitSpecialization;
02346   }
02347 
02348   /// \brief True if this declaration is an explicit specialization,
02349   /// explicit instantiation declaration, or explicit instantiation
02350   /// definition.
02351   bool isExplicitInstantiationOrSpecialization() const {
02352     switch (getTemplateSpecializationKind()) {
02353     case TSK_ExplicitSpecialization:
02354     case TSK_ExplicitInstantiationDeclaration:
02355     case TSK_ExplicitInstantiationDefinition:
02356       return true;
02357 
02358     case TSK_Undeclared:
02359     case TSK_ImplicitInstantiation:
02360       return false;
02361     }
02362     llvm_unreachable("bad template specialization kind");
02363   }
02364 
02365   void setSpecializationKind(TemplateSpecializationKind TSK) {
02366     SpecializationKind = TSK;
02367   }
02368 
02369   /// \brief Get the point of instantiation (if any), or null if none.
02370   SourceLocation getPointOfInstantiation() const {
02371     return PointOfInstantiation;
02372   }
02373 
02374   void setPointOfInstantiation(SourceLocation Loc) {
02375     assert(Loc.isValid() && "point of instantiation must be valid!");
02376     PointOfInstantiation = Loc;
02377   }
02378 
02379   /// \brief If this variable template specialization is an instantiation of
02380   /// a template (rather than an explicit specialization), return the
02381   /// variable template or variable template partial specialization from which
02382   /// it was instantiated.
02383   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
02384   getInstantiatedFrom() const {
02385     if (getSpecializationKind() != TSK_ImplicitInstantiation &&
02386         getSpecializationKind() != TSK_ExplicitInstantiationDefinition &&
02387         getSpecializationKind() != TSK_ExplicitInstantiationDeclaration)
02388       return llvm::PointerUnion<VarTemplateDecl *,
02389                                 VarTemplatePartialSpecializationDecl *>();
02390 
02391     if (SpecializedPartialSpecialization *PartialSpec =
02392             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
02393       return PartialSpec->PartialSpecialization;
02394 
02395     return SpecializedTemplate.get<VarTemplateDecl *>();
02396   }
02397 
02398   /// \brief Retrieve the variable template or variable template partial
02399   /// specialization which was specialized by this.
02400   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
02401   getSpecializedTemplateOrPartial() const {
02402     if (SpecializedPartialSpecialization *PartialSpec =
02403             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
02404       return PartialSpec->PartialSpecialization;
02405 
02406     return SpecializedTemplate.get<VarTemplateDecl *>();
02407   }
02408 
02409   /// \brief Retrieve the set of template arguments that should be used
02410   /// to instantiate the initializer of the variable template or variable
02411   /// template partial specialization from which this variable template
02412   /// specialization was instantiated.
02413   ///
02414   /// \returns For a variable template specialization instantiated from the
02415   /// primary template, this function will return the same template arguments
02416   /// as getTemplateArgs(). For a variable template specialization instantiated
02417   /// from a variable template partial specialization, this function will the
02418   /// return deduced template arguments for the variable template partial
02419   /// specialization itself.
02420   const TemplateArgumentList &getTemplateInstantiationArgs() const {
02421     if (SpecializedPartialSpecialization *PartialSpec =
02422             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
02423       return *PartialSpec->TemplateArgs;
02424 
02425     return getTemplateArgs();
02426   }
02427 
02428   /// \brief Note that this variable template specialization is actually an
02429   /// instantiation of the given variable template partial specialization whose
02430   /// template arguments have been deduced.
02431   void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
02432                           const TemplateArgumentList *TemplateArgs) {
02433     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
02434            "Already set to a variable template partial specialization!");
02435     SpecializedPartialSpecialization *PS =
02436         new (getASTContext()) SpecializedPartialSpecialization();
02437     PS->PartialSpecialization = PartialSpec;
02438     PS->TemplateArgs = TemplateArgs;
02439     SpecializedTemplate = PS;
02440   }
02441 
02442   /// \brief Note that this variable template specialization is an instantiation
02443   /// of the given variable template.
02444   void setInstantiationOf(VarTemplateDecl *TemplDecl) {
02445     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
02446            "Previously set to a variable template partial specialization!");
02447     SpecializedTemplate = TemplDecl;
02448   }
02449 
02450   /// \brief Sets the type of this specialization as it was written by
02451   /// the user.
02452   void setTypeAsWritten(TypeSourceInfo *T) {
02453     if (!ExplicitInfo)
02454       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
02455     ExplicitInfo->TypeAsWritten = T;
02456   }
02457   /// \brief Gets the type of this specialization as it was written by
02458   /// the user, if it was so written.
02459   TypeSourceInfo *getTypeAsWritten() const {
02460     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
02461   }
02462 
02463   /// \brief Gets the location of the extern keyword, if present.
02464   SourceLocation getExternLoc() const {
02465     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
02466   }
02467   /// \brief Sets the location of the extern keyword.
02468   void setExternLoc(SourceLocation Loc) {
02469     if (!ExplicitInfo)
02470       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
02471     ExplicitInfo->ExternLoc = Loc;
02472   }
02473 
02474   /// \brief Sets the location of the template keyword.
02475   void setTemplateKeywordLoc(SourceLocation Loc) {
02476     if (!ExplicitInfo)
02477       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
02478     ExplicitInfo->TemplateKeywordLoc = Loc;
02479   }
02480   /// \brief Gets the location of the template keyword, if present.
02481   SourceLocation getTemplateKeywordLoc() const {
02482     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
02483   }
02484 
02485   void Profile(llvm::FoldingSetNodeID &ID) const {
02486     Profile(ID, TemplateArgs->asArray(), getASTContext());
02487   }
02488 
02489   static void Profile(llvm::FoldingSetNodeID &ID,
02490                       ArrayRef<TemplateArgument> TemplateArgs,
02491                       ASTContext &Context) {
02492     ID.AddInteger(TemplateArgs.size());
02493     for (unsigned Arg = 0; Arg != TemplateArgs.size(); ++Arg)
02494       TemplateArgs[Arg].Profile(ID, Context);
02495   }
02496 
02497   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
02498   static bool classofKind(Kind K) {
02499     return K >= firstVarTemplateSpecialization &&
02500            K <= lastVarTemplateSpecialization;
02501   }
02502 
02503   friend class ASTDeclReader;
02504   friend class ASTDeclWriter;
02505 };
02506 
02507 class VarTemplatePartialSpecializationDecl
02508     : public VarTemplateSpecializationDecl {
02509   void anchor() override;
02510 
02511   /// \brief The list of template parameters
02512   TemplateParameterList *TemplateParams;
02513 
02514   /// \brief The source info for the template arguments as written.
02515   /// FIXME: redundant with TypeAsWritten?
02516   const ASTTemplateArgumentListInfo *ArgsAsWritten;
02517 
02518   /// \brief The variable template partial specialization from which this
02519   /// variable template partial specialization was instantiated.
02520   ///
02521   /// The boolean value will be true to indicate that this variable template
02522   /// partial specialization was specialized at this level.
02523   llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
02524   InstantiatedFromMember;
02525 
02526   VarTemplatePartialSpecializationDecl(
02527       ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
02528       SourceLocation IdLoc, TemplateParameterList *Params,
02529       VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
02530       StorageClass S, const TemplateArgument *Args, unsigned NumArgs,
02531       const ASTTemplateArgumentListInfo *ArgInfos);
02532 
02533   VarTemplatePartialSpecializationDecl(ASTContext &Context)
02534     : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization, Context),
02535       TemplateParams(nullptr), ArgsAsWritten(nullptr),
02536       InstantiatedFromMember(nullptr, false) {}
02537 
02538 public:
02539   static VarTemplatePartialSpecializationDecl *
02540   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
02541          SourceLocation IdLoc, TemplateParameterList *Params,
02542          VarTemplateDecl *SpecializedTemplate, QualType T,
02543          TypeSourceInfo *TInfo, StorageClass S, const TemplateArgument *Args,
02544          unsigned NumArgs, const TemplateArgumentListInfo &ArgInfos);
02545 
02546   static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
02547                                                                   unsigned ID);
02548 
02549   VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
02550     return cast<VarTemplatePartialSpecializationDecl>(
02551              static_cast<VarTemplateSpecializationDecl *>(
02552                this)->getMostRecentDecl());
02553   }
02554 
02555   /// Get the list of template parameters
02556   TemplateParameterList *getTemplateParameters() const {
02557     return TemplateParams;
02558   }
02559 
02560   /// Get the template arguments as written.
02561   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
02562     return ArgsAsWritten;
02563   }
02564 
02565   /// \brief Retrieve the member variable template partial specialization from
02566   /// which this particular variable template partial specialization was
02567   /// instantiated.
02568   ///
02569   /// \code
02570   /// template<typename T>
02571   /// struct Outer {
02572   ///   template<typename U> U Inner;
02573   ///   template<typename U> U* Inner<U*> = (U*)(0); // #1
02574   /// };
02575   ///
02576   /// template int* Outer<float>::Inner<int*>;
02577   /// \endcode
02578   ///
02579   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
02580   /// end up instantiating the partial specialization
02581   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
02582   /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
02583   /// \c Outer<float>::Inner<U*>, this function would return
02584   /// \c Outer<T>::Inner<U*>.
02585   VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() {
02586     VarTemplatePartialSpecializationDecl *First =
02587         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
02588     return First->InstantiatedFromMember.getPointer();
02589   }
02590 
02591   void
02592   setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
02593     VarTemplatePartialSpecializationDecl *First =
02594         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
02595     First->InstantiatedFromMember.setPointer(PartialSpec);
02596   }
02597 
02598   /// \brief Determines whether this variable template partial specialization
02599   /// was a specialization of a member partial specialization.
02600   ///
02601   /// In the following example, the member template partial specialization
02602   /// \c X<int>::Inner<T*> is a member specialization.
02603   ///
02604   /// \code
02605   /// template<typename T>
02606   /// struct X {
02607   ///   template<typename U> U Inner;
02608   ///   template<typename U> U* Inner<U*> = (U*)(0);
02609   /// };
02610   ///
02611   /// template<> template<typename T>
02612   /// U* X<int>::Inner<T*> = (T*)(0) + 1;
02613   /// \endcode
02614   bool isMemberSpecialization() {
02615     VarTemplatePartialSpecializationDecl *First =
02616         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
02617     return First->InstantiatedFromMember.getInt();
02618   }
02619 
02620   /// \brief Note that this member template is a specialization.
02621   void setMemberSpecialization() {
02622     VarTemplatePartialSpecializationDecl *First =
02623         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
02624     assert(First->InstantiatedFromMember.getPointer() &&
02625            "Only member templates can be member template specializations");
02626     return First->InstantiatedFromMember.setInt(true);
02627   }
02628 
02629   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
02630   static bool classofKind(Kind K) {
02631     return K == VarTemplatePartialSpecialization;
02632   }
02633 
02634   friend class ASTDeclReader;
02635   friend class ASTDeclWriter;
02636 };
02637 
02638 /// Declaration of a variable template.
02639 class VarTemplateDecl : public RedeclarableTemplateDecl {
02640   static void DeallocateCommon(void *Ptr);
02641 
02642 protected:
02643   /// \brief Data that is common to all of the declarations of a given
02644   /// variable template.
02645   struct Common : CommonBase {
02646     Common() : LazySpecializations() {}
02647 
02648     /// \brief The variable template specializations for this variable
02649     /// template, including explicit specializations and instantiations.
02650     llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
02651 
02652     /// \brief The variable template partial specializations for this variable
02653     /// template.
02654     llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
02655     PartialSpecializations;
02656 
02657     /// \brief If non-null, points to an array of specializations (including
02658     /// partial specializations) known ownly by their external declaration IDs.
02659     ///
02660     /// The first value in the array is the number of of specializations/
02661     /// partial specializations that follow.
02662     uint32_t *LazySpecializations;
02663   };
02664 
02665   /// \brief Load any lazily-loaded specializations from the external source.
02666   void LoadLazySpecializations() const;
02667 
02668   /// \brief Retrieve the set of specializations of this variable template.
02669   llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
02670   getSpecializations() const;
02671 
02672   /// \brief Retrieve the set of partial specializations of this class
02673   /// template.
02674   llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
02675   getPartialSpecializations();
02676 
02677   VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
02678                   DeclarationName Name, TemplateParameterList *Params,
02679                   NamedDecl *Decl)
02680       : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
02681 
02682   CommonBase *newCommon(ASTContext &C) const override;
02683 
02684   Common *getCommonPtr() const {
02685     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
02686   }
02687 
02688 public:
02689   /// \brief Get the underlying variable declarations of the template.
02690   VarDecl *getTemplatedDecl() const {
02691     return static_cast<VarDecl *>(TemplatedDecl);
02692   }
02693 
02694   /// \brief Returns whether this template declaration defines the primary
02695   /// variable pattern.
02696   bool isThisDeclarationADefinition() const {
02697     return getTemplatedDecl()->isThisDeclarationADefinition();
02698   }
02699 
02700   VarTemplateDecl *getDefinition();
02701 
02702   /// \brief Create a variable template node.
02703   static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
02704                                  SourceLocation L, DeclarationName Name,
02705                                  TemplateParameterList *Params,
02706                                  VarDecl *Decl);
02707 
02708   /// \brief Create an empty variable template node.
02709   static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
02710 
02711   /// \brief Return the specialization with the provided arguments if it exists,
02712   /// otherwise return the insertion point.
02713   VarTemplateSpecializationDecl *
02714   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
02715 
02716   /// \brief Insert the specified specialization knowing that it is not already
02717   /// in. InsertPos must be obtained from findSpecialization.
02718   void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
02719 
02720   VarTemplateDecl *getCanonicalDecl() override {
02721     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
02722   }
02723   const VarTemplateDecl *getCanonicalDecl() const {
02724     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
02725   }
02726 
02727   /// \brief Retrieve the previous declaration of this variable template, or
02728   /// NULL if no such declaration exists.
02729   VarTemplateDecl *getPreviousDecl() {
02730     return cast_or_null<VarTemplateDecl>(
02731         static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
02732   }
02733 
02734   /// \brief Retrieve the previous declaration of this variable template, or
02735   /// NULL if no such declaration exists.
02736   const VarTemplateDecl *getPreviousDecl() const {
02737     return cast_or_null<VarTemplateDecl>(
02738             static_cast<const RedeclarableTemplateDecl *>(
02739               this)->getPreviousDecl());
02740   }
02741 
02742   VarTemplateDecl *getInstantiatedFromMemberTemplate() {
02743     return cast_or_null<VarTemplateDecl>(
02744         RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
02745   }
02746 
02747   /// \brief Return the partial specialization with the provided arguments if it
02748   /// exists, otherwise return the insertion point.
02749   VarTemplatePartialSpecializationDecl *
02750   findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
02751 
02752   /// \brief Insert the specified partial specialization knowing that it is not
02753   /// already in. InsertPos must be obtained from findPartialSpecialization.
02754   void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
02755                                 void *InsertPos);
02756 
02757   /// \brief Retrieve the partial specializations as an ordered list.
02758   void getPartialSpecializations(
02759       SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
02760 
02761   /// \brief Find a variable template partial specialization which was
02762   /// instantiated
02763   /// from the given member partial specialization.
02764   ///
02765   /// \param D a member variable template partial specialization.
02766   ///
02767   /// \returns the variable template partial specialization which was
02768   /// instantiated
02769   /// from the given member partial specialization, or NULL if no such partial
02770   /// specialization exists.
02771   VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
02772       VarTemplatePartialSpecializationDecl *D);
02773 
02774   typedef SpecIterator<VarTemplateSpecializationDecl> spec_iterator;
02775   typedef llvm::iterator_range<spec_iterator> spec_range;
02776 
02777   spec_range specializations() const {
02778     return spec_range(spec_begin(), spec_end());
02779   }
02780 
02781   spec_iterator spec_begin() const {
02782     return makeSpecIterator(getSpecializations(), false);
02783   }
02784 
02785   spec_iterator spec_end() const {
02786     return makeSpecIterator(getSpecializations(), true);
02787   }
02788 
02789   // Implement isa/cast/dyncast support
02790   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
02791   static bool classofKind(Kind K) { return K == VarTemplate; }
02792 
02793   friend class ASTDeclReader;
02794   friend class ASTDeclWriter;
02795 };
02796 
02797 } /* end of namespace clang */
02798 
02799 #endif