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