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