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