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