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