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