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