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