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