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