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