]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/AST/DeclTemplate.h
Update clang to trunk r256633.
[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 /// \file
11 /// \brief Defines the C++ template declaration subclasses.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
16 #define LLVM_CLANG_AST_DECLTEMPLATE_H
17
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/Redeclarable.h"
20 #include "clang/AST/TemplateBase.h"
21 #include "llvm/ADT/PointerUnion.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/TrailingObjects.h"
24 #include <limits>
25
26 namespace clang {
27
28 enum BuiltinTemplateKind : int;
29 class TemplateParameterList;
30 class TemplateDecl;
31 class RedeclarableTemplateDecl;
32 class FunctionTemplateDecl;
33 class ClassTemplateDecl;
34 class ClassTemplatePartialSpecializationDecl;
35 class TemplateTypeParmDecl;
36 class NonTypeTemplateParmDecl;
37 class TemplateTemplateParmDecl;
38 class TypeAliasTemplateDecl;
39 class VarTemplateDecl;
40 class VarTemplatePartialSpecializationDecl;
41
42 /// \brief Stores a template parameter of any kind.
43 typedef llvm::PointerUnion3<TemplateTypeParmDecl*, NonTypeTemplateParmDecl*,
44                             TemplateTemplateParmDecl*> TemplateParameter;
45
46 /// \brief Stores a list of template parameters for a TemplateDecl and its
47 /// derived classes.
48 class TemplateParameterList final
49     : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *> {
50
51   /// The location of the 'template' keyword.
52   SourceLocation TemplateLoc;
53
54   /// The locations of the '<' and '>' angle brackets.
55   SourceLocation LAngleLoc, RAngleLoc;
56
57   /// The number of template parameters in this template
58   /// parameter list.
59   unsigned NumParams : 31;
60
61   /// Whether this template parameter list contains an unexpanded parameter
62   /// pack.
63   unsigned ContainsUnexpandedParameterPack : 1;
64
65 protected:
66   size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
67     return NumParams;
68   }
69
70   TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
71                         ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc);
72
73 public:
74   static TemplateParameterList *Create(const ASTContext &C,
75                                        SourceLocation TemplateLoc,
76                                        SourceLocation LAngleLoc,
77                                        ArrayRef<NamedDecl *> Params,
78                                        SourceLocation RAngleLoc);
79
80   /// \brief Iterates through the template parameters in this list.
81   typedef NamedDecl** iterator;
82
83   /// \brief Iterates through the template parameters in this list.
84   typedef NamedDecl* const* const_iterator;
85
86   iterator begin() { return getTrailingObjects<NamedDecl *>(); }
87   const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
88   iterator end() { return begin() + NumParams; }
89   const_iterator end() const { return begin() + NumParams; }
90
91   unsigned size() const { return NumParams; }
92
93   ArrayRef<NamedDecl*> asArray() {
94     return llvm::makeArrayRef(begin(), end());
95   }
96   ArrayRef<const NamedDecl*> asArray() const {
97     return llvm::makeArrayRef(begin(), size());
98   }
99
100   NamedDecl* getParam(unsigned Idx) {
101     assert(Idx < size() && "Template parameter index out-of-range");
102     return begin()[Idx];
103   }
104
105   const NamedDecl* getParam(unsigned Idx) const {
106     assert(Idx < size() && "Template parameter index out-of-range");
107     return begin()[Idx];
108   }
109
110   /// \brief Returns the minimum number of arguments needed to form a
111   /// template specialization.
112   ///
113   /// This may be fewer than the number of template parameters, if some of
114   /// the parameters have default arguments or if there is a parameter pack.
115   unsigned getMinRequiredArguments() const;
116
117   /// \brief Get the depth of this template parameter list in the set of
118   /// template parameter lists.
119   ///
120   /// The first template parameter list in a declaration will have depth 0,
121   /// the second template parameter list will have depth 1, etc.
122   unsigned getDepth() const;
123
124   /// \brief Determine whether this template parameter list contains an
125   /// unexpanded parameter pack.
126   bool containsUnexpandedParameterPack() const {
127     return ContainsUnexpandedParameterPack;
128   }
129
130   SourceLocation getTemplateLoc() const { return TemplateLoc; }
131   SourceLocation getLAngleLoc() const { return LAngleLoc; }
132   SourceLocation getRAngleLoc() const { return RAngleLoc; }
133
134   SourceRange getSourceRange() const LLVM_READONLY {
135     return SourceRange(TemplateLoc, RAngleLoc);
136   }
137
138   friend TrailingObjects;
139   template <size_t N> friend class FixedSizeTemplateParameterListStorage;
140 };
141
142 /// \brief Stores a list of template parameters for a TemplateDecl and its
143 /// derived classes. Suitable for creating on the stack.
144 template <size_t N> class FixedSizeTemplateParameterListStorage {
145   // This is kinda ugly: TemplateParameterList usually gets allocated
146   // in a block of memory with NamedDecls appended to it. Here, to get
147   // it stack allocated, we include the params as a separate
148   // variable. After allocation, the TemplateParameterList object
149   // treats them as part of itself.
150   TemplateParameterList List;
151   NamedDecl *Params[N];
152
153 public:
154   FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
155                                         SourceLocation LAngleLoc,
156                                         ArrayRef<NamedDecl *> Params,
157                                         SourceLocation RAngleLoc)
158       : List(TemplateLoc, LAngleLoc, Params, RAngleLoc) {
159     // Because we're doing an evil layout hack above, have some
160     // asserts, just to double-check everything is laid out like
161     // expected.
162     assert(sizeof(*this) ==
163                TemplateParameterList::totalSizeToAlloc<NamedDecl *>(N) &&
164            "Object layout not as expected");
165     assert(this->Params == List.getTrailingObjects<NamedDecl *>() &&
166            "Object layout not as expected");
167   }
168   TemplateParameterList *get() { return &List; }
169 };
170
171 /// \brief A template argument list.
172 class TemplateArgumentList final
173     : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
174   /// \brief The template argument list.
175   const TemplateArgument *Arguments;
176
177   /// \brief The number of template arguments in this template
178   /// argument list.
179   unsigned NumArguments;
180
181   TemplateArgumentList(const TemplateArgumentList &Other) = delete;
182   void operator=(const TemplateArgumentList &Other) = delete;
183
184   // Constructs an instance with an internal Argument list, containing
185   // a copy of the Args array. (Called by CreateCopy)
186   TemplateArgumentList(const TemplateArgument *Args, unsigned NumArgs);
187
188 public:
189   /// \brief Type used to indicate that the template argument list itself is a
190   /// stack object. It does not own its template arguments.
191   enum OnStackType { OnStack };
192
193   /// \brief Create a new template argument list that copies the given set of
194   /// template arguments.
195   static TemplateArgumentList *CreateCopy(ASTContext &Context,
196                                           const TemplateArgument *Args,
197                                           unsigned NumArgs);
198
199   /// \brief Construct a new, temporary template argument list on the stack.
200   ///
201   /// The template argument list does not own the template arguments
202   /// provided.
203   explicit TemplateArgumentList(OnStackType, const TemplateArgument *Args,
204                                 unsigned NumArgs)
205       : Arguments(Args), NumArguments(NumArgs) {}
206
207   /// \brief Produces a shallow copy of the given template argument list.
208   ///
209   /// This operation assumes that the input argument list outlives it.
210   /// This takes the list as a pointer to avoid looking like a copy
211   /// constructor, since this really really isn't safe to use that
212   /// way.
213   explicit TemplateArgumentList(const TemplateArgumentList *Other)
214       : Arguments(Other->data()), NumArguments(Other->size()) {}
215
216   /// \brief Retrieve the template argument at a given index.
217   const TemplateArgument &get(unsigned Idx) const {
218     assert(Idx < NumArguments && "Invalid template argument index");
219     return data()[Idx];
220   }
221
222   /// \brief Retrieve the template argument at a given index.
223   const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
224
225   /// \brief Produce this as an array ref.
226   ArrayRef<TemplateArgument> asArray() const {
227     return llvm::makeArrayRef(data(), size());
228   }
229
230   /// \brief Retrieve the number of template arguments in this
231   /// template argument list.
232   unsigned size() const { return NumArguments; }
233
234   /// \brief Retrieve a pointer to the template argument list.
235   const TemplateArgument *data() const { return Arguments; }
236
237   friend TrailingObjects;
238 };
239
240 void *allocateDefaultArgStorageChain(const ASTContext &C);
241
242 /// Storage for a default argument. This is conceptually either empty, or an
243 /// argument value, or a pointer to a previous declaration that had a default
244 /// argument.
245 ///
246 /// However, this is complicated by modules: while we require all the default
247 /// arguments for a template to be equivalent, there may be more than one, and
248 /// we need to track all the originating parameters to determine if the default
249 /// argument is visible.
250 template<typename ParmDecl, typename ArgType>
251 class DefaultArgStorage {
252   /// Storage for both the value *and* another parameter from which we inherit
253   /// the default argument. This is used when multiple default arguments for a
254   /// parameter are merged together from different modules.
255   struct Chain {
256     ParmDecl *PrevDeclWithDefaultArg;
257     ArgType Value;
258   };
259   static_assert(sizeof(Chain) == sizeof(void *) * 2,
260                 "non-pointer argument type?");
261
262   llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
263
264   static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
265     const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
266     if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl*>())
267       Parm = Prev;
268     assert(!Parm->getDefaultArgStorage()
269                 .ValueOrInherited.template is<ParmDecl *>() &&
270            "should only be one level of indirection");
271     return Parm;
272   }
273
274 public:
275   DefaultArgStorage() : ValueOrInherited(ArgType()) {}
276
277   /// Determine whether there is a default argument for this parameter.
278   bool isSet() const { return !ValueOrInherited.isNull(); }
279   /// Determine whether the default argument for this parameter was inherited
280   /// from a previous declaration of the same entity.
281   bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
282   /// Get the default argument's value. This does not consider whether the
283   /// default argument is visible.
284   ArgType get() const {
285     const DefaultArgStorage *Storage = this;
286     if (auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl*>())
287       Storage = &Prev->getDefaultArgStorage();
288     if (auto *C = Storage->ValueOrInherited.template dyn_cast<Chain*>())
289       return C->Value;
290     return Storage->ValueOrInherited.template get<ArgType>();
291   }
292   /// Get the parameter from which we inherit the default argument, if any.
293   /// This is the parameter on which the default argument was actually written.
294   const ParmDecl *getInheritedFrom() const {
295     if (auto *D = ValueOrInherited.template dyn_cast<ParmDecl*>())
296       return D;
297     if (auto *C = ValueOrInherited.template dyn_cast<Chain*>())
298       return C->PrevDeclWithDefaultArg;
299     return nullptr;
300   }
301   /// Set the default argument.
302   void set(ArgType Arg) {
303     assert(!isSet() && "default argument already set");
304     ValueOrInherited = Arg;
305   }
306   /// Set that the default argument was inherited from another parameter.
307   void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
308     assert(!isInherited() && "default argument already inherited");
309     InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
310     if (!isSet())
311       ValueOrInherited = InheritedFrom;
312     else
313       ValueOrInherited = new (allocateDefaultArgStorageChain(C))
314           Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
315   }
316   /// Remove the default argument, even if it was inherited.
317   void clear() {
318     ValueOrInherited = ArgType();
319   }
320 };
321
322 //===----------------------------------------------------------------------===//
323 // Kinds of Templates
324 //===----------------------------------------------------------------------===//
325
326 /// \brief The base class of all kinds of template declarations (e.g.,
327 /// class, function, etc.).
328 ///
329 /// The TemplateDecl class stores the list of template parameters and a
330 /// reference to the templated scoped declaration: the underlying AST node.
331 class TemplateDecl : public NamedDecl {
332   void anchor() override;
333 protected:
334   // This is probably never used.
335   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
336                DeclarationName Name)
337     : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
338       TemplateParams(nullptr) {}
339
340   // Construct a template decl with the given name and parameters.
341   // Used when there is not templated element (tt-params).
342   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
343                DeclarationName Name, TemplateParameterList *Params)
344     : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
345       TemplateParams(Params) {}
346
347   // Construct a template decl with name, parameters, and templated element.
348   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
349                DeclarationName Name, TemplateParameterList *Params,
350                NamedDecl *Decl)
351     : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
352       TemplateParams(Params) { }
353 public:
354   /// Get the list of template parameters
355   TemplateParameterList *getTemplateParameters() const {
356     return TemplateParams;
357   }
358
359   /// Get the underlying, templated declaration.
360   NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
361
362   // Implement isa/cast/dyncast/etc.
363   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
364   static bool classofKind(Kind K) {
365     return K >= firstTemplate && K <= lastTemplate;
366   }
367
368   SourceRange getSourceRange() const override LLVM_READONLY {
369     return SourceRange(TemplateParams->getTemplateLoc(),
370                        TemplatedDecl->getSourceRange().getEnd());
371   }
372
373 protected:
374   NamedDecl *TemplatedDecl;
375   TemplateParameterList* TemplateParams;
376
377 public:
378   /// \brief Initialize the underlying templated declaration and
379   /// template parameters.
380   void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
381     assert(!TemplatedDecl && "TemplatedDecl already set!");
382     assert(!TemplateParams && "TemplateParams already set!");
383     TemplatedDecl = templatedDecl;
384     TemplateParams = templateParams;
385   }
386 };
387
388 /// \brief Provides information about a function template specialization,
389 /// which is a FunctionDecl that has been explicitly specialization or
390 /// instantiated from a function template.
391 class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
392   FunctionTemplateSpecializationInfo(FunctionDecl *FD,
393                                      FunctionTemplateDecl *Template,
394                                      TemplateSpecializationKind TSK,
395                                      const TemplateArgumentList *TemplateArgs,
396                        const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
397                                      SourceLocation POI)
398   : Function(FD),
399     Template(Template, TSK - 1),
400     TemplateArguments(TemplateArgs),
401     TemplateArgumentsAsWritten(TemplateArgsAsWritten),
402     PointOfInstantiation(POI) { }
403
404 public:
405   static FunctionTemplateSpecializationInfo *
406   Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
407          TemplateSpecializationKind TSK,
408          const TemplateArgumentList *TemplateArgs,
409          const TemplateArgumentListInfo *TemplateArgsAsWritten,
410          SourceLocation POI);
411
412   /// \brief The function template specialization that this structure
413   /// describes.
414   FunctionDecl *Function;
415
416   /// \brief The function template from which this function template
417   /// specialization was generated.
418   ///
419   /// The two bits contain the top 4 values of TemplateSpecializationKind.
420   llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
421
422   /// \brief The template arguments used to produce the function template
423   /// specialization from the function template.
424   const TemplateArgumentList *TemplateArguments;
425
426   /// \brief The template arguments as written in the sources, if provided.
427   const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
428
429   /// \brief The point at which this function template specialization was
430   /// first instantiated.
431   SourceLocation PointOfInstantiation;
432
433   /// \brief Retrieve the template from which this function was specialized.
434   FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
435
436   /// \brief Determine what kind of template specialization this is.
437   TemplateSpecializationKind getTemplateSpecializationKind() const {
438     return (TemplateSpecializationKind)(Template.getInt() + 1);
439   }
440
441   bool isExplicitSpecialization() const {
442     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
443   }
444
445   /// \brief True if this declaration is an explicit specialization,
446   /// explicit instantiation declaration, or explicit instantiation
447   /// definition.
448   bool isExplicitInstantiationOrSpecialization() const {
449     return isTemplateExplicitInstantiationOrSpecialization(
450         getTemplateSpecializationKind());
451   }
452
453   /// \brief Set the template specialization kind.
454   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
455     assert(TSK != TSK_Undeclared &&
456          "Cannot encode TSK_Undeclared for a function template specialization");
457     Template.setInt(TSK - 1);
458   }
459
460   /// \brief Retrieve the first point of instantiation of this function
461   /// template specialization.
462   ///
463   /// The point of instantiation may be an invalid source location if this
464   /// function has yet to be instantiated.
465   SourceLocation getPointOfInstantiation() const {
466     return PointOfInstantiation;
467   }
468
469   /// \brief Set the (first) point of instantiation of this function template
470   /// specialization.
471   void setPointOfInstantiation(SourceLocation POI) {
472     PointOfInstantiation = POI;
473   }
474
475   void Profile(llvm::FoldingSetNodeID &ID) {
476     Profile(ID, TemplateArguments->asArray(),
477             Function->getASTContext());
478   }
479
480   static void
481   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
482           ASTContext &Context) {
483     ID.AddInteger(TemplateArgs.size());
484     for (unsigned Arg = 0; Arg != TemplateArgs.size(); ++Arg)
485       TemplateArgs[Arg].Profile(ID, Context);
486   }
487 };
488
489 /// \brief Provides information a specialization of a member of a class
490 /// template, which may be a member function, static data member,
491 /// member class or member enumeration.
492 class MemberSpecializationInfo {
493   // The member declaration from which this member was instantiated, and the
494   // manner in which the instantiation occurred (in the lower two bits).
495   llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
496
497   // The point at which this member was first instantiated.
498   SourceLocation PointOfInstantiation;
499
500 public:
501   explicit
502   MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
503                            SourceLocation POI = SourceLocation())
504     : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
505     assert(TSK != TSK_Undeclared &&
506            "Cannot encode undeclared template specializations for members");
507   }
508
509   /// \brief Retrieve the member declaration from which this member was
510   /// instantiated.
511   NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
512
513   /// \brief Determine what kind of template specialization this is.
514   TemplateSpecializationKind getTemplateSpecializationKind() const {
515     return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
516   }
517
518   bool isExplicitSpecialization() const {
519     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
520   }
521
522   /// \brief Set the template specialization kind.
523   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
524     assert(TSK != TSK_Undeclared &&
525            "Cannot encode undeclared template specializations for members");
526     MemberAndTSK.setInt(TSK - 1);
527   }
528
529   /// \brief Retrieve the first point of instantiation of this member.
530   /// If the point of instantiation is an invalid location, then this member
531   /// has not yet been instantiated.
532   SourceLocation getPointOfInstantiation() const {
533     return PointOfInstantiation;
534   }
535
536   /// \brief Set the first point of instantiation.
537   void setPointOfInstantiation(SourceLocation POI) {
538     PointOfInstantiation = POI;
539   }
540 };
541
542 /// \brief Provides information about a dependent function-template
543 /// specialization declaration.
544 ///
545 /// Since explicit function template specialization and instantiation
546 /// declarations can only appear in namespace scope, and you can only
547 /// specialize a member of a fully-specialized class, the only way to
548 /// get one of these is in a friend declaration like the following:
549 ///
550 /// \code
551 ///   template \<class T> void foo(T);
552 ///   template \<class T> class A {
553 ///     friend void foo<>(T);
554 ///   };
555 /// \endcode
556 class DependentFunctionTemplateSpecializationInfo final
557     : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
558                                     TemplateArgumentLoc,
559                                     FunctionTemplateDecl *> {
560   /// The number of potential template candidates.
561   unsigned NumTemplates;
562
563   /// The number of template arguments.
564   unsigned NumArgs;
565
566   /// The locations of the left and right angle brackets.
567   SourceRange AngleLocs;
568
569   size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
570     return NumArgs;
571   }
572   size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
573     return NumTemplates;
574   }
575
576   DependentFunctionTemplateSpecializationInfo(
577                                  const UnresolvedSetImpl &Templates,
578                                  const TemplateArgumentListInfo &TemplateArgs);
579
580 public:
581   static DependentFunctionTemplateSpecializationInfo *
582   Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
583          const TemplateArgumentListInfo &TemplateArgs);
584
585   /// \brief Returns the number of function templates that this might
586   /// be a specialization of.
587   unsigned getNumTemplates() const { return NumTemplates; }
588
589   /// \brief Returns the i'th template candidate.
590   FunctionTemplateDecl *getTemplate(unsigned I) const {
591     assert(I < getNumTemplates() && "template index out of range");
592     return getTrailingObjects<FunctionTemplateDecl *>()[I];
593   }
594
595   /// \brief Returns the explicit template arguments that were given.
596   const TemplateArgumentLoc *getTemplateArgs() const {
597     return getTrailingObjects<TemplateArgumentLoc>();
598   }
599
600   /// \brief Returns the number of explicit template arguments that were given.
601   unsigned getNumTemplateArgs() const { return NumArgs; }
602
603   /// \brief Returns the nth template argument.
604   const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
605     assert(I < getNumTemplateArgs() && "template arg index out of range");
606     return getTemplateArgs()[I];
607   }
608
609   SourceLocation getLAngleLoc() const {
610     return AngleLocs.getBegin();
611   }
612
613   SourceLocation getRAngleLoc() const {
614     return AngleLocs.getEnd();
615   }
616
617   friend TrailingObjects;
618 };
619
620 /// Declaration of a redeclarable template.
621 class RedeclarableTemplateDecl : public TemplateDecl, 
622                                  public Redeclarable<RedeclarableTemplateDecl> 
623 {
624   typedef Redeclarable<RedeclarableTemplateDecl> redeclarable_base;
625   RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
626     return getNextRedeclaration();
627   }
628   RedeclarableTemplateDecl *getPreviousDeclImpl() override {
629     return getPreviousDecl();
630   }
631   RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
632     return getMostRecentDecl();
633   }
634
635 protected:
636   template <typename EntryType> struct SpecEntryTraits {
637     typedef EntryType DeclType;
638
639     static DeclType *getDecl(EntryType *D) {
640       return D;
641     }
642     static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
643       return D->getTemplateArgs().asArray();
644     }
645   };
646
647   template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
648             typename DeclType = typename SETraits::DeclType>
649   struct SpecIterator
650       : llvm::iterator_adaptor_base<
651             SpecIterator<EntryType, SETraits, DeclType>,
652             typename llvm::FoldingSetVector<EntryType>::iterator,
653             typename std::iterator_traits<typename llvm::FoldingSetVector<
654                 EntryType>::iterator>::iterator_category,
655             DeclType *, ptrdiff_t, DeclType *, DeclType *> {
656     SpecIterator() {}
657     explicit SpecIterator(
658         typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
659         : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
660
661     DeclType *operator*() const {
662       return SETraits::getDecl(&*this->I)->getMostRecentDecl();
663     }
664     DeclType *operator->() const { return **this; }
665   };
666
667   template <typename EntryType>
668   static SpecIterator<EntryType>
669   makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
670     return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
671   }
672
673   template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
674   findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
675                          ArrayRef<TemplateArgument> Args, void *&InsertPos);
676
677   template <class Derived, class EntryType>
678   void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
679                              EntryType *Entry, void *InsertPos);
680
681   struct CommonBase {
682     CommonBase() : InstantiatedFromMember(nullptr, false) { }
683
684     /// \brief The template from which this was most
685     /// directly instantiated (or null).
686     ///
687     /// The boolean value indicates whether this template
688     /// was explicitly specialized.
689     llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
690       InstantiatedFromMember;
691   };
692
693   /// \brief Pointer to the common data shared by all declarations of this
694   /// template.
695   mutable CommonBase *Common;
696   
697   /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
698   /// the same template. Calling this routine may implicitly allocate memory
699   /// for the common pointer.
700   CommonBase *getCommonPtr() const;
701
702   virtual CommonBase *newCommon(ASTContext &C) const = 0;
703
704   // Construct a template decl with name, parameters, and templated element.
705   RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
706                            SourceLocation L, DeclarationName Name,
707                            TemplateParameterList *Params, NamedDecl *Decl)
708       : TemplateDecl(DK, DC, L, Name, Params, Decl), redeclarable_base(C),
709         Common() {}
710
711 public:
712   template <class decl_type> friend class RedeclarableTemplate;
713
714   /// \brief Retrieves the canonical declaration of this template.
715   RedeclarableTemplateDecl *getCanonicalDecl() override {
716     return getFirstDecl();
717   }
718   const RedeclarableTemplateDecl *getCanonicalDecl() const {
719     return getFirstDecl();
720   }
721
722   /// \brief Determines whether this template was a specialization of a
723   /// member template.
724   ///
725   /// In the following example, the function template \c X<int>::f and the
726   /// member template \c X<int>::Inner are member specializations.
727   ///
728   /// \code
729   /// template<typename T>
730   /// struct X {
731   ///   template<typename U> void f(T, U);
732   ///   template<typename U> struct Inner;
733   /// };
734   ///
735   /// template<> template<typename T>
736   /// void X<int>::f(int, T);
737   /// template<> template<typename T>
738   /// struct X<int>::Inner { /* ... */ };
739   /// \endcode
740   bool isMemberSpecialization() const {
741     return getCommonPtr()->InstantiatedFromMember.getInt();
742   }
743
744   /// \brief Note that this member template is a specialization.
745   void setMemberSpecialization() {
746     assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
747            "Only member templates can be member template specializations");
748     getCommonPtr()->InstantiatedFromMember.setInt(true);
749   }
750
751   /// \brief Retrieve the member template from which this template was
752   /// instantiated, or NULL if this template was not instantiated from a 
753   /// member template.
754   ///
755   /// A template is instantiated from a member template when the member 
756   /// template itself is part of a class template (or member thereof). For
757   /// example, given
758   ///
759   /// \code
760   /// template<typename T>
761   /// struct X {
762   ///   template<typename U> void f(T, U);
763   /// };
764   ///
765   /// void test(X<int> x) {
766   ///   x.f(1, 'a');
767   /// };
768   /// \endcode
769   ///
770   /// \c X<int>::f is a FunctionTemplateDecl that describes the function
771   /// template
772   ///
773   /// \code
774   /// template<typename U> void X<int>::f(int, U);
775   /// \endcode
776   ///
777   /// which was itself created during the instantiation of \c X<int>. Calling
778   /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
779   /// retrieve the FunctionTemplateDecl for the original template \c f within
780   /// the class template \c X<T>, i.e.,
781   ///
782   /// \code
783   /// template<typename T>
784   /// template<typename U>
785   /// void X<T>::f(T, U);
786   /// \endcode
787   RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
788     return getCommonPtr()->InstantiatedFromMember.getPointer();
789   }
790
791   void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
792     assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
793     getCommonPtr()->InstantiatedFromMember.setPointer(TD);
794   }
795
796   typedef redeclarable_base::redecl_range redecl_range;
797   typedef redeclarable_base::redecl_iterator redecl_iterator;
798   using redeclarable_base::redecls_begin;
799   using redeclarable_base::redecls_end;
800   using redeclarable_base::redecls;
801   using redeclarable_base::getPreviousDecl;
802   using redeclarable_base::getMostRecentDecl;
803   using redeclarable_base::isFirstDecl;
804
805   // Implement isa/cast/dyncast/etc.
806   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
807   static bool classofKind(Kind K) {
808     return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
809   }
810
811   friend class ASTReader;
812   friend class ASTDeclReader;
813   friend class ASTDeclWriter;
814 };
815
816 template <> struct RedeclarableTemplateDecl::
817 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
818   typedef FunctionDecl DeclType;
819
820   static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
821     return I->Function;
822   }
823   static ArrayRef<TemplateArgument>
824   getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
825     return I->TemplateArguments->asArray();
826   }
827 };
828
829 /// Declaration of a template function.
830 class FunctionTemplateDecl : public RedeclarableTemplateDecl {
831   static void DeallocateCommon(void *Ptr);
832
833 protected:
834   /// \brief Data that is common to all of the declarations of a given
835   /// function template.
836   struct Common : CommonBase {
837     Common() : InjectedArgs(), LazySpecializations() { }
838
839     /// \brief The function template specializations for this function
840     /// template, including explicit specializations and instantiations.
841     llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
842
843     /// \brief The set of "injected" template arguments used within this
844     /// function template.
845     ///
846     /// This pointer refers to the template arguments (there are as
847     /// many template arguments as template parameaters) for the function
848     /// template, and is allocated lazily, since most function templates do not
849     /// require the use of this information.
850     TemplateArgument *InjectedArgs;
851
852     /// \brief If non-null, points to an array of specializations known only
853     /// by their external declaration IDs.
854     ///
855     /// The first value in the array is the number of of specializations
856     /// that follow.
857     uint32_t *LazySpecializations;
858   };
859
860   FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
861                        DeclarationName Name, TemplateParameterList *Params,
862                        NamedDecl *Decl)
863       : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
864                                  Decl) {}
865
866   CommonBase *newCommon(ASTContext &C) const override;
867
868   Common *getCommonPtr() const {
869     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
870   }
871
872   friend class FunctionDecl;
873
874   /// \brief Retrieve the set of function template specializations of this
875   /// function template.
876   llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
877   getSpecializations() const;
878
879   /// \brief Add a specialization of this function template.
880   ///
881   /// \param InsertPos Insert position in the FoldingSetVector, must have been
882   ///        retrieved by an earlier call to findSpecialization().
883   void addSpecialization(FunctionTemplateSpecializationInfo* Info,
884                          void *InsertPos);
885
886 public:
887   /// \brief Load any lazily-loaded specializations from the external source.
888   void LoadLazySpecializations() const;
889
890   /// Get the underlying function declaration of the template.
891   FunctionDecl *getTemplatedDecl() const {
892     return static_cast<FunctionDecl*>(TemplatedDecl);
893   }
894
895   /// Returns whether this template declaration defines the primary
896   /// pattern.
897   bool isThisDeclarationADefinition() const {
898     return getTemplatedDecl()->isThisDeclarationADefinition();
899   }
900
901   /// \brief Return the specialization with the provided arguments if it exists,
902   /// otherwise return the insertion point.
903   FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
904                                    void *&InsertPos);
905
906   FunctionTemplateDecl *getCanonicalDecl() override {
907     return cast<FunctionTemplateDecl>(
908              RedeclarableTemplateDecl::getCanonicalDecl());
909   }
910   const FunctionTemplateDecl *getCanonicalDecl() const {
911     return cast<FunctionTemplateDecl>(
912              RedeclarableTemplateDecl::getCanonicalDecl());
913   }
914
915   /// \brief Retrieve the previous declaration of this function template, or
916   /// NULL if no such declaration exists.
917   FunctionTemplateDecl *getPreviousDecl() {
918     return cast_or_null<FunctionTemplateDecl>(
919              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
920   }
921
922   /// \brief Retrieve the previous declaration of this function template, or
923   /// NULL if no such declaration exists.
924   const FunctionTemplateDecl *getPreviousDecl() const {
925     return cast_or_null<FunctionTemplateDecl>(
926        static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
927   }
928
929   FunctionTemplateDecl *getMostRecentDecl() {
930     return cast<FunctionTemplateDecl>(
931         static_cast<RedeclarableTemplateDecl *>(this)
932             ->getMostRecentDecl());
933   }
934   const FunctionTemplateDecl *getMostRecentDecl() const {
935     return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
936   }
937
938   FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
939     return cast_or_null<FunctionTemplateDecl>(
940              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
941   }
942
943   typedef SpecIterator<FunctionTemplateSpecializationInfo> spec_iterator;
944   typedef llvm::iterator_range<spec_iterator> spec_range;
945
946   spec_range specializations() const {
947     return spec_range(spec_begin(), spec_end());
948   }
949   spec_iterator spec_begin() const {
950     return makeSpecIterator(getSpecializations(), false);
951   }
952
953   spec_iterator spec_end() const {
954     return makeSpecIterator(getSpecializations(), true);
955   }
956
957   /// \brief Retrieve the "injected" template arguments that correspond to the
958   /// template parameters of this function template.
959   ///
960   /// Although the C++ standard has no notion of the "injected" template
961   /// arguments for a function template, the notion is convenient when
962   /// we need to perform substitutions inside the definition of a function
963   /// template.
964   ArrayRef<TemplateArgument> getInjectedTemplateArgs();
965
966   /// \brief Create a function template node.
967   static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
968                                       SourceLocation L,
969                                       DeclarationName Name,
970                                       TemplateParameterList *Params,
971                                       NamedDecl *Decl);
972
973   /// \brief Create an empty function template node.
974   static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
975
976   // Implement isa/cast/dyncast support
977   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
978   static bool classofKind(Kind K) { return K == FunctionTemplate; }
979
980   friend class ASTDeclReader;
981   friend class ASTDeclWriter;
982 };
983
984 //===----------------------------------------------------------------------===//
985 // Kinds of Template Parameters
986 //===----------------------------------------------------------------------===//
987
988 /// \brief Defines the position of a template parameter within a template
989 /// parameter list.
990 ///
991 /// Because template parameter can be listed
992 /// sequentially for out-of-line template members, each template parameter is
993 /// given a Depth - the nesting of template parameter scopes - and a Position -
994 /// the occurrence within the parameter list.
995 /// This class is inheritedly privately by different kinds of template
996 /// parameters and is not part of the Decl hierarchy. Just a facility.
997 class TemplateParmPosition {
998   TemplateParmPosition() = delete;
999
1000 protected:
1001   TemplateParmPosition(unsigned D, unsigned P)
1002     : Depth(D), Position(P)
1003   { }
1004
1005   // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
1006   // position? Maybe?
1007   unsigned Depth;
1008   unsigned Position;
1009
1010 public:
1011   /// Get the nesting depth of the template parameter.
1012   unsigned getDepth() const { return Depth; }
1013   void setDepth(unsigned D) { Depth = D; }
1014
1015   /// Get the position of the template parameter within its parameter list.
1016   unsigned getPosition() const { return Position; }
1017   void setPosition(unsigned P) { Position = P; }
1018
1019   /// Get the index of the template parameter within its parameter list.
1020   unsigned getIndex() const { return Position; }
1021 };
1022
1023 /// \brief Declaration of a template type parameter.
1024 ///
1025 /// For example, "T" in
1026 /// \code
1027 /// template<typename T> class vector;
1028 /// \endcode
1029 class TemplateTypeParmDecl : public TypeDecl {
1030   /// \brief Whether this template type parameter was declaration with
1031   /// the 'typename' keyword.
1032   ///
1033   /// If false, it was declared with the 'class' keyword.
1034   bool Typename : 1;
1035
1036   /// \brief The default template argument, if any.
1037   typedef DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>
1038       DefArgStorage;
1039   DefArgStorage DefaultArgument;
1040
1041   TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
1042                        SourceLocation IdLoc, IdentifierInfo *Id,
1043                        bool Typename)
1044     : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
1045       DefaultArgument() { }
1046
1047   /// Sema creates these on the stack during auto type deduction.
1048   friend class Sema;
1049
1050 public:
1051   static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
1052                                       SourceLocation KeyLoc,
1053                                       SourceLocation NameLoc,
1054                                       unsigned D, unsigned P,
1055                                       IdentifierInfo *Id, bool Typename,
1056                                       bool ParameterPack);
1057   static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, 
1058                                                   unsigned ID);
1059
1060   /// \brief Whether this template type parameter was declared with
1061   /// the 'typename' keyword.
1062   ///
1063   /// If not, it was declared with the 'class' keyword.
1064   bool wasDeclaredWithTypename() const { return Typename; }
1065
1066   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1067
1068   /// \brief Determine whether this template parameter has a default
1069   /// argument.
1070   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1071
1072   /// \brief Retrieve the default argument, if any.
1073   QualType getDefaultArgument() const {
1074     return DefaultArgument.get()->getType();
1075   }
1076
1077   /// \brief Retrieves the default argument's source information, if any.
1078   TypeSourceInfo *getDefaultArgumentInfo() const {
1079     return DefaultArgument.get();
1080   }
1081
1082   /// \brief Retrieves the location of the default argument declaration.
1083   SourceLocation getDefaultArgumentLoc() const;
1084
1085   /// \brief Determines whether the default argument was inherited
1086   /// from a previous declaration of this template.
1087   bool defaultArgumentWasInherited() const {
1088     return DefaultArgument.isInherited();
1089   }
1090
1091   /// \brief Set the default argument for this template parameter.
1092   void setDefaultArgument(TypeSourceInfo *DefArg) {
1093     DefaultArgument.set(DefArg);
1094   }
1095   /// \brief Set that this default argument was inherited from another
1096   /// parameter.
1097   void setInheritedDefaultArgument(const ASTContext &C,
1098                                    TemplateTypeParmDecl *Prev) {
1099     DefaultArgument.setInherited(C, Prev);
1100   }
1101
1102   /// \brief Removes the default argument of this template parameter.
1103   void removeDefaultArgument() {
1104     DefaultArgument.clear();
1105   }
1106
1107   /// \brief Set whether this template type parameter was declared with
1108   /// the 'typename' or 'class' keyword.
1109   void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1110
1111   /// \brief Retrieve the depth of the template parameter.
1112   unsigned getDepth() const;
1113
1114   /// \brief Retrieve the index of the template parameter.
1115   unsigned getIndex() const;
1116
1117   /// \brief Returns whether this is a parameter pack.
1118   bool isParameterPack() const;
1119
1120   SourceRange getSourceRange() const override LLVM_READONLY;
1121
1122   // Implement isa/cast/dyncast/etc.
1123   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1124   static bool classofKind(Kind K) { return K == TemplateTypeParm; }
1125 };
1126
1127 /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
1128 /// e.g., "Size" in
1129 /// @code
1130 /// template<int Size> class array { };
1131 /// @endcode
1132 class NonTypeTemplateParmDecl final
1133     : public DeclaratorDecl,
1134       protected TemplateParmPosition,
1135       private llvm::TrailingObjects<NonTypeTemplateParmDecl,
1136                                     std::pair<QualType, TypeSourceInfo *>> {
1137   /// \brief The default template argument, if any, and whether or not
1138   /// it was inherited.
1139   typedef DefaultArgStorage<NonTypeTemplateParmDecl, Expr*> DefArgStorage;
1140   DefArgStorage DefaultArgument;
1141
1142   // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
1143   // down here to save memory.
1144
1145   /// \brief Whether this non-type template parameter is a parameter pack.
1146   bool ParameterPack;
1147
1148   /// \brief Whether this non-type template parameter is an "expanded"
1149   /// parameter pack, meaning that its type is a pack expansion and we
1150   /// already know the set of types that expansion expands to.
1151   bool ExpandedParameterPack;
1152
1153   /// \brief The number of types in an expanded parameter pack.
1154   unsigned NumExpandedTypes;
1155
1156   size_t numTrailingObjects(
1157       OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
1158     return NumExpandedTypes;
1159   }
1160
1161   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1162                           SourceLocation IdLoc, unsigned D, unsigned P,
1163                           IdentifierInfo *Id, QualType T,
1164                           bool ParameterPack, TypeSourceInfo *TInfo)
1165     : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
1166       TemplateParmPosition(D, P), ParameterPack(ParameterPack),
1167       ExpandedParameterPack(false), NumExpandedTypes(0)
1168   { }
1169
1170   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1171                           SourceLocation IdLoc, unsigned D, unsigned P,
1172                           IdentifierInfo *Id, QualType T,
1173                           TypeSourceInfo *TInfo,
1174                           const QualType *ExpandedTypes,
1175                           unsigned NumExpandedTypes,
1176                           TypeSourceInfo **ExpandedTInfos);
1177
1178   friend class ASTDeclReader;
1179   friend TrailingObjects;
1180
1181 public:
1182   static NonTypeTemplateParmDecl *
1183   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1184          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1185          QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
1186
1187   static NonTypeTemplateParmDecl *
1188   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1189          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1190          QualType T, TypeSourceInfo *TInfo,
1191          const QualType *ExpandedTypes, unsigned NumExpandedTypes,
1192          TypeSourceInfo **ExpandedTInfos);
1193
1194   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, 
1195                                                      unsigned ID);
1196   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, 
1197                                                      unsigned ID,
1198                                                      unsigned NumExpandedTypes);
1199     
1200   using TemplateParmPosition::getDepth;
1201   using TemplateParmPosition::setDepth;
1202   using TemplateParmPosition::getPosition;
1203   using TemplateParmPosition::setPosition;
1204   using TemplateParmPosition::getIndex;
1205
1206   SourceRange getSourceRange() const override LLVM_READONLY;
1207
1208   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1209
1210   /// \brief Determine whether this template parameter has a default
1211   /// argument.
1212   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1213
1214   /// \brief Retrieve the default argument, if any.
1215   Expr *getDefaultArgument() const { return DefaultArgument.get(); }
1216
1217   /// \brief Retrieve the location of the default argument, if any.
1218   SourceLocation getDefaultArgumentLoc() const;
1219
1220   /// \brief Determines whether the default argument was inherited
1221   /// from a previous declaration of this template.
1222   bool defaultArgumentWasInherited() const {
1223     return DefaultArgument.isInherited();
1224   }
1225
1226   /// \brief Set the default argument for this template parameter, and
1227   /// whether that default argument was inherited from another
1228   /// declaration.
1229   void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
1230   void setInheritedDefaultArgument(const ASTContext &C,
1231                                    NonTypeTemplateParmDecl *Parm) {
1232     DefaultArgument.setInherited(C, Parm);
1233   }
1234
1235   /// \brief Removes the default argument of this template parameter.
1236   void removeDefaultArgument() { DefaultArgument.clear(); }
1237
1238   /// \brief Whether this parameter is a non-type template parameter pack.
1239   ///
1240   /// If the parameter is a parameter pack, the type may be a
1241   /// \c PackExpansionType. In the following example, the \c Dims parameter
1242   /// is a parameter pack (whose type is 'unsigned').
1243   ///
1244   /// \code
1245   /// template<typename T, unsigned ...Dims> struct multi_array;
1246   /// \endcode
1247   bool isParameterPack() const { return ParameterPack; }
1248
1249   /// \brief Whether this parameter pack is a pack expansion.
1250   ///
1251   /// A non-type template parameter pack is a pack expansion if its type
1252   /// contains an unexpanded parameter pack. In this case, we will have
1253   /// built a PackExpansionType wrapping the type.
1254   bool isPackExpansion() const {
1255     return ParameterPack && getType()->getAs<PackExpansionType>();
1256   }
1257
1258   /// \brief Whether this parameter is a non-type template parameter pack
1259   /// that has a known list of different types at different positions.
1260   ///
1261   /// A parameter pack is an expanded parameter pack when the original
1262   /// parameter pack's type was itself a pack expansion, and that expansion
1263   /// has already been expanded. For example, given:
1264   ///
1265   /// \code
1266   /// template<typename ...Types>
1267   /// struct X {
1268   ///   template<Types ...Values>
1269   ///   struct Y { /* ... */ };
1270   /// };
1271   /// \endcode
1272   ///
1273   /// The parameter pack \c Values has a \c PackExpansionType as its type,
1274   /// which expands \c Types. When \c Types is supplied with template arguments
1275   /// by instantiating \c X, the instantiation of \c Values becomes an
1276   /// expanded parameter pack. For example, instantiating
1277   /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1278   /// pack with expansion types \c int and \c unsigned int.
1279   ///
1280   /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1281   /// return the expansion types.
1282   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1283
1284   /// \brief Retrieves the number of expansion types in an expanded parameter
1285   /// pack.
1286   unsigned getNumExpansionTypes() const {
1287     assert(ExpandedParameterPack && "Not an expansion parameter pack");
1288     return NumExpandedTypes;
1289   }
1290
1291   /// \brief Retrieve a particular expansion type within an expanded parameter
1292   /// pack.
1293   QualType getExpansionType(unsigned I) const {
1294     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1295     auto TypesAndInfos =
1296         getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1297     return TypesAndInfos[I].first;
1298   }
1299
1300   /// \brief Retrieve a particular expansion type source info within an
1301   /// expanded parameter pack.
1302   TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1303     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1304     auto TypesAndInfos =
1305         getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1306     return TypesAndInfos[I].second;
1307   }
1308
1309   // Implement isa/cast/dyncast/etc.
1310   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1311   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1312 };
1313
1314 /// TemplateTemplateParmDecl - Declares a template template parameter,
1315 /// e.g., "T" in
1316 /// @code
1317 /// template <template <typename> class T> class container { };
1318 /// @endcode
1319 /// A template template parameter is a TemplateDecl because it defines the
1320 /// name of a template and the template parameters allowable for substitution.
1321 class TemplateTemplateParmDecl final
1322     : public TemplateDecl,
1323       protected TemplateParmPosition,
1324       private llvm::TrailingObjects<TemplateTemplateParmDecl,
1325                                     TemplateParameterList *> {
1326   void anchor() override;
1327
1328   /// \brief The default template argument, if any.
1329   typedef DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>
1330       DefArgStorage;
1331   DefArgStorage DefaultArgument;
1332
1333   /// \brief Whether this parameter is a parameter pack.
1334   bool ParameterPack;
1335
1336   /// \brief Whether this template template parameter is an "expanded"
1337   /// parameter pack, meaning that it is a pack expansion and we
1338   /// already know the set of template parameters that expansion expands to.
1339   bool ExpandedParameterPack;
1340
1341   /// \brief The number of parameters in an expanded parameter pack.
1342   unsigned NumExpandedParams;
1343
1344   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1345                            unsigned D, unsigned P, bool ParameterPack,
1346                            IdentifierInfo *Id, TemplateParameterList *Params)
1347     : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1348       TemplateParmPosition(D, P), ParameterPack(ParameterPack),
1349       ExpandedParameterPack(false), NumExpandedParams(0)
1350     { }
1351
1352   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1353                            unsigned D, unsigned P,
1354                            IdentifierInfo *Id, TemplateParameterList *Params,
1355                            unsigned NumExpansions,
1356                            TemplateParameterList * const *Expansions);
1357
1358 public:
1359   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1360                                           SourceLocation L, unsigned D,
1361                                           unsigned P, bool ParameterPack,
1362                                           IdentifierInfo *Id,
1363                                           TemplateParameterList *Params);
1364   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1365                                           SourceLocation L, unsigned D,
1366                                           unsigned P,
1367                                           IdentifierInfo *Id,
1368                                           TemplateParameterList *Params,
1369                                  ArrayRef<TemplateParameterList *> Expansions);
1370
1371   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1372                                                       unsigned ID);
1373   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1374                                                       unsigned ID,
1375                                                       unsigned NumExpansions);
1376   
1377   using TemplateParmPosition::getDepth;
1378   using TemplateParmPosition::getPosition;
1379   using TemplateParmPosition::getIndex;
1380
1381   /// \brief Whether this template template parameter is a template
1382   /// parameter pack.
1383   ///
1384   /// \code
1385   /// template<template <class T> ...MetaFunctions> struct Apply;
1386   /// \endcode
1387   bool isParameterPack() const { return ParameterPack; }
1388
1389   /// \brief Whether this parameter pack is a pack expansion.
1390   ///
1391   /// A template template parameter pack is a pack expansion if its template
1392   /// parameter list contains an unexpanded parameter pack.
1393   bool isPackExpansion() const {
1394     return ParameterPack &&
1395            getTemplateParameters()->containsUnexpandedParameterPack();
1396   }
1397
1398   /// \brief Whether this parameter is a template template parameter pack that
1399   /// has a known list of different template parameter lists at different
1400   /// positions.
1401   ///
1402   /// A parameter pack is an expanded parameter pack when the original parameter
1403   /// pack's template parameter list was itself a pack expansion, and that
1404   /// expansion has already been expanded. For exampe, given:
1405   ///
1406   /// \code
1407   /// template<typename...Types> struct Outer {
1408   ///   template<template<Types> class...Templates> struct Inner;
1409   /// };
1410   /// \endcode
1411   ///
1412   /// The parameter pack \c Templates is a pack expansion, which expands the
1413   /// pack \c Types. When \c Types is supplied with template arguments by
1414   /// instantiating \c Outer, the instantiation of \c Templates is an expanded
1415   /// parameter pack.
1416   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1417
1418   /// \brief Retrieves the number of expansion template parameters in
1419   /// an expanded parameter pack.
1420   unsigned getNumExpansionTemplateParameters() const {
1421     assert(ExpandedParameterPack && "Not an expansion parameter pack");
1422     return NumExpandedParams;
1423   }
1424
1425   /// \brief Retrieve a particular expansion type within an expanded parameter
1426   /// pack.
1427   TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
1428     assert(I < NumExpandedParams && "Out-of-range expansion type index");
1429     return getTrailingObjects<TemplateParameterList *>()[I];
1430   }
1431
1432   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1433
1434   /// \brief Determine whether this template parameter has a default
1435   /// argument.
1436   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1437
1438   /// \brief Retrieve the default argument, if any.
1439   const TemplateArgumentLoc &getDefaultArgument() const {
1440     static const TemplateArgumentLoc None;
1441     return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
1442   }
1443
1444   /// \brief Retrieve the location of the default argument, if any.
1445   SourceLocation getDefaultArgumentLoc() const;
1446
1447   /// \brief Determines whether the default argument was inherited
1448   /// from a previous declaration of this template.
1449   bool defaultArgumentWasInherited() const {
1450     return DefaultArgument.isInherited();
1451   }
1452
1453   /// \brief Set the default argument for this template parameter, and
1454   /// whether that default argument was inherited from another
1455   /// declaration.
1456   void setDefaultArgument(const ASTContext &C,
1457                           const TemplateArgumentLoc &DefArg);
1458   void setInheritedDefaultArgument(const ASTContext &C,
1459                                    TemplateTemplateParmDecl *Prev) {
1460     DefaultArgument.setInherited(C, Prev);
1461   }
1462
1463   /// \brief Removes the default argument of this template parameter.
1464   void removeDefaultArgument() { DefaultArgument.clear(); }
1465
1466   SourceRange getSourceRange() const override LLVM_READONLY {
1467     SourceLocation End = getLocation();
1468     if (hasDefaultArgument() && !defaultArgumentWasInherited())
1469       End = getDefaultArgument().getSourceRange().getEnd();
1470     return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1471   }
1472
1473   // Implement isa/cast/dyncast/etc.
1474   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1475   static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1476
1477   friend class ASTDeclReader;
1478   friend class ASTDeclWriter;
1479   friend TrailingObjects;
1480 };
1481
1482 /// \brief Represents the builtin template declaration which is used to
1483 /// implement __make_integer_seq.  It serves no real purpose beyond existing as
1484 /// a place to hold template parameters.
1485 class BuiltinTemplateDecl : public TemplateDecl {
1486   void anchor() override;
1487
1488   BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
1489                       DeclarationName Name, BuiltinTemplateKind BTK);
1490
1491   BuiltinTemplateKind BTK;
1492
1493 public:
1494   // Implement isa/cast/dyncast support
1495   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1496   static bool classofKind(Kind K) { return K == BuiltinTemplate; }
1497
1498   static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
1499                                      DeclarationName Name,
1500                                      BuiltinTemplateKind BTK) {
1501     return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
1502   }
1503
1504   SourceRange getSourceRange() const override LLVM_READONLY {
1505     return SourceRange();
1506   }
1507
1508   BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
1509 };
1510
1511 /// \brief Represents a class template specialization, which refers to
1512 /// a class template with a given set of template arguments.
1513 ///
1514 /// Class template specializations represent both explicit
1515 /// specialization of class templates, as in the example below, and
1516 /// implicit instantiations of class templates.
1517 ///
1518 /// \code
1519 /// template<typename T> class array;
1520 ///
1521 /// template<>
1522 /// class array<bool> { }; // class template specialization array<bool>
1523 /// \endcode
1524 class ClassTemplateSpecializationDecl
1525   : public CXXRecordDecl, public llvm::FoldingSetNode {
1526
1527   /// \brief Structure that stores information about a class template
1528   /// specialization that was instantiated from a class template partial
1529   /// specialization.
1530   struct SpecializedPartialSpecialization {
1531     /// \brief The class template partial specialization from which this
1532     /// class template specialization was instantiated.
1533     ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1534
1535     /// \brief The template argument list deduced for the class template
1536     /// partial specialization itself.
1537     const TemplateArgumentList *TemplateArgs;
1538   };
1539
1540   /// \brief The template that this specialization specializes
1541   llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1542     SpecializedTemplate;
1543
1544   /// \brief Further info for explicit template specialization/instantiation.
1545   struct ExplicitSpecializationInfo {
1546     /// \brief The type-as-written.
1547     TypeSourceInfo *TypeAsWritten;
1548     /// \brief The location of the extern keyword.
1549     SourceLocation ExternLoc;
1550     /// \brief The location of the template keyword.
1551     SourceLocation TemplateKeywordLoc;
1552
1553     ExplicitSpecializationInfo()
1554       : TypeAsWritten(nullptr), ExternLoc(), TemplateKeywordLoc() {}
1555   };
1556
1557   /// \brief Further info for explicit template specialization/instantiation.
1558   /// Does not apply to implicit specializations.
1559   ExplicitSpecializationInfo *ExplicitInfo;
1560
1561   /// \brief The template arguments used to describe this specialization.
1562   const TemplateArgumentList *TemplateArgs;
1563
1564   /// \brief The point where this template was instantiated (if any)
1565   SourceLocation PointOfInstantiation;
1566
1567   /// \brief The kind of specialization this declaration refers to.
1568   /// Really a value of type TemplateSpecializationKind.
1569   unsigned SpecializationKind : 3;
1570
1571 protected:
1572   ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1573                                   DeclContext *DC, SourceLocation StartLoc,
1574                                   SourceLocation IdLoc,
1575                                   ClassTemplateDecl *SpecializedTemplate,
1576                                   const TemplateArgument *Args,
1577                                   unsigned NumArgs,
1578                                   ClassTemplateSpecializationDecl *PrevDecl);
1579
1580   explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
1581
1582 public:
1583   static ClassTemplateSpecializationDecl *
1584   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1585          SourceLocation StartLoc, SourceLocation IdLoc,
1586          ClassTemplateDecl *SpecializedTemplate,
1587          const TemplateArgument *Args,
1588          unsigned NumArgs,
1589          ClassTemplateSpecializationDecl *PrevDecl);
1590   static ClassTemplateSpecializationDecl *
1591   CreateDeserialized(ASTContext &C, unsigned ID);
1592
1593   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1594                             bool Qualified) const override;
1595
1596   // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
1597   // different "most recent" declaration from this function for the same
1598   // declaration, because we don't override getMostRecentDeclImpl(). But
1599   // it's not clear that we should override that, because the most recent
1600   // declaration as a CXXRecordDecl sometimes is the injected-class-name.
1601   ClassTemplateSpecializationDecl *getMostRecentDecl() {
1602     CXXRecordDecl *Recent = static_cast<CXXRecordDecl *>(
1603                               this)->getMostRecentDecl();
1604     while (!isa<ClassTemplateSpecializationDecl>(Recent)) {
1605       // FIXME: Does injected class name need to be in the redeclarations chain?
1606       assert(Recent->isInjectedClassName() && Recent->getPreviousDecl());
1607       Recent = Recent->getPreviousDecl();
1608     }
1609     return cast<ClassTemplateSpecializationDecl>(Recent);
1610   }
1611
1612   /// \brief Retrieve the template that this specialization specializes.
1613   ClassTemplateDecl *getSpecializedTemplate() const;
1614
1615   /// \brief Retrieve the template arguments of the class template
1616   /// specialization.
1617   const TemplateArgumentList &getTemplateArgs() const {
1618     return *TemplateArgs;
1619   }
1620
1621   /// \brief Determine the kind of specialization that this
1622   /// declaration represents.
1623   TemplateSpecializationKind getSpecializationKind() const {
1624     return static_cast<TemplateSpecializationKind>(SpecializationKind);
1625   }
1626
1627   bool isExplicitSpecialization() const {
1628     return getSpecializationKind() == TSK_ExplicitSpecialization;
1629   }
1630
1631   /// \brief True if this declaration is an explicit specialization,
1632   /// explicit instantiation declaration, or explicit instantiation
1633   /// definition.
1634   bool isExplicitInstantiationOrSpecialization() const {
1635     return isTemplateExplicitInstantiationOrSpecialization(
1636         getTemplateSpecializationKind());
1637   }
1638
1639   void setSpecializationKind(TemplateSpecializationKind TSK) {
1640     SpecializationKind = TSK;
1641   }
1642
1643   /// \brief Get the point of instantiation (if any), or null if none.
1644   SourceLocation getPointOfInstantiation() const {
1645     return PointOfInstantiation;
1646   }
1647
1648   void setPointOfInstantiation(SourceLocation Loc) {
1649     assert(Loc.isValid() && "point of instantiation must be valid!");
1650     PointOfInstantiation = Loc;
1651   }
1652
1653   /// \brief If this class template specialization is an instantiation of
1654   /// a template (rather than an explicit specialization), return the
1655   /// class template or class template partial specialization from which it
1656   /// was instantiated.
1657   llvm::PointerUnion<ClassTemplateDecl *,
1658                      ClassTemplatePartialSpecializationDecl *>
1659   getInstantiatedFrom() const {
1660     if (!isTemplateInstantiation(getSpecializationKind()))
1661       return llvm::PointerUnion<ClassTemplateDecl *,
1662                                 ClassTemplatePartialSpecializationDecl *>();
1663
1664     return getSpecializedTemplateOrPartial();
1665   }
1666
1667   /// \brief Retrieve the class template or class template partial
1668   /// specialization which was specialized by this.
1669   llvm::PointerUnion<ClassTemplateDecl *,
1670                      ClassTemplatePartialSpecializationDecl *>
1671   getSpecializedTemplateOrPartial() const {
1672     if (SpecializedPartialSpecialization *PartialSpec
1673           = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1674       return PartialSpec->PartialSpecialization;
1675
1676     return SpecializedTemplate.get<ClassTemplateDecl*>();
1677   }
1678
1679   /// \brief Retrieve the set of template arguments that should be used
1680   /// to instantiate members of the class template or class template partial
1681   /// specialization from which this class template specialization was
1682   /// instantiated.
1683   ///
1684   /// \returns For a class template specialization instantiated from the primary
1685   /// template, this function will return the same template arguments as
1686   /// getTemplateArgs(). For a class template specialization instantiated from
1687   /// a class template partial specialization, this function will return the
1688   /// deduced template arguments for the class template partial specialization
1689   /// itself.
1690   const TemplateArgumentList &getTemplateInstantiationArgs() const {
1691     if (SpecializedPartialSpecialization *PartialSpec
1692         = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1693       return *PartialSpec->TemplateArgs;
1694
1695     return getTemplateArgs();
1696   }
1697
1698   /// \brief Note that this class template specialization is actually an
1699   /// instantiation of the given class template partial specialization whose
1700   /// template arguments have been deduced.
1701   void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1702                           const TemplateArgumentList *TemplateArgs) {
1703     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1704            "Already set to a class template partial specialization!");
1705     SpecializedPartialSpecialization *PS
1706       = new (getASTContext()) SpecializedPartialSpecialization();
1707     PS->PartialSpecialization = PartialSpec;
1708     PS->TemplateArgs = TemplateArgs;
1709     SpecializedTemplate = PS;
1710   }
1711
1712   /// \brief Note that this class template specialization is an instantiation
1713   /// of the given class template.
1714   void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1715     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1716            "Previously set to a class template partial specialization!");
1717     SpecializedTemplate = TemplDecl;
1718   }
1719
1720   /// \brief Sets the type of this specialization as it was written by
1721   /// the user. This will be a class template specialization type.
1722   void setTypeAsWritten(TypeSourceInfo *T) {
1723     if (!ExplicitInfo)
1724       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1725     ExplicitInfo->TypeAsWritten = T;
1726   }
1727   /// \brief Gets the type of this specialization as it was written by
1728   /// the user, if it was so written.
1729   TypeSourceInfo *getTypeAsWritten() const {
1730     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
1731   }
1732
1733   /// \brief Gets the location of the extern keyword, if present.
1734   SourceLocation getExternLoc() const {
1735     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1736   }
1737   /// \brief Sets the location of the extern keyword.
1738   void setExternLoc(SourceLocation Loc) {
1739     if (!ExplicitInfo)
1740       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1741     ExplicitInfo->ExternLoc = Loc;
1742   }
1743
1744   /// \brief Sets the location of the template keyword.
1745   void setTemplateKeywordLoc(SourceLocation Loc) {
1746     if (!ExplicitInfo)
1747       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1748     ExplicitInfo->TemplateKeywordLoc = Loc;
1749   }
1750   /// \brief Gets the location of the template keyword, if present.
1751   SourceLocation getTemplateKeywordLoc() const {
1752     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1753   }
1754
1755   SourceRange getSourceRange() const override LLVM_READONLY;
1756
1757   void Profile(llvm::FoldingSetNodeID &ID) const {
1758     Profile(ID, TemplateArgs->asArray(), getASTContext());
1759   }
1760
1761   static void
1762   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
1763           ASTContext &Context) {
1764     ID.AddInteger(TemplateArgs.size());
1765     for (unsigned Arg = 0; Arg != TemplateArgs.size(); ++Arg)
1766       TemplateArgs[Arg].Profile(ID, Context);
1767   }
1768
1769   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1770   static bool classofKind(Kind K) {
1771     return K >= firstClassTemplateSpecialization &&
1772            K <= lastClassTemplateSpecialization;
1773   }
1774
1775   friend class ASTDeclReader;
1776   friend class ASTDeclWriter;
1777 };
1778
1779 class ClassTemplatePartialSpecializationDecl
1780   : public ClassTemplateSpecializationDecl {
1781   void anchor() override;
1782
1783   /// \brief The list of template parameters
1784   TemplateParameterList* TemplateParams;
1785
1786   /// \brief The source info for the template arguments as written.
1787   /// FIXME: redundant with TypeAsWritten?
1788   const ASTTemplateArgumentListInfo *ArgsAsWritten;
1789
1790   /// \brief The class template partial specialization from which this
1791   /// class template partial specialization was instantiated.
1792   ///
1793   /// The boolean value will be true to indicate that this class template
1794   /// partial specialization was specialized at this level.
1795   llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1796       InstantiatedFromMember;
1797
1798   ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1799                                          DeclContext *DC,
1800                                          SourceLocation StartLoc,
1801                                          SourceLocation IdLoc,
1802                                          TemplateParameterList *Params,
1803                                          ClassTemplateDecl *SpecializedTemplate,
1804                                          const TemplateArgument *Args,
1805                                          unsigned NumArgs,
1806                                const ASTTemplateArgumentListInfo *ArgsAsWritten,
1807                                ClassTemplatePartialSpecializationDecl *PrevDecl);
1808
1809   ClassTemplatePartialSpecializationDecl(ASTContext &C)
1810     : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
1811       TemplateParams(nullptr), ArgsAsWritten(nullptr),
1812       InstantiatedFromMember(nullptr, false) {}
1813
1814 public:
1815   static ClassTemplatePartialSpecializationDecl *
1816   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1817          SourceLocation StartLoc, SourceLocation IdLoc,
1818          TemplateParameterList *Params,
1819          ClassTemplateDecl *SpecializedTemplate,
1820          const TemplateArgument *Args,
1821          unsigned NumArgs,
1822          const TemplateArgumentListInfo &ArgInfos,
1823          QualType CanonInjectedType,
1824          ClassTemplatePartialSpecializationDecl *PrevDecl);
1825
1826   static ClassTemplatePartialSpecializationDecl *
1827   CreateDeserialized(ASTContext &C, unsigned ID);
1828
1829   ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
1830     return cast<ClassTemplatePartialSpecializationDecl>(
1831              static_cast<ClassTemplateSpecializationDecl *>(
1832                this)->getMostRecentDecl());
1833   }
1834
1835   /// Get the list of template parameters
1836   TemplateParameterList *getTemplateParameters() const {
1837     return TemplateParams;
1838   }
1839
1840   /// Get the template arguments as written.
1841   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
1842     return ArgsAsWritten;
1843   }
1844
1845   /// \brief Retrieve the member class template partial specialization from
1846   /// which this particular class template partial specialization was
1847   /// instantiated.
1848   ///
1849   /// \code
1850   /// template<typename T>
1851   /// struct Outer {
1852   ///   template<typename U> struct Inner;
1853   ///   template<typename U> struct Inner<U*> { }; // #1
1854   /// };
1855   ///
1856   /// Outer<float>::Inner<int*> ii;
1857   /// \endcode
1858   ///
1859   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
1860   /// end up instantiating the partial specialization
1861   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
1862   /// template partial specialization \c Outer<T>::Inner<U*>. Given
1863   /// \c Outer<float>::Inner<U*>, this function would return
1864   /// \c Outer<T>::Inner<U*>.
1865   ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
1866     const ClassTemplatePartialSpecializationDecl *First =
1867         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1868     return First->InstantiatedFromMember.getPointer();
1869   }
1870
1871   void setInstantiatedFromMember(
1872                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
1873     ClassTemplatePartialSpecializationDecl *First =
1874         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1875     First->InstantiatedFromMember.setPointer(PartialSpec);
1876   }
1877
1878   /// \brief Determines whether this class template partial specialization
1879   /// template was a specialization of a member partial specialization.
1880   ///
1881   /// In the following example, the member template partial specialization
1882   /// \c X<int>::Inner<T*> is a member specialization.
1883   ///
1884   /// \code
1885   /// template<typename T>
1886   /// struct X {
1887   ///   template<typename U> struct Inner;
1888   ///   template<typename U> struct Inner<U*>;
1889   /// };
1890   ///
1891   /// template<> template<typename T>
1892   /// struct X<int>::Inner<T*> { /* ... */ };
1893   /// \endcode
1894   bool isMemberSpecialization() {
1895     ClassTemplatePartialSpecializationDecl *First =
1896         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1897     return First->InstantiatedFromMember.getInt();
1898   }
1899
1900   /// \brief Note that this member template is a specialization.
1901   void setMemberSpecialization() {
1902     ClassTemplatePartialSpecializationDecl *First =
1903         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1904     assert(First->InstantiatedFromMember.getPointer() &&
1905            "Only member templates can be member template specializations");
1906     return First->InstantiatedFromMember.setInt(true);
1907   }
1908
1909   /// Retrieves the injected specialization type for this partial
1910   /// specialization.  This is not the same as the type-decl-type for
1911   /// this partial specialization, which is an InjectedClassNameType.
1912   QualType getInjectedSpecializationType() const {
1913     assert(getTypeForDecl() && "partial specialization has no type set!");
1914     return cast<InjectedClassNameType>(getTypeForDecl())
1915              ->getInjectedSpecializationType();
1916   }
1917
1918   // FIXME: Add Profile support!
1919
1920   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1921   static bool classofKind(Kind K) {
1922     return K == ClassTemplatePartialSpecialization;
1923   }
1924
1925   friend class ASTDeclReader;
1926   friend class ASTDeclWriter;
1927 };
1928
1929 /// Declaration of a class template.
1930 class ClassTemplateDecl : public RedeclarableTemplateDecl {
1931   static void DeallocateCommon(void *Ptr);
1932
1933 protected:
1934   /// \brief Data that is common to all of the declarations of a given
1935   /// class template.
1936   struct Common : CommonBase {
1937     Common() : LazySpecializations() { }
1938
1939     /// \brief The class template specializations for this class
1940     /// template, including explicit specializations and instantiations.
1941     llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
1942
1943     /// \brief The class template partial specializations for this class
1944     /// template.
1945     llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
1946       PartialSpecializations;
1947
1948     /// \brief The injected-class-name type for this class template.
1949     QualType InjectedClassNameType;
1950
1951     /// \brief If non-null, points to an array of specializations (including
1952     /// partial specializations) known only by their external declaration IDs.
1953     ///
1954     /// The first value in the array is the number of of specializations/
1955     /// partial specializations that follow.
1956     uint32_t *LazySpecializations;
1957   };
1958
1959   /// \brief Retrieve the set of specializations of this class template.
1960   llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
1961   getSpecializations() const;
1962
1963   /// \brief Retrieve the set of partial specializations of this class
1964   /// template.
1965   llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
1966   getPartialSpecializations();
1967
1968   ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
1969                     DeclarationName Name, TemplateParameterList *Params,
1970                     NamedDecl *Decl)
1971       : RedeclarableTemplateDecl(ClassTemplate, C, DC, L, Name, Params, Decl) {}
1972
1973   CommonBase *newCommon(ASTContext &C) const override;
1974
1975   Common *getCommonPtr() const {
1976     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1977   }
1978
1979 public:
1980   /// \brief Load any lazily-loaded specializations from the external source.
1981   void LoadLazySpecializations() const;
1982
1983   /// \brief Get the underlying class declarations of the template.
1984   CXXRecordDecl *getTemplatedDecl() const {
1985     return static_cast<CXXRecordDecl *>(TemplatedDecl);
1986   }
1987
1988   /// \brief Returns whether this template declaration defines the primary
1989   /// class pattern.
1990   bool isThisDeclarationADefinition() const {
1991     return getTemplatedDecl()->isThisDeclarationADefinition();
1992   }
1993
1994   /// \brief Create a class template node.
1995   static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1996                                    SourceLocation L,
1997                                    DeclarationName Name,
1998                                    TemplateParameterList *Params,
1999                                    NamedDecl *Decl,
2000                                    ClassTemplateDecl *PrevDecl);
2001
2002   /// \brief Create an empty class template node.
2003   static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2004
2005   /// \brief Return the specialization with the provided arguments if it exists,
2006   /// otherwise return the insertion point.
2007   ClassTemplateSpecializationDecl *
2008   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2009
2010   /// \brief Insert the specified specialization knowing that it is not already
2011   /// in. InsertPos must be obtained from findSpecialization.
2012   void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
2013
2014   ClassTemplateDecl *getCanonicalDecl() override {
2015     return cast<ClassTemplateDecl>(
2016              RedeclarableTemplateDecl::getCanonicalDecl());
2017   }
2018   const ClassTemplateDecl *getCanonicalDecl() const {
2019     return cast<ClassTemplateDecl>(
2020              RedeclarableTemplateDecl::getCanonicalDecl());
2021   }
2022
2023   /// \brief Retrieve the previous declaration of this class template, or
2024   /// NULL if no such declaration exists.
2025   ClassTemplateDecl *getPreviousDecl() {
2026     return cast_or_null<ClassTemplateDecl>(
2027              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2028   }
2029
2030   /// \brief Retrieve the previous declaration of this class template, or
2031   /// NULL if no such declaration exists.
2032   const ClassTemplateDecl *getPreviousDecl() const {
2033     return cast_or_null<ClassTemplateDecl>(
2034              static_cast<const RedeclarableTemplateDecl *>(
2035                this)->getPreviousDecl());
2036   }
2037
2038   ClassTemplateDecl *getMostRecentDecl() {
2039     return cast<ClassTemplateDecl>(
2040         static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2041   }
2042   const ClassTemplateDecl *getMostRecentDecl() const {
2043     return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
2044   }
2045
2046   ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
2047     return cast_or_null<ClassTemplateDecl>(
2048              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2049   }
2050
2051   /// \brief Return the partial specialization with the provided arguments if it
2052   /// exists, otherwise return the insertion point.
2053   ClassTemplatePartialSpecializationDecl *
2054   findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2055
2056   /// \brief Insert the specified partial specialization knowing that it is not
2057   /// already in. InsertPos must be obtained from findPartialSpecialization.
2058   void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
2059                                 void *InsertPos);
2060
2061   /// \brief Retrieve the partial specializations as an ordered list.
2062   void getPartialSpecializations(
2063           SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
2064
2065   /// \brief Find a class template partial specialization with the given
2066   /// type T.
2067   ///
2068   /// \param T a dependent type that names a specialization of this class
2069   /// template.
2070   ///
2071   /// \returns the class template partial specialization that exactly matches
2072   /// the type \p T, or NULL if no such partial specialization exists.
2073   ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
2074
2075   /// \brief Find a class template partial specialization which was instantiated
2076   /// from the given member partial specialization.
2077   ///
2078   /// \param D a member class template partial specialization.
2079   ///
2080   /// \returns the class template partial specialization which was instantiated
2081   /// from the given member partial specialization, or NULL if no such partial
2082   /// specialization exists.
2083   ClassTemplatePartialSpecializationDecl *
2084   findPartialSpecInstantiatedFromMember(
2085                                      ClassTemplatePartialSpecializationDecl *D);
2086
2087   /// \brief Retrieve the template specialization type of the
2088   /// injected-class-name for this class template.
2089   ///
2090   /// The injected-class-name for a class template \c X is \c
2091   /// X<template-args>, where \c template-args is formed from the
2092   /// template arguments that correspond to the template parameters of
2093   /// \c X. For example:
2094   ///
2095   /// \code
2096   /// template<typename T, int N>
2097   /// struct array {
2098   ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
2099   /// };
2100   /// \endcode
2101   QualType getInjectedClassNameSpecialization();
2102
2103   typedef SpecIterator<ClassTemplateSpecializationDecl> spec_iterator;
2104   typedef llvm::iterator_range<spec_iterator> spec_range;
2105
2106   spec_range specializations() const {
2107     return spec_range(spec_begin(), spec_end());
2108   }
2109
2110   spec_iterator spec_begin() const {
2111     return makeSpecIterator(getSpecializations(), false);
2112   }
2113
2114   spec_iterator spec_end() const {
2115     return makeSpecIterator(getSpecializations(), true);
2116   }
2117
2118   // Implement isa/cast/dyncast support
2119   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2120   static bool classofKind(Kind K) { return K == ClassTemplate; }
2121
2122   friend class ASTDeclReader;
2123   friend class ASTDeclWriter;
2124 };
2125
2126 /// \brief Declaration of a friend template.
2127 ///
2128 /// For example:
2129 /// \code
2130 /// template \<typename T> class A {
2131 ///   friend class MyVector<T>; // not a friend template
2132 ///   template \<typename U> friend class B; // not a friend template
2133 ///   template \<typename U> friend class Foo<T>::Nested; // friend template
2134 /// };
2135 /// \endcode
2136 ///
2137 /// \note This class is not currently in use.  All of the above
2138 /// will yield a FriendDecl, not a FriendTemplateDecl.
2139 class FriendTemplateDecl : public Decl {
2140   virtual void anchor();
2141 public:
2142   typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
2143
2144 private:
2145   // The number of template parameters;  always non-zero.
2146   unsigned NumParams;
2147
2148   // The parameter list.
2149   TemplateParameterList **Params;
2150
2151   // The declaration that's a friend of this class.
2152   FriendUnion Friend;
2153
2154   // Location of the 'friend' specifier.
2155   SourceLocation FriendLoc;
2156
2157
2158   FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
2159                      unsigned NParams,
2160                      TemplateParameterList **Params,
2161                      FriendUnion Friend,
2162                      SourceLocation FriendLoc)
2163     : Decl(Decl::FriendTemplate, DC, Loc),
2164       NumParams(NParams),
2165       Params(Params),
2166       Friend(Friend),
2167       FriendLoc(FriendLoc)
2168   {}
2169
2170   FriendTemplateDecl(EmptyShell Empty)
2171     : Decl(Decl::FriendTemplate, Empty),
2172       NumParams(0),
2173       Params(nullptr)
2174   {}
2175
2176 public:
2177   static FriendTemplateDecl *Create(ASTContext &Context,
2178                                     DeclContext *DC, SourceLocation Loc,
2179                                     unsigned NParams,
2180                                     TemplateParameterList **Params,
2181                                     FriendUnion Friend,
2182                                     SourceLocation FriendLoc);
2183
2184   static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2185
2186   /// If this friend declaration names a templated type (or
2187   /// a dependent member type of a templated type), return that
2188   /// type;  otherwise return null.
2189   TypeSourceInfo *getFriendType() const {
2190     return Friend.dyn_cast<TypeSourceInfo*>();
2191   }
2192
2193   /// If this friend declaration names a templated function (or
2194   /// a member function of a templated type), return that type;
2195   /// otherwise return null.
2196   NamedDecl *getFriendDecl() const {
2197     return Friend.dyn_cast<NamedDecl*>();
2198   }
2199
2200   /// \brief Retrieves the location of the 'friend' keyword.
2201   SourceLocation getFriendLoc() const {
2202     return FriendLoc;
2203   }
2204
2205   TemplateParameterList *getTemplateParameterList(unsigned i) const {
2206     assert(i <= NumParams);
2207     return Params[i];
2208   }
2209
2210   unsigned getNumTemplateParameters() const {
2211     return NumParams;
2212   }
2213
2214   // Implement isa/cast/dyncast/etc.
2215   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2216   static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
2217
2218   friend class ASTDeclReader;
2219 };
2220
2221 /// \brief Declaration of an alias template.
2222 ///
2223 /// For example:
2224 /// \code
2225 /// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
2226 /// \endcode
2227 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
2228   static void DeallocateCommon(void *Ptr);
2229
2230 protected:
2231   typedef CommonBase Common;
2232
2233   TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2234                         DeclarationName Name, TemplateParameterList *Params,
2235                         NamedDecl *Decl)
2236       : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
2237                                  Decl) {}
2238
2239   CommonBase *newCommon(ASTContext &C) const override;
2240
2241   Common *getCommonPtr() {
2242     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2243   }
2244
2245 public:
2246   /// Get the underlying function declaration of the template.
2247   TypeAliasDecl *getTemplatedDecl() const {
2248     return static_cast<TypeAliasDecl*>(TemplatedDecl);
2249   }
2250
2251
2252   TypeAliasTemplateDecl *getCanonicalDecl() override {
2253     return cast<TypeAliasTemplateDecl>(
2254              RedeclarableTemplateDecl::getCanonicalDecl());
2255   }
2256   const TypeAliasTemplateDecl *getCanonicalDecl() const {
2257     return cast<TypeAliasTemplateDecl>(
2258              RedeclarableTemplateDecl::getCanonicalDecl());
2259   }
2260
2261   /// \brief Retrieve the previous declaration of this function template, or
2262   /// NULL if no such declaration exists.
2263   TypeAliasTemplateDecl *getPreviousDecl() {
2264     return cast_or_null<TypeAliasTemplateDecl>(
2265              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2266   }
2267
2268   /// \brief Retrieve the previous declaration of this function template, or
2269   /// NULL if no such declaration exists.
2270   const TypeAliasTemplateDecl *getPreviousDecl() const {
2271     return cast_or_null<TypeAliasTemplateDecl>(
2272              static_cast<const RedeclarableTemplateDecl *>(
2273                this)->getPreviousDecl());
2274   }
2275
2276   TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
2277     return cast_or_null<TypeAliasTemplateDecl>(
2278              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2279   }
2280
2281
2282   /// \brief Create a function template node.
2283   static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2284                                        SourceLocation L,
2285                                        DeclarationName Name,
2286                                        TemplateParameterList *Params,
2287                                        NamedDecl *Decl);
2288
2289   /// \brief Create an empty alias template node.
2290   static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2291
2292   // Implement isa/cast/dyncast support
2293   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2294   static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2295
2296   friend class ASTDeclReader;
2297   friend class ASTDeclWriter;
2298 };
2299
2300 /// \brief Declaration of a function specialization at template class scope.
2301 ///
2302 /// This is a non-standard extension needed to support MSVC.
2303 ///
2304 /// For example:
2305 /// \code
2306 /// template <class T>
2307 /// class A {
2308 ///    template <class U> void foo(U a) { }
2309 ///    template<> void foo(int a) { }
2310 /// }
2311 /// \endcode
2312 ///
2313 /// "template<> foo(int a)" will be saved in Specialization as a normal
2314 /// CXXMethodDecl. Then during an instantiation of class A, it will be
2315 /// transformed into an actual function specialization.
2316 class ClassScopeFunctionSpecializationDecl : public Decl {
2317   virtual void anchor();
2318
2319   ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
2320                                        CXXMethodDecl *FD, bool Args,
2321                                        TemplateArgumentListInfo TemplArgs)
2322     : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2323       Specialization(FD), HasExplicitTemplateArgs(Args),
2324       TemplateArgs(TemplArgs) {}
2325
2326   ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2327     : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2328
2329   CXXMethodDecl *Specialization;
2330   bool HasExplicitTemplateArgs;
2331   TemplateArgumentListInfo TemplateArgs;
2332
2333 public:
2334   CXXMethodDecl *getSpecialization() const { return Specialization; }
2335   bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
2336   const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
2337
2338   static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
2339                                                       DeclContext *DC,
2340                                                       SourceLocation Loc,
2341                                                       CXXMethodDecl *FD,
2342                                                    bool HasExplicitTemplateArgs,
2343                                         TemplateArgumentListInfo TemplateArgs) {
2344     return new (C, DC) ClassScopeFunctionSpecializationDecl(
2345         DC, Loc, FD, HasExplicitTemplateArgs, TemplateArgs);
2346   }
2347
2348   static ClassScopeFunctionSpecializationDecl *
2349   CreateDeserialized(ASTContext &Context, unsigned ID);
2350   
2351   // Implement isa/cast/dyncast/etc.
2352   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2353   static bool classofKind(Kind K) {
2354     return K == Decl::ClassScopeFunctionSpecialization;
2355   }
2356
2357   friend class ASTDeclReader;
2358   friend class ASTDeclWriter;
2359 };
2360
2361 /// Implementation of inline functions that require the template declarations
2362 inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
2363   : Function(FTD) { }
2364
2365 /// \brief Represents a variable template specialization, which refers to
2366 /// a variable template with a given set of template arguments.
2367 ///
2368 /// Variable template specializations represent both explicit
2369 /// specializations of variable templates, as in the example below, and
2370 /// implicit instantiations of variable templates.
2371 ///
2372 /// \code
2373 /// template<typename T> constexpr T pi = T(3.1415926535897932385);
2374 ///
2375 /// template<>
2376 /// constexpr float pi<float>; // variable template specialization pi<float>
2377 /// \endcode
2378 class VarTemplateSpecializationDecl : public VarDecl,
2379                                       public llvm::FoldingSetNode {
2380
2381   /// \brief Structure that stores information about a variable template
2382   /// specialization that was instantiated from a variable template partial
2383   /// specialization.
2384   struct SpecializedPartialSpecialization {
2385     /// \brief The variable template partial specialization from which this
2386     /// variable template specialization was instantiated.
2387     VarTemplatePartialSpecializationDecl *PartialSpecialization;
2388
2389     /// \brief The template argument list deduced for the variable template
2390     /// partial specialization itself.
2391     const TemplateArgumentList *TemplateArgs;
2392   };
2393
2394   /// \brief The template that this specialization specializes.
2395   llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
2396   SpecializedTemplate;
2397
2398   /// \brief Further info for explicit template specialization/instantiation.
2399   struct ExplicitSpecializationInfo {
2400     /// \brief The type-as-written.
2401     TypeSourceInfo *TypeAsWritten;
2402     /// \brief The location of the extern keyword.
2403     SourceLocation ExternLoc;
2404     /// \brief The location of the template keyword.
2405     SourceLocation TemplateKeywordLoc;
2406
2407     ExplicitSpecializationInfo()
2408         : TypeAsWritten(nullptr), ExternLoc(), TemplateKeywordLoc() {}
2409   };
2410
2411   /// \brief Further info for explicit template specialization/instantiation.
2412   /// Does not apply to implicit specializations.
2413   ExplicitSpecializationInfo *ExplicitInfo;
2414
2415   /// \brief The template arguments used to describe this specialization.
2416   const TemplateArgumentList *TemplateArgs;
2417   TemplateArgumentListInfo TemplateArgsInfo;
2418
2419   /// \brief The point where this template was instantiated (if any).
2420   SourceLocation PointOfInstantiation;
2421
2422   /// \brief The kind of specialization this declaration refers to.
2423   /// Really a value of type TemplateSpecializationKind.
2424   unsigned SpecializationKind : 3;
2425
2426 protected:
2427   VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
2428                                 SourceLocation StartLoc, SourceLocation IdLoc,
2429                                 VarTemplateDecl *SpecializedTemplate,
2430                                 QualType T, TypeSourceInfo *TInfo,
2431                                 StorageClass S, const TemplateArgument *Args,
2432                                 unsigned NumArgs);
2433
2434   explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
2435
2436 public:
2437   static VarTemplateSpecializationDecl *
2438   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2439          SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
2440          TypeSourceInfo *TInfo, StorageClass S, const TemplateArgument *Args,
2441          unsigned NumArgs);
2442   static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
2443                                                            unsigned ID);
2444
2445   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2446                             bool Qualified) const override;
2447
2448   VarTemplateSpecializationDecl *getMostRecentDecl() {
2449     VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
2450     return cast<VarTemplateSpecializationDecl>(Recent);
2451   }
2452
2453   /// \brief Retrieve the template that this specialization specializes.
2454   VarTemplateDecl *getSpecializedTemplate() const;
2455
2456   /// \brief Retrieve the template arguments of the variable template
2457   /// specialization.
2458   const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
2459
2460   // TODO: Always set this when creating the new specialization?
2461   void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
2462
2463   const TemplateArgumentListInfo &getTemplateArgsInfo() const {
2464     return TemplateArgsInfo;
2465   }
2466
2467   /// \brief Determine the kind of specialization that this
2468   /// declaration represents.
2469   TemplateSpecializationKind getSpecializationKind() const {
2470     return static_cast<TemplateSpecializationKind>(SpecializationKind);
2471   }
2472
2473   bool isExplicitSpecialization() const {
2474     return getSpecializationKind() == TSK_ExplicitSpecialization;
2475   }
2476
2477   /// \brief True if this declaration is an explicit specialization,
2478   /// explicit instantiation declaration, or explicit instantiation
2479   /// definition.
2480   bool isExplicitInstantiationOrSpecialization() const {
2481     return isTemplateExplicitInstantiationOrSpecialization(
2482         getTemplateSpecializationKind());
2483   }
2484
2485   void setSpecializationKind(TemplateSpecializationKind TSK) {
2486     SpecializationKind = TSK;
2487   }
2488
2489   /// \brief Get the point of instantiation (if any), or null if none.
2490   SourceLocation getPointOfInstantiation() const {
2491     return PointOfInstantiation;
2492   }
2493
2494   void setPointOfInstantiation(SourceLocation Loc) {
2495     assert(Loc.isValid() && "point of instantiation must be valid!");
2496     PointOfInstantiation = Loc;
2497   }
2498
2499   /// \brief If this variable template specialization is an instantiation of
2500   /// a template (rather than an explicit specialization), return the
2501   /// variable template or variable template partial specialization from which
2502   /// it was instantiated.
2503   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2504   getInstantiatedFrom() const {
2505     if (getSpecializationKind() != TSK_ImplicitInstantiation &&
2506         getSpecializationKind() != TSK_ExplicitInstantiationDefinition &&
2507         getSpecializationKind() != TSK_ExplicitInstantiationDeclaration)
2508       return llvm::PointerUnion<VarTemplateDecl *,
2509                                 VarTemplatePartialSpecializationDecl *>();
2510
2511     if (SpecializedPartialSpecialization *PartialSpec =
2512             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2513       return PartialSpec->PartialSpecialization;
2514
2515     return SpecializedTemplate.get<VarTemplateDecl *>();
2516   }
2517
2518   /// \brief Retrieve the variable template or variable template partial
2519   /// specialization which was specialized by this.
2520   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2521   getSpecializedTemplateOrPartial() const {
2522     if (SpecializedPartialSpecialization *PartialSpec =
2523             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2524       return PartialSpec->PartialSpecialization;
2525
2526     return SpecializedTemplate.get<VarTemplateDecl *>();
2527   }
2528
2529   /// \brief Retrieve the set of template arguments that should be used
2530   /// to instantiate the initializer of the variable template or variable
2531   /// template partial specialization from which this variable template
2532   /// specialization was instantiated.
2533   ///
2534   /// \returns For a variable template specialization instantiated from the
2535   /// primary template, this function will return the same template arguments
2536   /// as getTemplateArgs(). For a variable template specialization instantiated
2537   /// from a variable template partial specialization, this function will the
2538   /// return deduced template arguments for the variable template partial
2539   /// specialization itself.
2540   const TemplateArgumentList &getTemplateInstantiationArgs() const {
2541     if (SpecializedPartialSpecialization *PartialSpec =
2542             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2543       return *PartialSpec->TemplateArgs;
2544
2545     return getTemplateArgs();
2546   }
2547
2548   /// \brief Note that this variable template specialization is actually an
2549   /// instantiation of the given variable template partial specialization whose
2550   /// template arguments have been deduced.
2551   void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
2552                           const TemplateArgumentList *TemplateArgs) {
2553     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
2554            "Already set to a variable template partial specialization!");
2555     SpecializedPartialSpecialization *PS =
2556         new (getASTContext()) SpecializedPartialSpecialization();
2557     PS->PartialSpecialization = PartialSpec;
2558     PS->TemplateArgs = TemplateArgs;
2559     SpecializedTemplate = PS;
2560   }
2561
2562   /// \brief Note that this variable template specialization is an instantiation
2563   /// of the given variable template.
2564   void setInstantiationOf(VarTemplateDecl *TemplDecl) {
2565     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
2566            "Previously set to a variable template partial specialization!");
2567     SpecializedTemplate = TemplDecl;
2568   }
2569
2570   /// \brief Sets the type of this specialization as it was written by
2571   /// the user.
2572   void setTypeAsWritten(TypeSourceInfo *T) {
2573     if (!ExplicitInfo)
2574       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2575     ExplicitInfo->TypeAsWritten = T;
2576   }
2577   /// \brief Gets the type of this specialization as it was written by
2578   /// the user, if it was so written.
2579   TypeSourceInfo *getTypeAsWritten() const {
2580     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
2581   }
2582
2583   /// \brief Gets the location of the extern keyword, if present.
2584   SourceLocation getExternLoc() const {
2585     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
2586   }
2587   /// \brief Sets the location of the extern keyword.
2588   void setExternLoc(SourceLocation Loc) {
2589     if (!ExplicitInfo)
2590       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2591     ExplicitInfo->ExternLoc = Loc;
2592   }
2593
2594   /// \brief Sets the location of the template keyword.
2595   void setTemplateKeywordLoc(SourceLocation Loc) {
2596     if (!ExplicitInfo)
2597       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2598     ExplicitInfo->TemplateKeywordLoc = Loc;
2599   }
2600   /// \brief Gets the location of the template keyword, if present.
2601   SourceLocation getTemplateKeywordLoc() const {
2602     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
2603   }
2604
2605   void Profile(llvm::FoldingSetNodeID &ID) const {
2606     Profile(ID, TemplateArgs->asArray(), getASTContext());
2607   }
2608
2609   static void Profile(llvm::FoldingSetNodeID &ID,
2610                       ArrayRef<TemplateArgument> TemplateArgs,
2611                       ASTContext &Context) {
2612     ID.AddInteger(TemplateArgs.size());
2613     for (unsigned Arg = 0; Arg != TemplateArgs.size(); ++Arg)
2614       TemplateArgs[Arg].Profile(ID, Context);
2615   }
2616
2617   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2618   static bool classofKind(Kind K) {
2619     return K >= firstVarTemplateSpecialization &&
2620            K <= lastVarTemplateSpecialization;
2621   }
2622
2623   friend class ASTDeclReader;
2624   friend class ASTDeclWriter;
2625 };
2626
2627 class VarTemplatePartialSpecializationDecl
2628     : public VarTemplateSpecializationDecl {
2629   void anchor() override;
2630
2631   /// \brief The list of template parameters
2632   TemplateParameterList *TemplateParams;
2633
2634   /// \brief The source info for the template arguments as written.
2635   /// FIXME: redundant with TypeAsWritten?
2636   const ASTTemplateArgumentListInfo *ArgsAsWritten;
2637
2638   /// \brief The variable template partial specialization from which this
2639   /// variable template partial specialization was instantiated.
2640   ///
2641   /// The boolean value will be true to indicate that this variable template
2642   /// partial specialization was specialized at this level.
2643   llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
2644   InstantiatedFromMember;
2645
2646   VarTemplatePartialSpecializationDecl(
2647       ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2648       SourceLocation IdLoc, TemplateParameterList *Params,
2649       VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
2650       StorageClass S, const TemplateArgument *Args, unsigned NumArgs,
2651       const ASTTemplateArgumentListInfo *ArgInfos);
2652
2653   VarTemplatePartialSpecializationDecl(ASTContext &Context)
2654     : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization, Context),
2655       TemplateParams(nullptr), ArgsAsWritten(nullptr),
2656       InstantiatedFromMember(nullptr, false) {}
2657
2658 public:
2659   static VarTemplatePartialSpecializationDecl *
2660   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2661          SourceLocation IdLoc, TemplateParameterList *Params,
2662          VarTemplateDecl *SpecializedTemplate, QualType T,
2663          TypeSourceInfo *TInfo, StorageClass S, const TemplateArgument *Args,
2664          unsigned NumArgs, const TemplateArgumentListInfo &ArgInfos);
2665
2666   static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
2667                                                                   unsigned ID);
2668
2669   VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
2670     return cast<VarTemplatePartialSpecializationDecl>(
2671              static_cast<VarTemplateSpecializationDecl *>(
2672                this)->getMostRecentDecl());
2673   }
2674
2675   /// Get the list of template parameters
2676   TemplateParameterList *getTemplateParameters() const {
2677     return TemplateParams;
2678   }
2679
2680   /// Get the template arguments as written.
2681   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2682     return ArgsAsWritten;
2683   }
2684
2685   /// \brief Retrieve the member variable template partial specialization from
2686   /// which this particular variable template partial specialization was
2687   /// instantiated.
2688   ///
2689   /// \code
2690   /// template<typename T>
2691   /// struct Outer {
2692   ///   template<typename U> U Inner;
2693   ///   template<typename U> U* Inner<U*> = (U*)(0); // #1
2694   /// };
2695   ///
2696   /// template int* Outer<float>::Inner<int*>;
2697   /// \endcode
2698   ///
2699   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
2700   /// end up instantiating the partial specialization
2701   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
2702   /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
2703   /// \c Outer<float>::Inner<U*>, this function would return
2704   /// \c Outer<T>::Inner<U*>.
2705   VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2706     const VarTemplatePartialSpecializationDecl *First =
2707         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2708     return First->InstantiatedFromMember.getPointer();
2709   }
2710
2711   void
2712   setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
2713     VarTemplatePartialSpecializationDecl *First =
2714         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2715     First->InstantiatedFromMember.setPointer(PartialSpec);
2716   }
2717
2718   /// \brief Determines whether this variable template partial specialization
2719   /// was a specialization of a member partial specialization.
2720   ///
2721   /// In the following example, the member template partial specialization
2722   /// \c X<int>::Inner<T*> is a member specialization.
2723   ///
2724   /// \code
2725   /// template<typename T>
2726   /// struct X {
2727   ///   template<typename U> U Inner;
2728   ///   template<typename U> U* Inner<U*> = (U*)(0);
2729   /// };
2730   ///
2731   /// template<> template<typename T>
2732   /// U* X<int>::Inner<T*> = (T*)(0) + 1;
2733   /// \endcode
2734   bool isMemberSpecialization() {
2735     VarTemplatePartialSpecializationDecl *First =
2736         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2737     return First->InstantiatedFromMember.getInt();
2738   }
2739
2740   /// \brief Note that this member template is a specialization.
2741   void setMemberSpecialization() {
2742     VarTemplatePartialSpecializationDecl *First =
2743         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2744     assert(First->InstantiatedFromMember.getPointer() &&
2745            "Only member templates can be member template specializations");
2746     return First->InstantiatedFromMember.setInt(true);
2747   }
2748
2749   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2750   static bool classofKind(Kind K) {
2751     return K == VarTemplatePartialSpecialization;
2752   }
2753
2754   friend class ASTDeclReader;
2755   friend class ASTDeclWriter;
2756 };
2757
2758 /// Declaration of a variable template.
2759 class VarTemplateDecl : public RedeclarableTemplateDecl {
2760   static void DeallocateCommon(void *Ptr);
2761
2762 protected:
2763   /// \brief Data that is common to all of the declarations of a given
2764   /// variable template.
2765   struct Common : CommonBase {
2766     Common() : LazySpecializations() {}
2767
2768     /// \brief The variable template specializations for this variable
2769     /// template, including explicit specializations and instantiations.
2770     llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
2771
2772     /// \brief The variable template partial specializations for this variable
2773     /// template.
2774     llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
2775     PartialSpecializations;
2776
2777     /// \brief If non-null, points to an array of specializations (including
2778     /// partial specializations) known ownly by their external declaration IDs.
2779     ///
2780     /// The first value in the array is the number of of specializations/
2781     /// partial specializations that follow.
2782     uint32_t *LazySpecializations;
2783   };
2784
2785   /// \brief Retrieve the set of specializations of this variable template.
2786   llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
2787   getSpecializations() const;
2788
2789   /// \brief Retrieve the set of partial specializations of this class
2790   /// template.
2791   llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
2792   getPartialSpecializations();
2793
2794   VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2795                   DeclarationName Name, TemplateParameterList *Params,
2796                   NamedDecl *Decl)
2797       : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
2798
2799   CommonBase *newCommon(ASTContext &C) const override;
2800
2801   Common *getCommonPtr() const {
2802     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2803   }
2804
2805 public:
2806   /// \brief Load any lazily-loaded specializations from the external source.
2807   void LoadLazySpecializations() const;
2808
2809   /// \brief Get the underlying variable declarations of the template.
2810   VarDecl *getTemplatedDecl() const {
2811     return static_cast<VarDecl *>(TemplatedDecl);
2812   }
2813
2814   /// \brief Returns whether this template declaration defines the primary
2815   /// variable pattern.
2816   bool isThisDeclarationADefinition() const {
2817     return getTemplatedDecl()->isThisDeclarationADefinition();
2818   }
2819
2820   VarTemplateDecl *getDefinition();
2821
2822   /// \brief Create a variable template node.
2823   static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2824                                  SourceLocation L, DeclarationName Name,
2825                                  TemplateParameterList *Params,
2826                                  VarDecl *Decl);
2827
2828   /// \brief Create an empty variable template node.
2829   static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2830
2831   /// \brief Return the specialization with the provided arguments if it exists,
2832   /// otherwise return the insertion point.
2833   VarTemplateSpecializationDecl *
2834   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2835
2836   /// \brief Insert the specified specialization knowing that it is not already
2837   /// in. InsertPos must be obtained from findSpecialization.
2838   void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
2839
2840   VarTemplateDecl *getCanonicalDecl() override {
2841     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2842   }
2843   const VarTemplateDecl *getCanonicalDecl() const {
2844     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2845   }
2846
2847   /// \brief Retrieve the previous declaration of this variable template, or
2848   /// NULL if no such declaration exists.
2849   VarTemplateDecl *getPreviousDecl() {
2850     return cast_or_null<VarTemplateDecl>(
2851         static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2852   }
2853
2854   /// \brief Retrieve the previous declaration of this variable template, or
2855   /// NULL if no such declaration exists.
2856   const VarTemplateDecl *getPreviousDecl() const {
2857     return cast_or_null<VarTemplateDecl>(
2858             static_cast<const RedeclarableTemplateDecl *>(
2859               this)->getPreviousDecl());
2860   }
2861
2862   VarTemplateDecl *getMostRecentDecl() {
2863     return cast<VarTemplateDecl>(
2864         static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2865   }
2866   const VarTemplateDecl *getMostRecentDecl() const {
2867     return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
2868   }
2869
2870   VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
2871     return cast_or_null<VarTemplateDecl>(
2872         RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2873   }
2874
2875   /// \brief Return the partial specialization with the provided arguments if it
2876   /// exists, otherwise return the insertion point.
2877   VarTemplatePartialSpecializationDecl *
2878   findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2879
2880   /// \brief Insert the specified partial specialization knowing that it is not
2881   /// already in. InsertPos must be obtained from findPartialSpecialization.
2882   void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
2883                                 void *InsertPos);
2884
2885   /// \brief Retrieve the partial specializations as an ordered list.
2886   void getPartialSpecializations(
2887       SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
2888
2889   /// \brief Find a variable template partial specialization which was
2890   /// instantiated
2891   /// from the given member partial specialization.
2892   ///
2893   /// \param D a member variable template partial specialization.
2894   ///
2895   /// \returns the variable template partial specialization which was
2896   /// instantiated
2897   /// from the given member partial specialization, or NULL if no such partial
2898   /// specialization exists.
2899   VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
2900       VarTemplatePartialSpecializationDecl *D);
2901
2902   typedef SpecIterator<VarTemplateSpecializationDecl> spec_iterator;
2903   typedef llvm::iterator_range<spec_iterator> spec_range;
2904
2905   spec_range specializations() const {
2906     return spec_range(spec_begin(), spec_end());
2907   }
2908
2909   spec_iterator spec_begin() const {
2910     return makeSpecIterator(getSpecializations(), false);
2911   }
2912
2913   spec_iterator spec_end() const {
2914     return makeSpecIterator(getSpecializations(), true);
2915   }
2916
2917   // Implement isa/cast/dyncast support
2918   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2919   static bool classofKind(Kind K) { return K == VarTemplate; }
2920
2921   friend class ASTDeclReader;
2922   friend class ASTDeclWriter;
2923 };
2924
2925 } /* end of namespace clang */
2926
2927 #endif