DeclTemplate.h revision f785a7d611404cf4747287a2bbc59b4d0e6a5a8c
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
490protected:
491  template <typename EntryType> struct SpecEntryTraits {
492    typedef EntryType DeclType;
493
494    static DeclType *getMostRecentDeclaration(EntryType *D) {
495      return D->getMostRecentDeclaration();
496    }
497  };
498
499  template <typename EntryType,
500            typename _SETraits = SpecEntryTraits<EntryType>,
501            typename _DeclType = typename _SETraits::DeclType>
502  class SpecIterator : public std::iterator<std::forward_iterator_tag,
503                                            _DeclType*, ptrdiff_t,
504                                            _DeclType*, _DeclType*> {
505    typedef _SETraits SETraits;
506    typedef _DeclType DeclType;
507
508    typedef typename llvm::FoldingSet<EntryType>::iterator SetIteratorType;
509
510    SetIteratorType SetIter;
511
512  public:
513    SpecIterator() : SetIter() {}
514    SpecIterator(SetIteratorType SetIter) : SetIter(SetIter) {}
515
516    DeclType *operator*() const {
517      return SETraits::getMostRecentDeclaration(&*SetIter);
518    }
519    DeclType *operator->() const { return **this; }
520
521    SpecIterator &operator++() { ++SetIter; return *this; }
522    SpecIterator operator++(int) {
523      SpecIterator tmp(*this);
524      ++(*this);
525      return tmp;
526    }
527
528    bool operator==(SpecIterator Other) const {
529      return SetIter == Other.SetIter;
530    }
531    bool operator!=(SpecIterator Other) const {
532      return SetIter != Other.SetIter;
533    }
534  };
535
536  template <typename EntryType>
537  SpecIterator<EntryType> makeSpecIterator(llvm::FoldingSet<EntryType> &Specs,
538                                           bool isEnd) {
539    return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
540  }
541
542  template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
543  findSpecializationImpl(llvm::FoldingSet<EntryType> &Specs,
544                         const TemplateArgument *Args, unsigned NumArgs,
545                         void *&InsertPos);
546
547  struct CommonBase {
548    CommonBase() : InstantiatedFromMember(0, false) { }
549
550    /// \brief The template from which this was most
551    /// directly instantiated (or null).
552    ///
553    /// The boolean value indicates whether this template
554    /// was explicitly specialized.
555    llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
556      InstantiatedFromMember;
557  };
558
559  /// \brief Pointer to the common data shared by all declarations of this
560  /// template.
561  CommonBase *Common;
562
563  /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
564  /// the same template. Calling this routine may implicitly allocate memory
565  /// for the common pointer.
566  CommonBase *getCommonPtr();
567
568  virtual CommonBase *newCommon(ASTContext &C) = 0;
569
570  // Construct a template decl with name, parameters, and templated element.
571  RedeclarableTemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
572                           DeclarationName Name, TemplateParameterList *Params,
573                           NamedDecl *Decl)
574    : TemplateDecl(DK, DC, L, Name, Params, Decl), Common() { }
575
576public:
577  template <class decl_type> friend class RedeclarableTemplate;
578
579  /// Retrieves the canonical declaration of this template.
580  RedeclarableTemplateDecl *getCanonicalDecl() { return getFirstDeclaration(); }
581  const RedeclarableTemplateDecl *getCanonicalDecl() const {
582    return getFirstDeclaration();
583  }
584
585  /// \brief Determines whether this template was a specialization of a
586  /// member template.
587  ///
588  /// In the following example, the function template \c X<int>::f and the
589  /// member template \c X<int>::Inner are member specializations.
590  ///
591  /// \code
592  /// template<typename T>
593  /// struct X {
594  ///   template<typename U> void f(T, U);
595  ///   template<typename U> struct Inner;
596  /// };
597  ///
598  /// template<> template<typename T>
599  /// void X<int>::f(int, T);
600  /// template<> template<typename T>
601  /// struct X<int>::Inner { /* ... */ };
602  /// \endcode
603  bool isMemberSpecialization() {
604    return getCommonPtr()->InstantiatedFromMember.getInt();
605  }
606
607  /// \brief Note that this member template is a specialization.
608  void setMemberSpecialization() {
609    assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
610           "Only member templates can be member template specializations");
611    getCommonPtr()->InstantiatedFromMember.setInt(true);
612  }
613
614  /// \brief Retrieve the previous declaration of this template, or
615  /// NULL if no such declaration exists.
616  RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() {
617    return getCommonPtr()->InstantiatedFromMember.getPointer();
618  }
619
620  void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
621    assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
622    getCommonPtr()->InstantiatedFromMember.setPointer(TD);
623  }
624
625  typedef redeclarable_base::redecl_iterator redecl_iterator;
626  redecl_iterator redecls_begin() const {
627    return redeclarable_base::redecls_begin();
628  }
629  redecl_iterator redecls_end() const {
630    return redeclarable_base::redecls_end();
631  }
632
633  virtual RedeclarableTemplateDecl *getPreviousDecl() {
634    return redeclarable_base::getPreviousDeclaration();
635  }
636
637  virtual RedeclarableTemplateDecl *getMostRecentDecl() {
638    return redeclarable_base::getMostRecentDeclaration();
639  }
640
641  // Implement isa/cast/dyncast/etc.
642  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
643  static bool classof(const RedeclarableTemplateDecl *D) { return true; }
644  static bool classof(const FunctionTemplateDecl *D) { return true; }
645  static bool classof(const ClassTemplateDecl *D) { return true; }
646  static bool classof(const TypeAliasTemplateDecl *D) { return true; }
647  static bool classofKind(Kind K) {
648    return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
649  }
650
651  friend class ASTReader;
652  friend class ASTDeclReader;
653  friend class ASTDeclWriter;
654};
655
656template <> struct RedeclarableTemplateDecl::
657SpecEntryTraits<FunctionTemplateSpecializationInfo> {
658  typedef FunctionDecl DeclType;
659
660  static DeclType *
661  getMostRecentDeclaration(FunctionTemplateSpecializationInfo *I) {
662    return I->Function->getMostRecentDeclaration();
663  }
664};
665
666/// Declaration of a template function.
667class FunctionTemplateDecl : public RedeclarableTemplateDecl {
668  static void DeallocateCommon(void *Ptr);
669
670protected:
671  /// \brief Data that is common to all of the declarations of a given
672  /// function template.
673  struct Common : CommonBase {
674    Common() : InjectedArgs(0) { }
675
676    /// \brief The function template specializations for this function
677    /// template, including explicit specializations and instantiations.
678    llvm::FoldingSet<FunctionTemplateSpecializationInfo> Specializations;
679
680    /// \brief The set of "injected" template arguments used within this
681    /// function template.
682    ///
683    /// This pointer refers to the template arguments (there are as
684    /// many template arguments as template parameaters) for the function
685    /// template, and is allocated lazily, since most function templates do not
686    /// require the use of this information.
687    TemplateArgument *InjectedArgs;
688  };
689
690  FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
691                       TemplateParameterList *Params, NamedDecl *Decl)
692    : RedeclarableTemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl) { }
693
694  CommonBase *newCommon(ASTContext &C);
695
696  Common *getCommonPtr() {
697    return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
698  }
699
700  friend class FunctionDecl;
701
702  /// \brief Retrieve the set of function template specializations of this
703  /// function template.
704  llvm::FoldingSet<FunctionTemplateSpecializationInfo> &getSpecializations() {
705    return getCommonPtr()->Specializations;
706  }
707
708  /// \brief Add a specialization of this function template.
709  ///
710  /// \param InsertPos Insert position in the FoldingSet, must have been
711  ///        retrieved by an earlier call to findSpecialization().
712  void addSpecialization(FunctionTemplateSpecializationInfo* Info,
713                         void *InsertPos);
714
715public:
716  /// Get the underlying function declaration of the template.
717  FunctionDecl *getTemplatedDecl() const {
718    return static_cast<FunctionDecl*>(TemplatedDecl);
719  }
720
721  /// Returns whether this template declaration defines the primary
722  /// pattern.
723  bool isThisDeclarationADefinition() const {
724    return getTemplatedDecl()->isThisDeclarationADefinition();
725  }
726
727  /// \brief Return the specialization with the provided arguments if it exists,
728  /// otherwise return the insertion point.
729  FunctionDecl *findSpecialization(const TemplateArgument *Args,
730                                   unsigned NumArgs, void *&InsertPos);
731
732  FunctionTemplateDecl *getCanonicalDecl() {
733    return cast<FunctionTemplateDecl>(
734             RedeclarableTemplateDecl::getCanonicalDecl());
735  }
736  const FunctionTemplateDecl *getCanonicalDecl() const {
737    return cast<FunctionTemplateDecl>(
738             RedeclarableTemplateDecl::getCanonicalDecl());
739  }
740
741  /// \brief Retrieve the previous declaration of this function template, or
742  /// NULL if no such declaration exists.
743  FunctionTemplateDecl *getPreviousDeclaration() {
744    return cast_or_null<FunctionTemplateDecl>(
745             RedeclarableTemplateDecl::getPreviousDeclaration());
746  }
747
748  /// \brief Retrieve the previous declaration of this function template, or
749  /// NULL if no such declaration exists.
750  const FunctionTemplateDecl *getPreviousDeclaration() const {
751    return cast_or_null<FunctionTemplateDecl>(
752             RedeclarableTemplateDecl::getPreviousDeclaration());
753  }
754
755  FunctionTemplateDecl *getInstantiatedFromMemberTemplate() {
756    return cast_or_null<FunctionTemplateDecl>(
757             RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
758  }
759
760  typedef SpecIterator<FunctionTemplateSpecializationInfo> spec_iterator;
761
762  spec_iterator spec_begin() {
763    return makeSpecIterator(getSpecializations(), false);
764  }
765
766  spec_iterator spec_end() {
767    return makeSpecIterator(getSpecializations(), true);
768  }
769
770  /// \brief Retrieve the "injected" template arguments that correspond to the
771  /// template parameters of this function template.
772  ///
773  /// Although the C++ standard has no notion of the "injected" template
774  /// arguments for a function template, the notion is convenient when
775  /// we need to perform substitutions inside the definition of a function
776  /// template.
777  std::pair<const TemplateArgument *, unsigned> getInjectedTemplateArgs();
778
779  /// \brief Create a function template node.
780  static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
781                                      SourceLocation L,
782                                      DeclarationName Name,
783                                      TemplateParameterList *Params,
784                                      NamedDecl *Decl);
785
786  /// \brief Create an empty function template node.
787  static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
788
789  // Implement isa/cast/dyncast support
790  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
791  static bool classof(const FunctionTemplateDecl *D) { return true; }
792  static bool classofKind(Kind K) { return K == FunctionTemplate; }
793
794  friend class ASTDeclReader;
795  friend class ASTDeclWriter;
796};
797
798//===----------------------------------------------------------------------===//
799// Kinds of Template Parameters
800//===----------------------------------------------------------------------===//
801
802/// The TemplateParmPosition class defines the position of a template parameter
803/// within a template parameter list. Because template parameter can be listed
804/// sequentially for out-of-line template members, each template parameter is
805/// given a Depth - the nesting of template parameter scopes - and a Position -
806/// the occurrence within the parameter list.
807/// This class is inheritedly privately by different kinds of template
808/// parameters and is not part of the Decl hierarchy. Just a facility.
809class TemplateParmPosition {
810protected:
811  // FIXME: This should probably never be called, but it's here as
812  TemplateParmPosition()
813    : Depth(0), Position(0)
814  { /* llvm_unreachable("Cannot create positionless template parameter"); */ }
815
816  TemplateParmPosition(unsigned D, unsigned P)
817    : Depth(D), Position(P)
818  { }
819
820  // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
821  // position? Maybe?
822  unsigned Depth;
823  unsigned Position;
824
825public:
826  /// Get the nesting depth of the template parameter.
827  unsigned getDepth() const { return Depth; }
828  void setDepth(unsigned D) { Depth = D; }
829
830  /// Get the position of the template parameter within its parameter list.
831  unsigned getPosition() const { return Position; }
832  void setPosition(unsigned P) { Position = P; }
833
834  /// Get the index of the template parameter within its parameter list.
835  unsigned getIndex() const { return Position; }
836};
837
838/// TemplateTypeParmDecl - Declaration of a template type parameter,
839/// e.g., "T" in
840/// @code
841/// template<typename T> class vector;
842/// @endcode
843class TemplateTypeParmDecl : public TypeDecl {
844  /// \brief Whether this template type parameter was declaration with
845  /// the 'typename' keyword. If false, it was declared with the
846  /// 'class' keyword.
847  bool Typename : 1;
848
849  /// \brief Whether this template type parameter inherited its
850  /// default argument.
851  bool InheritedDefault : 1;
852
853  /// \brief The default template argument, if any.
854  TypeSourceInfo *DefaultArgument;
855
856  TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
857                       SourceLocation IdLoc, IdentifierInfo *Id,
858                       bool Typename)
859    : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
860      InheritedDefault(false), DefaultArgument() { }
861
862  /// Sema creates these on the stack during auto type deduction.
863  friend class Sema;
864
865public:
866  static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
867                                      SourceLocation KeyLoc,
868                                      SourceLocation NameLoc,
869                                      unsigned D, unsigned P,
870                                      IdentifierInfo *Id, bool Typename,
871                                      bool ParameterPack);
872  static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
873                                                  unsigned ID);
874
875  /// \brief Whether this template type parameter was declared with
876  /// the 'typename' keyword. If not, it was declared with the 'class'
877  /// keyword.
878  bool wasDeclaredWithTypename() const { return Typename; }
879
880  /// \brief Determine whether this template parameter has a default
881  /// argument.
882  bool hasDefaultArgument() const { return DefaultArgument != 0; }
883
884  /// \brief Retrieve the default argument, if any.
885  QualType getDefaultArgument() const { return DefaultArgument->getType(); }
886
887  /// \brief Retrieves the default argument's source information, if any.
888  TypeSourceInfo *getDefaultArgumentInfo() const { return DefaultArgument; }
889
890  /// \brief Retrieves the location of the default argument declaration.
891  SourceLocation getDefaultArgumentLoc() const;
892
893  /// \brief Determines whether the default argument was inherited
894  /// from a previous declaration of this template.
895  bool defaultArgumentWasInherited() const { return InheritedDefault; }
896
897  /// \brief Set the default argument for this template parameter, and
898  /// whether that default argument was inherited from another
899  /// declaration.
900  void setDefaultArgument(TypeSourceInfo *DefArg, bool Inherited) {
901    DefaultArgument = DefArg;
902    InheritedDefault = Inherited;
903  }
904
905  /// \brief Removes the default argument of this template parameter.
906  void removeDefaultArgument() {
907    DefaultArgument = 0;
908    InheritedDefault = false;
909  }
910
911  /// \brief Set whether this template type parameter was declared with
912  /// the 'typename' or 'class' keyword.
913  void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
914
915  /// \brief Retrieve the depth of the template parameter.
916  unsigned getDepth() const;
917
918  /// \brief Retrieve the index of the template parameter.
919  unsigned getIndex() const;
920
921  /// \brief Returns whether this is a parameter pack.
922  bool isParameterPack() const;
923
924  SourceRange getSourceRange() const;
925
926  // Implement isa/cast/dyncast/etc.
927  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
928  static bool classof(const TemplateTypeParmDecl *D) { return true; }
929  static bool classofKind(Kind K) { return K == TemplateTypeParm; }
930};
931
932/// NonTypeTemplateParmDecl - Declares a non-type template parameter,
933/// e.g., "Size" in
934/// @code
935/// template<int Size> class array { };
936/// @endcode
937class NonTypeTemplateParmDecl
938  : public DeclaratorDecl, protected TemplateParmPosition {
939  /// \brief The default template argument, if any, and whether or not
940  /// it was inherited.
941  llvm::PointerIntPair<Expr*, 1, bool> DefaultArgumentAndInherited;
942
943  // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
944  // down here to save memory.
945
946  /// \brief Whether this non-type template parameter is a parameter pack.
947  bool ParameterPack;
948
949  /// \brief Whether this non-type template parameter is an "expanded"
950  /// parameter pack, meaning that its type is a pack expansion and we
951  /// already know the set of types that expansion expands to.
952  bool ExpandedParameterPack;
953
954  /// \brief The number of types in an expanded parameter pack.
955  unsigned NumExpandedTypes;
956
957  NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
958                          SourceLocation IdLoc, unsigned D, unsigned P,
959                          IdentifierInfo *Id, QualType T,
960                          bool ParameterPack, TypeSourceInfo *TInfo)
961    : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
962      TemplateParmPosition(D, P), DefaultArgumentAndInherited(0, false),
963      ParameterPack(ParameterPack), ExpandedParameterPack(false),
964      NumExpandedTypes(0)
965  { }
966
967  NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
968                          SourceLocation IdLoc, unsigned D, unsigned P,
969                          IdentifierInfo *Id, QualType T,
970                          TypeSourceInfo *TInfo,
971                          const QualType *ExpandedTypes,
972                          unsigned NumExpandedTypes,
973                          TypeSourceInfo **ExpandedTInfos);
974
975  friend class ASTDeclReader;
976
977public:
978  static NonTypeTemplateParmDecl *
979  Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
980         SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
981         QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
982
983  static NonTypeTemplateParmDecl *
984  Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
985         SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
986         QualType T, TypeSourceInfo *TInfo,
987         const QualType *ExpandedTypes, unsigned NumExpandedTypes,
988         TypeSourceInfo **ExpandedTInfos);
989
990  static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
991                                                     unsigned ID);
992  static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
993                                                     unsigned ID,
994                                                     unsigned NumExpandedTypes);
995
996  using TemplateParmPosition::getDepth;
997  using TemplateParmPosition::setDepth;
998  using TemplateParmPosition::getPosition;
999  using TemplateParmPosition::setPosition;
1000  using TemplateParmPosition::getIndex;
1001
1002  SourceRange getSourceRange() const;
1003
1004  /// \brief Determine whether this template parameter has a default
1005  /// argument.
1006  bool hasDefaultArgument() const {
1007    return DefaultArgumentAndInherited.getPointer() != 0;
1008  }
1009
1010  /// \brief Retrieve the default argument, if any.
1011  Expr *getDefaultArgument() const {
1012    return DefaultArgumentAndInherited.getPointer();
1013  }
1014
1015  /// \brief Retrieve the location of the default argument, if any.
1016  SourceLocation getDefaultArgumentLoc() const;
1017
1018  /// \brief Determines whether the default argument was inherited
1019  /// from a previous declaration of this template.
1020  bool defaultArgumentWasInherited() const {
1021    return DefaultArgumentAndInherited.getInt();
1022  }
1023
1024  /// \brief Set the default argument for this template parameter, and
1025  /// whether that default argument was inherited from another
1026  /// declaration.
1027  void setDefaultArgument(Expr *DefArg, bool Inherited) {
1028    DefaultArgumentAndInherited.setPointer(DefArg);
1029    DefaultArgumentAndInherited.setInt(Inherited);
1030  }
1031
1032  /// \brief Removes the default argument of this template parameter.
1033  void removeDefaultArgument() {
1034    DefaultArgumentAndInherited.setPointer(0);
1035    DefaultArgumentAndInherited.setInt(false);
1036  }
1037
1038  /// \brief Whether this parameter is a non-type template parameter pack.
1039  ///
1040  /// If the parameter is a parameter pack, the type may be a
1041  /// \c PackExpansionType. In the following example, the \c Dims parameter
1042  /// is a parameter pack (whose type is 'unsigned').
1043  ///
1044  /// \code
1045  /// template<typename T, unsigned ...Dims> struct multi_array;
1046  /// \endcode
1047  bool isParameterPack() const { return ParameterPack; }
1048
1049  /// \brief Whether this parameter is a non-type template parameter pack
1050  /// that has different types at different positions.
1051  ///
1052  /// A parameter pack is an expanded parameter pack when the original
1053  /// parameter pack's type was itself a pack expansion, and that expansion
1054  /// has already been expanded. For example, given:
1055  ///
1056  /// \code
1057  /// template<typename ...Types>
1058  /// struct X {
1059  ///   template<Types ...Values>
1060  ///   struct Y { /* ... */ };
1061  /// };
1062  /// \endcode
1063  ///
1064  /// The parameter pack \c Values has a \c PackExpansionType as its type,
1065  /// which expands \c Types. When \c Types is supplied with template arguments
1066  /// by instantiating \c X, the instantiation of \c Values becomes an
1067  /// expanded parameter pack. For example, instantiating
1068  /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1069  /// pack with expansion types \c int and \c unsigned int.
1070  ///
1071  /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1072  /// return the expansion types.
1073  bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1074
1075  /// \brief Retrieves the number of expansion types in an expanded parameter
1076  /// pack.
1077  unsigned getNumExpansionTypes() const {
1078    assert(ExpandedParameterPack && "Not an expansion parameter pack");
1079    return NumExpandedTypes;
1080  }
1081
1082  /// \brief Retrieve a particular expansion type within an expanded parameter
1083  /// pack.
1084  QualType getExpansionType(unsigned I) const {
1085    assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1086    void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
1087    return QualType::getFromOpaquePtr(TypesAndInfos[2*I]);
1088  }
1089
1090  /// \brief Retrieve a particular expansion type source info within an
1091  /// expanded parameter pack.
1092  TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1093    assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1094    void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
1095    return static_cast<TypeSourceInfo *>(TypesAndInfos[2*I+1]);
1096  }
1097
1098  // Implement isa/cast/dyncast/etc.
1099  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1100  static bool classof(const NonTypeTemplateParmDecl *D) { return true; }
1101  static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1102};
1103
1104/// TemplateTemplateParmDecl - Declares a template template parameter,
1105/// e.g., "T" in
1106/// @code
1107/// template <template <typename> class T> class container { };
1108/// @endcode
1109/// A template template parameter is a TemplateDecl because it defines the
1110/// name of a template and the template parameters allowable for substitution.
1111class TemplateTemplateParmDecl : public TemplateDecl,
1112                                 protected TemplateParmPosition
1113{
1114  virtual void anchor();
1115
1116  /// DefaultArgument - The default template argument, if any.
1117  TemplateArgumentLoc DefaultArgument;
1118  /// Whether or not the default argument was inherited.
1119  bool DefaultArgumentWasInherited;
1120
1121  /// \brief Whether this parameter is a parameter pack.
1122  bool ParameterPack;
1123
1124  TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1125                           unsigned D, unsigned P, bool ParameterPack,
1126                           IdentifierInfo *Id, TemplateParameterList *Params)
1127    : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1128      TemplateParmPosition(D, P), DefaultArgument(),
1129      DefaultArgumentWasInherited(false), ParameterPack(ParameterPack)
1130    { }
1131
1132public:
1133  static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1134                                          SourceLocation L, unsigned D,
1135                                          unsigned P, bool ParameterPack,
1136                                          IdentifierInfo *Id,
1137                                          TemplateParameterList *Params);
1138
1139  static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1140                                                      unsigned ID);
1141
1142  using TemplateParmPosition::getDepth;
1143  using TemplateParmPosition::getPosition;
1144  using TemplateParmPosition::getIndex;
1145
1146  /// \brief Whether this template template parameter is a template
1147  /// parameter pack.
1148  ///
1149  /// \code
1150  /// template<template <class T> ...MetaFunctions> struct Apply;
1151  /// \endcode
1152  bool isParameterPack() const { return ParameterPack; }
1153
1154  /// \brief Determine whether this template parameter has a default
1155  /// argument.
1156  bool hasDefaultArgument() const {
1157    return !DefaultArgument.getArgument().isNull();
1158  }
1159
1160  /// \brief Retrieve the default argument, if any.
1161  const TemplateArgumentLoc &getDefaultArgument() const {
1162    return DefaultArgument;
1163  }
1164
1165  /// \brief Retrieve the location of the default argument, if any.
1166  SourceLocation getDefaultArgumentLoc() const;
1167
1168  /// \brief Determines whether the default argument was inherited
1169  /// from a previous declaration of this template.
1170  bool defaultArgumentWasInherited() const {
1171    return DefaultArgumentWasInherited;
1172  }
1173
1174  /// \brief Set the default argument for this template parameter, and
1175  /// whether that default argument was inherited from another
1176  /// declaration.
1177  void setDefaultArgument(const TemplateArgumentLoc &DefArg, bool Inherited) {
1178    DefaultArgument = DefArg;
1179    DefaultArgumentWasInherited = Inherited;
1180  }
1181
1182  /// \brief Removes the default argument of this template parameter.
1183  void removeDefaultArgument() {
1184    DefaultArgument = TemplateArgumentLoc();
1185    DefaultArgumentWasInherited = false;
1186  }
1187
1188  SourceRange getSourceRange() const {
1189    SourceLocation End = getLocation();
1190    if (hasDefaultArgument() && !defaultArgumentWasInherited())
1191      End = getDefaultArgument().getSourceRange().getEnd();
1192    return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1193  }
1194
1195  // Implement isa/cast/dyncast/etc.
1196  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1197  static bool classof(const TemplateTemplateParmDecl *D) { return true; }
1198  static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1199
1200  friend class ASTDeclReader;
1201  friend class ASTDeclWriter;
1202};
1203
1204/// \brief Represents a class template specialization, which refers to
1205/// a class template with a given set of template arguments.
1206///
1207/// Class template specializations represent both explicit
1208/// specialization of class templates, as in the example below, and
1209/// implicit instantiations of class templates.
1210///
1211/// \code
1212/// template<typename T> class array;
1213///
1214/// template<>
1215/// class array<bool> { }; // class template specialization array<bool>
1216/// \endcode
1217class ClassTemplateSpecializationDecl
1218  : public CXXRecordDecl, public llvm::FoldingSetNode {
1219
1220  /// \brief Structure that stores information about a class template
1221  /// specialization that was instantiated from a class template partial
1222  /// specialization.
1223  struct SpecializedPartialSpecialization {
1224    /// \brief The class template partial specialization from which this
1225    /// class template specialization was instantiated.
1226    ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1227
1228    /// \brief The template argument list deduced for the class template
1229    /// partial specialization itself.
1230    TemplateArgumentList *TemplateArgs;
1231  };
1232
1233  /// \brief The template that this specialization specializes
1234  llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1235    SpecializedTemplate;
1236
1237  /// \brief Further info for explicit template specialization/instantiation.
1238  struct ExplicitSpecializationInfo {
1239    /// \brief The type-as-written.
1240    TypeSourceInfo *TypeAsWritten;
1241    /// \brief The location of the extern keyword.
1242    SourceLocation ExternLoc;
1243    /// \brief The location of the template keyword.
1244    SourceLocation TemplateKeywordLoc;
1245
1246    ExplicitSpecializationInfo()
1247      : TypeAsWritten(0), ExternLoc(), TemplateKeywordLoc() {}
1248  };
1249
1250  /// \brief Further info for explicit template specialization/instantiation.
1251  /// Does not apply to implicit specializations.
1252  ExplicitSpecializationInfo *ExplicitInfo;
1253
1254  /// \brief The template arguments used to describe this specialization.
1255  TemplateArgumentList *TemplateArgs;
1256
1257  /// \brief The point where this template was instantiated (if any)
1258  SourceLocation PointOfInstantiation;
1259
1260  /// \brief The kind of specialization this declaration refers to.
1261  /// Really a value of type TemplateSpecializationKind.
1262  unsigned SpecializationKind : 3;
1263
1264protected:
1265  ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1266                                  DeclContext *DC, SourceLocation StartLoc,
1267                                  SourceLocation IdLoc,
1268                                  ClassTemplateDecl *SpecializedTemplate,
1269                                  const TemplateArgument *Args,
1270                                  unsigned NumArgs,
1271                                  ClassTemplateSpecializationDecl *PrevDecl);
1272
1273  explicit ClassTemplateSpecializationDecl(Kind DK);
1274
1275public:
1276  static ClassTemplateSpecializationDecl *
1277  Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1278         SourceLocation StartLoc, SourceLocation IdLoc,
1279         ClassTemplateDecl *SpecializedTemplate,
1280         const TemplateArgument *Args,
1281         unsigned NumArgs,
1282         ClassTemplateSpecializationDecl *PrevDecl);
1283  static ClassTemplateSpecializationDecl *
1284  CreateDeserialized(ASTContext &C, unsigned ID);
1285
1286  virtual void getNameForDiagnostic(std::string &S,
1287                                    const PrintingPolicy &Policy,
1288                                    bool Qualified) const;
1289
1290  ClassTemplateSpecializationDecl *getMostRecentDeclaration() {
1291    CXXRecordDecl *Recent
1292        = cast<CXXRecordDecl>(CXXRecordDecl::getMostRecentDeclaration());
1293    if (!isa<ClassTemplateSpecializationDecl>(Recent)) {
1294      // FIXME: Does injected class name need to be in the redeclarations chain?
1295      assert(Recent->isInjectedClassName() && Recent->getPreviousDeclaration());
1296      Recent = Recent->getPreviousDeclaration();
1297    }
1298    return cast<ClassTemplateSpecializationDecl>(Recent);
1299  }
1300
1301  /// \brief Retrieve the template that this specialization specializes.
1302  ClassTemplateDecl *getSpecializedTemplate() const;
1303
1304  /// \brief Retrieve the template arguments of the class template
1305  /// specialization.
1306  const TemplateArgumentList &getTemplateArgs() const {
1307    return *TemplateArgs;
1308  }
1309
1310  /// \brief Determine the kind of specialization that this
1311  /// declaration represents.
1312  TemplateSpecializationKind getSpecializationKind() const {
1313    return static_cast<TemplateSpecializationKind>(SpecializationKind);
1314  }
1315
1316  bool isExplicitSpecialization() const {
1317    return getSpecializationKind() == TSK_ExplicitSpecialization;
1318  }
1319
1320  void setSpecializationKind(TemplateSpecializationKind TSK) {
1321    SpecializationKind = TSK;
1322  }
1323
1324  /// \brief Get the point of instantiation (if any), or null if none.
1325  SourceLocation getPointOfInstantiation() const {
1326    return PointOfInstantiation;
1327  }
1328
1329  void setPointOfInstantiation(SourceLocation Loc) {
1330    assert(Loc.isValid() && "point of instantiation must be valid!");
1331    PointOfInstantiation = Loc;
1332  }
1333
1334  /// \brief If this class template specialization is an instantiation of
1335  /// a template (rather than an explicit specialization), return the
1336  /// class template or class template partial specialization from which it
1337  /// was instantiated.
1338  llvm::PointerUnion<ClassTemplateDecl *,
1339                     ClassTemplatePartialSpecializationDecl *>
1340  getInstantiatedFrom() const {
1341    if (getSpecializationKind() != TSK_ImplicitInstantiation &&
1342        getSpecializationKind() != TSK_ExplicitInstantiationDefinition &&
1343        getSpecializationKind() != TSK_ExplicitInstantiationDeclaration)
1344      return llvm::PointerUnion<ClassTemplateDecl *,
1345                                ClassTemplatePartialSpecializationDecl *>();
1346
1347    if (SpecializedPartialSpecialization *PartialSpec
1348          = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1349      return PartialSpec->PartialSpecialization;
1350
1351    return const_cast<ClassTemplateDecl*>(
1352                             SpecializedTemplate.get<ClassTemplateDecl*>());
1353  }
1354
1355  /// \brief Retrieve the class template or class template partial
1356  /// specialization which was specialized by this.
1357  llvm::PointerUnion<ClassTemplateDecl *,
1358                     ClassTemplatePartialSpecializationDecl *>
1359  getSpecializedTemplateOrPartial() const {
1360    if (SpecializedPartialSpecialization *PartialSpec
1361          = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1362      return PartialSpec->PartialSpecialization;
1363
1364    return const_cast<ClassTemplateDecl*>(
1365                             SpecializedTemplate.get<ClassTemplateDecl*>());
1366  }
1367
1368  /// \brief Retrieve the set of template arguments that should be used
1369  /// to instantiate members of the class template or class template partial
1370  /// specialization from which this class template specialization was
1371  /// instantiated.
1372  ///
1373  /// \returns For a class template specialization instantiated from the primary
1374  /// template, this function will return the same template arguments as
1375  /// getTemplateArgs(). For a class template specialization instantiated from
1376  /// a class template partial specialization, this function will return the
1377  /// deduced template arguments for the class template partial specialization
1378  /// itself.
1379  const TemplateArgumentList &getTemplateInstantiationArgs() const {
1380    if (SpecializedPartialSpecialization *PartialSpec
1381        = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1382      return *PartialSpec->TemplateArgs;
1383
1384    return getTemplateArgs();
1385  }
1386
1387  /// \brief Note that this class template specialization is actually an
1388  /// instantiation of the given class template partial specialization whose
1389  /// template arguments have been deduced.
1390  void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1391                          TemplateArgumentList *TemplateArgs) {
1392    assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1393           "Already set to a class template partial specialization!");
1394    SpecializedPartialSpecialization *PS
1395      = new (getASTContext()) SpecializedPartialSpecialization();
1396    PS->PartialSpecialization = PartialSpec;
1397    PS->TemplateArgs = TemplateArgs;
1398    SpecializedTemplate = PS;
1399  }
1400
1401  /// \brief Note that this class template specialization is an instantiation
1402  /// of the given class template.
1403  void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1404    assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1405           "Previously set to a class template partial specialization!");
1406    SpecializedTemplate = TemplDecl;
1407  }
1408
1409  /// \brief Sets the type of this specialization as it was written by
1410  /// the user. This will be a class template specialization type.
1411  void setTypeAsWritten(TypeSourceInfo *T) {
1412    if (!ExplicitInfo)
1413      ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1414    ExplicitInfo->TypeAsWritten = T;
1415  }
1416  /// \brief Gets the type of this specialization as it was written by
1417  /// the user, if it was so written.
1418  TypeSourceInfo *getTypeAsWritten() const {
1419    return ExplicitInfo ? ExplicitInfo->TypeAsWritten : 0;
1420  }
1421
1422  /// \brief Gets the location of the extern keyword, if present.
1423  SourceLocation getExternLoc() const {
1424    return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1425  }
1426  /// \brief Sets the location of the extern keyword.
1427  void setExternLoc(SourceLocation Loc) {
1428    if (!ExplicitInfo)
1429      ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1430    ExplicitInfo->ExternLoc = Loc;
1431  }
1432
1433  /// \brief Sets the location of the template keyword.
1434  void setTemplateKeywordLoc(SourceLocation Loc) {
1435    if (!ExplicitInfo)
1436      ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1437    ExplicitInfo->TemplateKeywordLoc = Loc;
1438  }
1439  /// \brief Gets the location of the template keyword, if present.
1440  SourceLocation getTemplateKeywordLoc() const {
1441    return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1442  }
1443
1444  SourceRange getSourceRange() const;
1445
1446  void Profile(llvm::FoldingSetNodeID &ID) const {
1447    Profile(ID, TemplateArgs->data(), TemplateArgs->size(), getASTContext());
1448  }
1449
1450  static void
1451  Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs,
1452          unsigned NumTemplateArgs, ASTContext &Context) {
1453    ID.AddInteger(NumTemplateArgs);
1454    for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg)
1455      TemplateArgs[Arg].Profile(ID, Context);
1456  }
1457
1458  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1459  static bool classofKind(Kind K) {
1460    return K >= firstClassTemplateSpecialization &&
1461           K <= lastClassTemplateSpecialization;
1462  }
1463
1464  static bool classof(const ClassTemplateSpecializationDecl *) {
1465    return true;
1466  }
1467
1468  static bool classof(const ClassTemplatePartialSpecializationDecl *) {
1469    return true;
1470  }
1471
1472  friend class ASTDeclReader;
1473  friend class ASTDeclWriter;
1474};
1475
1476class ClassTemplatePartialSpecializationDecl
1477  : public ClassTemplateSpecializationDecl {
1478  virtual void anchor();
1479
1480  /// \brief The list of template parameters
1481  TemplateParameterList* TemplateParams;
1482
1483  /// \brief The source info for the template arguments as written.
1484  /// FIXME: redundant with TypeAsWritten?
1485  TemplateArgumentLoc *ArgsAsWritten;
1486  unsigned NumArgsAsWritten;
1487
1488  /// \brief Sequence number indicating when this class template partial
1489  /// specialization was added to the set of partial specializations for
1490  /// its owning class template.
1491  unsigned SequenceNumber;
1492
1493  /// \brief The class template partial specialization from which this
1494  /// class template partial specialization was instantiated.
1495  ///
1496  /// The boolean value will be true to indicate that this class template
1497  /// partial specialization was specialized at this level.
1498  llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1499      InstantiatedFromMember;
1500
1501  ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1502                                         DeclContext *DC,
1503                                         SourceLocation StartLoc,
1504                                         SourceLocation IdLoc,
1505                                         TemplateParameterList *Params,
1506                                         ClassTemplateDecl *SpecializedTemplate,
1507                                         const TemplateArgument *Args,
1508                                         unsigned NumArgs,
1509                                         TemplateArgumentLoc *ArgInfos,
1510                                         unsigned NumArgInfos,
1511                               ClassTemplatePartialSpecializationDecl *PrevDecl,
1512                                         unsigned SequenceNumber);
1513
1514  ClassTemplatePartialSpecializationDecl()
1515    : ClassTemplateSpecializationDecl(ClassTemplatePartialSpecialization),
1516      TemplateParams(0), ArgsAsWritten(0),
1517      NumArgsAsWritten(0), SequenceNumber(0),
1518      InstantiatedFromMember(0, false) { }
1519
1520public:
1521  static ClassTemplatePartialSpecializationDecl *
1522  Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1523         SourceLocation StartLoc, SourceLocation IdLoc,
1524         TemplateParameterList *Params,
1525         ClassTemplateDecl *SpecializedTemplate,
1526         const TemplateArgument *Args,
1527         unsigned NumArgs,
1528         const TemplateArgumentListInfo &ArgInfos,
1529         QualType CanonInjectedType,
1530         ClassTemplatePartialSpecializationDecl *PrevDecl,
1531         unsigned SequenceNumber);
1532
1533  static ClassTemplatePartialSpecializationDecl *
1534  CreateDeserialized(ASTContext &C, unsigned ID);
1535
1536  ClassTemplatePartialSpecializationDecl *getMostRecentDeclaration() {
1537    return cast<ClassTemplatePartialSpecializationDecl>(
1538                   ClassTemplateSpecializationDecl::getMostRecentDeclaration());
1539  }
1540
1541  /// Get the list of template parameters
1542  TemplateParameterList *getTemplateParameters() const {
1543    return TemplateParams;
1544  }
1545
1546  /// Get the template arguments as written.
1547  TemplateArgumentLoc *getTemplateArgsAsWritten() const {
1548    return ArgsAsWritten;
1549  }
1550
1551  /// Get the number of template arguments as written.
1552  unsigned getNumTemplateArgsAsWritten() const {
1553    return NumArgsAsWritten;
1554  }
1555
1556  /// \brief Get the sequence number for this class template partial
1557  /// specialization.
1558  unsigned getSequenceNumber() const { return SequenceNumber; }
1559
1560  /// \brief Retrieve the member class template partial specialization from
1561  /// which this particular class template partial specialization was
1562  /// instantiated.
1563  ///
1564  /// \code
1565  /// template<typename T>
1566  /// struct Outer {
1567  ///   template<typename U> struct Inner;
1568  ///   template<typename U> struct Inner<U*> { }; // #1
1569  /// };
1570  ///
1571  /// Outer<float>::Inner<int*> ii;
1572  /// \endcode
1573  ///
1574  /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
1575  /// end up instantiating the partial specialization
1576  /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
1577  /// template partial specialization \c Outer<T>::Inner<U*>. Given
1578  /// \c Outer<float>::Inner<U*>, this function would return
1579  /// \c Outer<T>::Inner<U*>.
1580  ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() {
1581    ClassTemplatePartialSpecializationDecl *First
1582      = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
1583    return First->InstantiatedFromMember.getPointer();
1584  }
1585
1586  void setInstantiatedFromMember(
1587                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
1588    ClassTemplatePartialSpecializationDecl *First
1589      = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
1590    First->InstantiatedFromMember.setPointer(PartialSpec);
1591  }
1592
1593  /// \brief Determines whether this class template partial specialization
1594  /// template was a specialization of a member partial specialization.
1595  ///
1596  /// In the following example, the member template partial specialization
1597  /// \c X<int>::Inner<T*> is a member specialization.
1598  ///
1599  /// \code
1600  /// template<typename T>
1601  /// struct X {
1602  ///   template<typename U> struct Inner;
1603  ///   template<typename U> struct Inner<U*>;
1604  /// };
1605  ///
1606  /// template<> template<typename T>
1607  /// struct X<int>::Inner<T*> { /* ... */ };
1608  /// \endcode
1609  bool isMemberSpecialization() {
1610    ClassTemplatePartialSpecializationDecl *First
1611      = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
1612    return First->InstantiatedFromMember.getInt();
1613  }
1614
1615  /// \brief Note that this member template is a specialization.
1616  void setMemberSpecialization() {
1617    ClassTemplatePartialSpecializationDecl *First
1618      = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
1619    assert(First->InstantiatedFromMember.getPointer() &&
1620           "Only member templates can be member template specializations");
1621    return First->InstantiatedFromMember.setInt(true);
1622  }
1623
1624  /// Retrieves the injected specialization type for this partial
1625  /// specialization.  This is not the same as the type-decl-type for
1626  /// this partial specialization, which is an InjectedClassNameType.
1627  QualType getInjectedSpecializationType() const {
1628    assert(getTypeForDecl() && "partial specialization has no type set!");
1629    return cast<InjectedClassNameType>(getTypeForDecl())
1630             ->getInjectedSpecializationType();
1631  }
1632
1633  // FIXME: Add Profile support!
1634
1635  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1636  static bool classofKind(Kind K) {
1637    return K == ClassTemplatePartialSpecialization;
1638  }
1639
1640  static bool classof(const ClassTemplatePartialSpecializationDecl *) {
1641    return true;
1642  }
1643
1644  friend class ASTDeclReader;
1645  friend class ASTDeclWriter;
1646};
1647
1648/// Declaration of a class template.
1649class ClassTemplateDecl : public RedeclarableTemplateDecl {
1650  static void DeallocateCommon(void *Ptr);
1651
1652protected:
1653  /// \brief Data that is common to all of the declarations of a given
1654  /// class template.
1655  struct Common : CommonBase {
1656    Common() : LazySpecializations() { }
1657
1658    /// \brief The class template specializations for this class
1659    /// template, including explicit specializations and instantiations.
1660    llvm::FoldingSet<ClassTemplateSpecializationDecl> Specializations;
1661
1662    /// \brief The class template partial specializations for this class
1663    /// template.
1664    llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>
1665      PartialSpecializations;
1666
1667    /// \brief The injected-class-name type for this class template.
1668    QualType InjectedClassNameType;
1669
1670    /// \brief If non-null, points to an array of specializations (including
1671    /// partial specializations) known ownly by their external declaration IDs.
1672    ///
1673    /// The first value in the array is the number of of specializations/
1674    /// partial specializations that follow.
1675    uint32_t *LazySpecializations;
1676  };
1677
1678  /// \brief Load any lazily-loaded specializations from the external source.
1679  void LoadLazySpecializations();
1680
1681  /// \brief Retrieve the set of specializations of this class template.
1682  llvm::FoldingSet<ClassTemplateSpecializationDecl> &getSpecializations();
1683
1684  /// \brief Retrieve the set of partial specializations of this class
1685  /// template.
1686  llvm::FoldingSet<ClassTemplatePartialSpecializationDecl> &
1687  getPartialSpecializations();
1688
1689  ClassTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
1690                    TemplateParameterList *Params, NamedDecl *Decl)
1691    : RedeclarableTemplateDecl(ClassTemplate, DC, L, Name, Params, Decl) { }
1692
1693  ClassTemplateDecl(EmptyShell Empty)
1694    : RedeclarableTemplateDecl(ClassTemplate, 0, SourceLocation(),
1695                               DeclarationName(), 0, 0) { }
1696
1697  CommonBase *newCommon(ASTContext &C);
1698
1699  Common *getCommonPtr() {
1700    return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1701  }
1702
1703public:
1704  /// Get the underlying class declarations of the template.
1705  CXXRecordDecl *getTemplatedDecl() const {
1706    return static_cast<CXXRecordDecl *>(TemplatedDecl);
1707  }
1708
1709  /// Returns whether this template declaration defines the primary
1710  /// class pattern.
1711  bool isThisDeclarationADefinition() const {
1712    return getTemplatedDecl()->isThisDeclarationADefinition();
1713  }
1714
1715  /// Create a class template node.
1716  static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1717                                   SourceLocation L,
1718                                   DeclarationName Name,
1719                                   TemplateParameterList *Params,
1720                                   NamedDecl *Decl,
1721                                   ClassTemplateDecl *PrevDecl);
1722
1723  /// Create an empty class template node.
1724  static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1725
1726  /// \brief Return the specialization with the provided arguments if it exists,
1727  /// otherwise return the insertion point.
1728  ClassTemplateSpecializationDecl *
1729  findSpecialization(const TemplateArgument *Args, unsigned NumArgs,
1730                     void *&InsertPos);
1731
1732  /// \brief Insert the specified specialization knowing that it is not already
1733  /// in. InsertPos must be obtained from findSpecialization.
1734  void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
1735
1736  ClassTemplateDecl *getCanonicalDecl() {
1737    return cast<ClassTemplateDecl>(
1738             RedeclarableTemplateDecl::getCanonicalDecl());
1739  }
1740  const ClassTemplateDecl *getCanonicalDecl() const {
1741    return cast<ClassTemplateDecl>(
1742             RedeclarableTemplateDecl::getCanonicalDecl());
1743  }
1744
1745  /// \brief Retrieve the previous declaration of this class template, or
1746  /// NULL if no such declaration exists.
1747  ClassTemplateDecl *getPreviousDeclaration() {
1748    return cast_or_null<ClassTemplateDecl>(
1749             RedeclarableTemplateDecl::getPreviousDeclaration());
1750  }
1751
1752  /// \brief Retrieve the previous declaration of this class template, or
1753  /// NULL if no such declaration exists.
1754  const ClassTemplateDecl *getPreviousDeclaration() const {
1755    return cast_or_null<ClassTemplateDecl>(
1756             RedeclarableTemplateDecl::getPreviousDeclaration());
1757  }
1758
1759  ClassTemplateDecl *getInstantiatedFromMemberTemplate() {
1760    return cast_or_null<ClassTemplateDecl>(
1761             RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1762  }
1763
1764  /// \brief Return the partial specialization with the provided arguments if it
1765  /// exists, otherwise return the insertion point.
1766  ClassTemplatePartialSpecializationDecl *
1767  findPartialSpecialization(const TemplateArgument *Args, unsigned NumArgs,
1768                            void *&InsertPos);
1769
1770  /// \brief Insert the specified partial specialization knowing that it is not
1771  /// already in. InsertPos must be obtained from findPartialSpecialization.
1772  void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
1773                                void *InsertPos);
1774
1775  /// \brief Return the next partial specialization sequence number.
1776  unsigned getNextPartialSpecSequenceNumber() {
1777    return getPartialSpecializations().size();
1778  }
1779
1780  /// \brief Retrieve the partial specializations as an ordered list.
1781  void getPartialSpecializations(
1782          SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
1783
1784  /// \brief Find a class template partial specialization with the given
1785  /// type T.
1786  ///
1787  /// \param T a dependent type that names a specialization of this class
1788  /// template.
1789  ///
1790  /// \returns the class template partial specialization that exactly matches
1791  /// the type \p T, or NULL if no such partial specialization exists.
1792  ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
1793
1794  /// \brief Find a class template partial specialization which was instantiated
1795  /// from the given member partial specialization.
1796  ///
1797  /// \param D a member class template partial specialization.
1798  ///
1799  /// \returns the class template partial specialization which was instantiated
1800  /// from the given member partial specialization, or NULL if no such partial
1801  /// specialization exists.
1802  ClassTemplatePartialSpecializationDecl *
1803  findPartialSpecInstantiatedFromMember(
1804                                     ClassTemplatePartialSpecializationDecl *D);
1805
1806  /// \brief Retrieve the template specialization type of the
1807  /// injected-class-name for this class template.
1808  ///
1809  /// The injected-class-name for a class template \c X is \c
1810  /// X<template-args>, where \c template-args is formed from the
1811  /// template arguments that correspond to the template parameters of
1812  /// \c X. For example:
1813  ///
1814  /// \code
1815  /// template<typename T, int N>
1816  /// struct array {
1817  ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
1818  /// };
1819  /// \endcode
1820  QualType getInjectedClassNameSpecialization();
1821
1822  typedef SpecIterator<ClassTemplateSpecializationDecl> spec_iterator;
1823
1824  spec_iterator spec_begin() {
1825    return makeSpecIterator(getSpecializations(), false);
1826  }
1827
1828  spec_iterator spec_end() {
1829    return makeSpecIterator(getSpecializations(), true);
1830  }
1831
1832  typedef SpecIterator<ClassTemplatePartialSpecializationDecl>
1833          partial_spec_iterator;
1834
1835  partial_spec_iterator partial_spec_begin() {
1836    return makeSpecIterator(getPartialSpecializations(), false);
1837  }
1838
1839  partial_spec_iterator partial_spec_end() {
1840    return makeSpecIterator(getPartialSpecializations(), true);
1841  }
1842
1843  // Implement isa/cast/dyncast support
1844  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1845  static bool classof(const ClassTemplateDecl *D) { return true; }
1846  static bool classofKind(Kind K) { return K == ClassTemplate; }
1847
1848  friend class ASTDeclReader;
1849  friend class ASTDeclWriter;
1850};
1851
1852/// Declaration of a friend template.  For example:
1853///
1854/// template <typename T> class A {
1855///   friend class MyVector<T>; // not a friend template
1856///   template <typename U> friend class B; // not a friend template
1857///   template <typename U> friend class Foo<T>::Nested; // friend template
1858/// };
1859/// NOTE: This class is not currently in use.  All of the above
1860/// will yield a FriendDecl, not a FriendTemplateDecl.
1861class FriendTemplateDecl : public Decl {
1862  virtual void anchor();
1863public:
1864  typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
1865
1866private:
1867  // The number of template parameters;  always non-zero.
1868  unsigned NumParams;
1869
1870  // The parameter list.
1871  TemplateParameterList **Params;
1872
1873  // The declaration that's a friend of this class.
1874  FriendUnion Friend;
1875
1876  // Location of the 'friend' specifier.
1877  SourceLocation FriendLoc;
1878
1879
1880  FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
1881                     unsigned NParams,
1882                     TemplateParameterList **Params,
1883                     FriendUnion Friend,
1884                     SourceLocation FriendLoc)
1885    : Decl(Decl::FriendTemplate, DC, Loc),
1886      NumParams(NParams),
1887      Params(Params),
1888      Friend(Friend),
1889      FriendLoc(FriendLoc)
1890  {}
1891
1892  FriendTemplateDecl(EmptyShell Empty)
1893    : Decl(Decl::FriendTemplate, Empty),
1894      NumParams(0),
1895      Params(0)
1896  {}
1897
1898public:
1899  static FriendTemplateDecl *Create(ASTContext &Context,
1900                                    DeclContext *DC, SourceLocation Loc,
1901                                    unsigned NParams,
1902                                    TemplateParameterList **Params,
1903                                    FriendUnion Friend,
1904                                    SourceLocation FriendLoc);
1905
1906  static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1907
1908  /// If this friend declaration names a templated type (or
1909  /// a dependent member type of a templated type), return that
1910  /// type;  otherwise return null.
1911  TypeSourceInfo *getFriendType() const {
1912    return Friend.dyn_cast<TypeSourceInfo*>();
1913  }
1914
1915  /// If this friend declaration names a templated function (or
1916  /// a member function of a templated type), return that type;
1917  /// otherwise return null.
1918  NamedDecl *getFriendDecl() const {
1919    return Friend.dyn_cast<NamedDecl*>();
1920  }
1921
1922  /// Retrieves the location of the 'friend' keyword.
1923  SourceLocation getFriendLoc() const {
1924    return FriendLoc;
1925  }
1926
1927  TemplateParameterList *getTemplateParameterList(unsigned i) const {
1928    assert(i <= NumParams);
1929    return Params[i];
1930  }
1931
1932  unsigned getNumTemplateParameters() const {
1933    return NumParams;
1934  }
1935
1936  // Implement isa/cast/dyncast/etc.
1937  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1938  static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
1939  static bool classof(const FriendTemplateDecl *D) { return true; }
1940
1941  friend class ASTDeclReader;
1942};
1943
1944/// Declaration of an alias template.  For example:
1945///
1946/// template <typename T> using V = std::map<T*, int, MyCompare<T>>;
1947class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
1948  static void DeallocateCommon(void *Ptr);
1949
1950protected:
1951  typedef CommonBase Common;
1952
1953  TypeAliasTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
1954                        TemplateParameterList *Params, NamedDecl *Decl)
1955    : RedeclarableTemplateDecl(TypeAliasTemplate, DC, L, Name, Params, Decl) { }
1956
1957  CommonBase *newCommon(ASTContext &C);
1958
1959  Common *getCommonPtr() {
1960    return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1961  }
1962
1963public:
1964  /// Get the underlying function declaration of the template.
1965  TypeAliasDecl *getTemplatedDecl() const {
1966    return static_cast<TypeAliasDecl*>(TemplatedDecl);
1967  }
1968
1969
1970  TypeAliasTemplateDecl *getCanonicalDecl() {
1971    return cast<TypeAliasTemplateDecl>(
1972             RedeclarableTemplateDecl::getCanonicalDecl());
1973  }
1974  const TypeAliasTemplateDecl *getCanonicalDecl() const {
1975    return cast<TypeAliasTemplateDecl>(
1976             RedeclarableTemplateDecl::getCanonicalDecl());
1977  }
1978
1979  /// \brief Retrieve the previous declaration of this function template, or
1980  /// NULL if no such declaration exists.
1981  TypeAliasTemplateDecl *getPreviousDeclaration() {
1982    return cast_or_null<TypeAliasTemplateDecl>(
1983             RedeclarableTemplateDecl::getPreviousDeclaration());
1984  }
1985
1986  /// \brief Retrieve the previous declaration of this function template, or
1987  /// NULL if no such declaration exists.
1988  const TypeAliasTemplateDecl *getPreviousDeclaration() const {
1989    return cast_or_null<TypeAliasTemplateDecl>(
1990             RedeclarableTemplateDecl::getPreviousDeclaration());
1991  }
1992
1993  TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() {
1994    return cast_or_null<TypeAliasTemplateDecl>(
1995             RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1996  }
1997
1998
1999  /// \brief Create a function template node.
2000  static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2001                                       SourceLocation L,
2002                                       DeclarationName Name,
2003                                       TemplateParameterList *Params,
2004                                       NamedDecl *Decl);
2005
2006  /// \brief Create an empty alias template node.
2007  static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2008
2009  // Implement isa/cast/dyncast support
2010  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2011  static bool classof(const TypeAliasTemplateDecl *D) { return true; }
2012  static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2013
2014  friend class ASTDeclReader;
2015  friend class ASTDeclWriter;
2016};
2017
2018/// Declaration of a function specialization at template class scope.
2019/// This is a non standard extension needed to support MSVC.
2020/// For example:
2021/// template <class T>
2022/// class A {
2023///    template <class U> void foo(U a) { }
2024///    template<> void foo(int a) { }
2025/// }
2026///
2027/// "template<> foo(int a)" will be saved in Specialization as a normal
2028/// CXXMethodDecl. Then during an instantiation of class A, it will be
2029/// transformed into an actual function specialization.
2030class ClassScopeFunctionSpecializationDecl : public Decl {
2031  virtual void anchor();
2032
2033  ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
2034                                       CXXMethodDecl *FD)
2035    : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2036      Specialization(FD) {}
2037
2038  ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2039    : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2040
2041  CXXMethodDecl *Specialization;
2042
2043public:
2044  CXXMethodDecl *getSpecialization() const { return Specialization; }
2045
2046  static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
2047                                                      DeclContext *DC,
2048                                                      SourceLocation Loc,
2049                                                      CXXMethodDecl *FD) {
2050    return new (C) ClassScopeFunctionSpecializationDecl(DC , Loc, FD);
2051  }
2052
2053  static ClassScopeFunctionSpecializationDecl *
2054  CreateDeserialized(ASTContext &Context, unsigned ID);
2055
2056  // Implement isa/cast/dyncast/etc.
2057  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2058  static bool classofKind(Kind K) {
2059    return K == Decl::ClassScopeFunctionSpecialization;
2060  }
2061  static bool classof(const ClassScopeFunctionSpecializationDecl *D) {
2062    return true;
2063  }
2064
2065  friend class ASTDeclReader;
2066  friend class ASTDeclWriter;
2067};
2068
2069/// Implementation of inline functions that require the template declarations
2070inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
2071  : Function(FTD) { }
2072
2073} /* end of namespace clang */
2074
2075#endif
2076