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