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