SemaTemplateInstantiate.cpp revision 4ac20ef0578c5bcf99cd5574e0ed6b36d186eadc
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/ 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7//===----------------------------------------------------------------------===/ 8// 9// This file implements C++ template instantiation. 10// 11//===----------------------------------------------------------------------===/ 12 13#include "Sema.h" 14#include "clang/AST/ASTConsumer.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/Expr.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/Parse/DeclSpec.h" 19#include "clang/Basic/LangOptions.h" 20#include "llvm/Support/Compiler.h" 21 22using namespace clang; 23 24//===----------------------------------------------------------------------===/ 25// Template Instantiation Support 26//===----------------------------------------------------------------------===/ 27 28/// \brief Retrieve the template argument list that should be used to 29/// instantiate the given declaration. 30const TemplateArgumentList & 31Sema::getTemplateInstantiationArgs(NamedDecl *D) { 32 if (ClassTemplateSpecializationDecl *Spec 33 = dyn_cast<ClassTemplateSpecializationDecl>(D)) 34 return Spec->getTemplateArgs(); 35 36 DeclContext *EnclosingTemplateCtx = D->getDeclContext(); 37 while (!isa<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx)) { 38 assert(!EnclosingTemplateCtx->isFileContext() && 39 "Tried to get the instantiation arguments of a non-template"); 40 EnclosingTemplateCtx = EnclosingTemplateCtx->getParent(); 41 } 42 43 ClassTemplateSpecializationDecl *EnclosingTemplate 44 = cast<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx); 45 return EnclosingTemplate->getTemplateArgs(); 46} 47 48Sema::InstantiatingTemplate:: 49InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 50 Decl *Entity, 51 SourceRange InstantiationRange) 52 : SemaRef(SemaRef) { 53 54 Invalid = CheckInstantiationDepth(PointOfInstantiation, 55 InstantiationRange); 56 if (!Invalid) { 57 ActiveTemplateInstantiation Inst; 58 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation; 59 Inst.PointOfInstantiation = PointOfInstantiation; 60 Inst.Entity = reinterpret_cast<uintptr_t>(Entity); 61 Inst.TemplateArgs = 0; 62 Inst.NumTemplateArgs = 0; 63 Inst.InstantiationRange = InstantiationRange; 64 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 65 Invalid = false; 66 } 67} 68 69Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 70 SourceLocation PointOfInstantiation, 71 TemplateDecl *Template, 72 const TemplateArgument *TemplateArgs, 73 unsigned NumTemplateArgs, 74 SourceRange InstantiationRange) 75 : SemaRef(SemaRef) { 76 77 Invalid = CheckInstantiationDepth(PointOfInstantiation, 78 InstantiationRange); 79 if (!Invalid) { 80 ActiveTemplateInstantiation Inst; 81 Inst.Kind 82 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation; 83 Inst.PointOfInstantiation = PointOfInstantiation; 84 Inst.Entity = reinterpret_cast<uintptr_t>(Template); 85 Inst.TemplateArgs = TemplateArgs; 86 Inst.NumTemplateArgs = NumTemplateArgs; 87 Inst.InstantiationRange = InstantiationRange; 88 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 89 Invalid = false; 90 } 91} 92 93void Sema::InstantiatingTemplate::Clear() { 94 if (!Invalid) { 95 SemaRef.ActiveTemplateInstantiations.pop_back(); 96 Invalid = true; 97 } 98} 99 100bool Sema::InstantiatingTemplate::CheckInstantiationDepth( 101 SourceLocation PointOfInstantiation, 102 SourceRange InstantiationRange) { 103 if (SemaRef.ActiveTemplateInstantiations.size() 104 <= SemaRef.getLangOptions().InstantiationDepth) 105 return false; 106 107 SemaRef.Diag(PointOfInstantiation, 108 diag::err_template_recursion_depth_exceeded) 109 << SemaRef.getLangOptions().InstantiationDepth 110 << InstantiationRange; 111 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) 112 << SemaRef.getLangOptions().InstantiationDepth; 113 return true; 114} 115 116/// \brief Prints the current instantiation stack through a series of 117/// notes. 118void Sema::PrintInstantiationStack() { 119 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator 120 Active = ActiveTemplateInstantiations.rbegin(), 121 ActiveEnd = ActiveTemplateInstantiations.rend(); 122 Active != ActiveEnd; 123 ++Active) { 124 switch (Active->Kind) { 125 case ActiveTemplateInstantiation::TemplateInstantiation: { 126 Decl *D = reinterpret_cast<Decl *>(Active->Entity); 127 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 128 unsigned DiagID = diag::note_template_member_class_here; 129 if (isa<ClassTemplateSpecializationDecl>(Record)) 130 DiagID = diag::note_template_class_instantiation_here; 131 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 132 DiagID) 133 << Context.getTypeDeclType(Record) 134 << Active->InstantiationRange; 135 } else { 136 FunctionDecl *Function = cast<FunctionDecl>(D); 137 unsigned DiagID = diag::note_template_member_function_here; 138 // FIXME: check for a function template 139 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 140 DiagID) 141 << Function 142 << Active->InstantiationRange; 143 } 144 break; 145 } 146 147 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: { 148 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity); 149 std::string TemplateArgsStr 150 = TemplateSpecializationType::PrintTemplateArgumentList( 151 Active->TemplateArgs, 152 Active->NumTemplateArgs); 153 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 154 diag::note_default_arg_instantiation_here) 155 << (Template->getNameAsString() + TemplateArgsStr) 156 << Active->InstantiationRange; 157 break; 158 } 159 } 160 } 161} 162 163//===----------------------------------------------------------------------===/ 164// Template Instantiation for Types 165//===----------------------------------------------------------------------===/ 166namespace { 167 class VISIBILITY_HIDDEN TemplateTypeInstantiator { 168 Sema &SemaRef; 169 const TemplateArgumentList &TemplateArgs; 170 SourceLocation Loc; 171 DeclarationName Entity; 172 173 public: 174 TemplateTypeInstantiator(Sema &SemaRef, 175 const TemplateArgumentList &TemplateArgs, 176 SourceLocation Loc, 177 DeclarationName Entity) 178 : SemaRef(SemaRef), TemplateArgs(TemplateArgs), 179 Loc(Loc), Entity(Entity) { } 180 181 QualType operator()(QualType T) const { return Instantiate(T); } 182 183 QualType Instantiate(QualType T) const; 184 185 // Declare instantiate functions for each type. 186#define TYPE(Class, Base) \ 187 QualType Instantiate##Class##Type(const Class##Type *T, \ 188 unsigned Quals) const; 189#define ABSTRACT_TYPE(Class, Base) 190#include "clang/AST/TypeNodes.def" 191 }; 192} 193 194QualType 195TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T, 196 unsigned Quals) const { 197 // FIXME: Implement this 198 assert(false && "Cannot instantiate ExtQualType yet"); 199 return QualType(); 200} 201 202QualType 203TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T, 204 unsigned Quals) const { 205 assert(false && "Builtin types are not dependent and cannot be instantiated"); 206 return QualType(T, Quals); 207} 208 209QualType 210TemplateTypeInstantiator:: 211InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const { 212 // FIXME: Implement this 213 assert(false && "Cannot instantiate FixedWidthIntType yet"); 214 return QualType(); 215} 216 217QualType 218TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T, 219 unsigned Quals) const { 220 // FIXME: Implement this 221 assert(false && "Cannot instantiate ComplexType yet"); 222 return QualType(); 223} 224 225QualType 226TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T, 227 unsigned Quals) const { 228 QualType PointeeType = Instantiate(T->getPointeeType()); 229 if (PointeeType.isNull()) 230 return QualType(); 231 232 return SemaRef.BuildPointerType(PointeeType, Quals, Loc, Entity); 233} 234 235QualType 236TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T, 237 unsigned Quals) const { 238 // FIXME: Implement this 239 assert(false && "Cannot instantiate BlockPointerType yet"); 240 return QualType(); 241} 242 243QualType 244TemplateTypeInstantiator::InstantiateLValueReferenceType( 245 const LValueReferenceType *T, unsigned Quals) const { 246 QualType ReferentType = Instantiate(T->getPointeeType()); 247 if (ReferentType.isNull()) 248 return QualType(); 249 250 return SemaRef.BuildReferenceType(ReferentType, true, Quals, Loc, Entity); 251} 252 253QualType 254TemplateTypeInstantiator::InstantiateRValueReferenceType( 255 const RValueReferenceType *T, unsigned Quals) const { 256 QualType ReferentType = Instantiate(T->getPointeeType()); 257 if (ReferentType.isNull()) 258 return QualType(); 259 260 return SemaRef.BuildReferenceType(ReferentType, false, Quals, Loc, Entity); 261} 262 263QualType 264TemplateTypeInstantiator:: 265InstantiateMemberPointerType(const MemberPointerType *T, 266 unsigned Quals) const { 267 // FIXME: Implement this 268 assert(false && "Cannot instantiate MemberPointerType yet"); 269 return QualType(); 270} 271 272QualType 273TemplateTypeInstantiator:: 274InstantiateConstantArrayType(const ConstantArrayType *T, 275 unsigned Quals) const { 276 QualType ElementType = Instantiate(T->getElementType()); 277 if (ElementType.isNull()) 278 return ElementType; 279 280 // Build a temporary integer literal to specify the size for 281 // BuildArrayType. Since we have already checked the size as part of 282 // creating the dependent array type in the first place, we know 283 // there aren't any errors. However, we do need to determine what 284 // C++ type to give the size expression. 285 llvm::APInt Size = T->getSize(); 286 QualType Types[] = { 287 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy, 288 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy, 289 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty 290 }; 291 const unsigned NumTypes = sizeof(Types) / sizeof(QualType); 292 QualType SizeType; 293 for (unsigned I = 0; I != NumTypes; ++I) 294 if (Size.getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) { 295 SizeType = Types[I]; 296 break; 297 } 298 299 if (SizeType.isNull()) 300 SizeType = SemaRef.Context.getFixedWidthIntType(Size.getBitWidth(), false); 301 302 IntegerLiteral ArraySize(Size, SizeType, Loc); 303 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(), 304 &ArraySize, T->getIndexTypeQualifier(), 305 Loc, Entity); 306} 307 308QualType 309TemplateTypeInstantiator:: 310InstantiateIncompleteArrayType(const IncompleteArrayType *T, 311 unsigned Quals) const { 312 QualType ElementType = Instantiate(T->getElementType()); 313 if (ElementType.isNull()) 314 return ElementType; 315 316 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(), 317 0, T->getIndexTypeQualifier(), 318 Loc, Entity); 319} 320 321QualType 322TemplateTypeInstantiator:: 323InstantiateVariableArrayType(const VariableArrayType *T, 324 unsigned Quals) const { 325 // FIXME: Implement this 326 assert(false && "Cannot instantiate VariableArrayType yet"); 327 return QualType(); 328} 329 330QualType 331TemplateTypeInstantiator:: 332InstantiateDependentSizedArrayType(const DependentSizedArrayType *T, 333 unsigned Quals) const { 334 Expr *ArraySize = T->getSizeExpr(); 335 assert(ArraySize->isValueDependent() && 336 "dependent sized array types must have value dependent size expr"); 337 338 // Instantiate the element type if needed 339 QualType ElementType = T->getElementType(); 340 if (ElementType->isDependentType()) { 341 ElementType = Instantiate(ElementType); 342 if (ElementType.isNull()) 343 return QualType(); 344 } 345 346 // Instantiate the size expression 347 Sema::OwningExprResult InstantiatedArraySize = 348 SemaRef.InstantiateExpr(ArraySize, TemplateArgs); 349 if (InstantiatedArraySize.isInvalid()) 350 return QualType(); 351 352 return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(), 353 InstantiatedArraySize.takeAs<Expr>(), 354 T->getIndexTypeQualifier(), Loc, Entity); 355} 356 357QualType 358TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T, 359 unsigned Quals) const { 360 // FIXME: Implement this 361 assert(false && "Cannot instantiate VectorType yet"); 362 return QualType(); 363} 364 365QualType 366TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T, 367 unsigned Quals) const { 368 // FIXME: Implement this 369 assert(false && "Cannot instantiate ExtVectorType yet"); 370 return QualType(); 371} 372 373QualType 374TemplateTypeInstantiator:: 375InstantiateFunctionProtoType(const FunctionProtoType *T, 376 unsigned Quals) const { 377 QualType ResultType = Instantiate(T->getResultType()); 378 if (ResultType.isNull()) 379 return ResultType; 380 381 llvm::SmallVector<QualType, 4> ParamTypes; 382 for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(), 383 ParamEnd = T->arg_type_end(); 384 Param != ParamEnd; ++Param) { 385 QualType P = Instantiate(*Param); 386 if (P.isNull()) 387 return P; 388 389 ParamTypes.push_back(P); 390 } 391 392 return SemaRef.BuildFunctionType(ResultType, &ParamTypes[0], 393 ParamTypes.size(), 394 T->isVariadic(), T->getTypeQuals(), 395 Loc, Entity); 396} 397 398QualType 399TemplateTypeInstantiator:: 400InstantiateFunctionNoProtoType(const FunctionNoProtoType *T, 401 unsigned Quals) const { 402 assert(false && "Functions without prototypes cannot be dependent."); 403 return QualType(); 404} 405 406QualType 407TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T, 408 unsigned Quals) const { 409 TypedefDecl *Typedef 410 = cast_or_null<TypedefDecl>( 411 SemaRef.InstantiateCurrentDeclRef(T->getDecl())); 412 if (!Typedef) 413 return QualType(); 414 415 return SemaRef.Context.getTypeDeclType(Typedef); 416} 417 418QualType 419TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T, 420 unsigned Quals) const { 421 Sema::OwningExprResult E 422 = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs); 423 if (E.isInvalid()) 424 return QualType(); 425 426 return SemaRef.Context.getTypeOfExprType(E.takeAs<Expr>()); 427} 428 429QualType 430TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T, 431 unsigned Quals) const { 432 QualType Underlying = Instantiate(T->getUnderlyingType()); 433 if (Underlying.isNull()) 434 return QualType(); 435 436 return SemaRef.Context.getTypeOfType(Underlying); 437} 438 439QualType 440TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T, 441 unsigned Quals) const { 442 RecordDecl *Record 443 = cast_or_null<RecordDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl())); 444 if (!Record) 445 return QualType(); 446 447 return SemaRef.Context.getTypeDeclType(Record); 448} 449 450QualType 451TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T, 452 unsigned Quals) const { 453 EnumDecl *Enum 454 = cast_or_null<EnumDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl())); 455 if (!Enum) 456 return QualType(); 457 458 return SemaRef.Context.getTypeDeclType(Enum); 459} 460 461QualType 462TemplateTypeInstantiator:: 463InstantiateTemplateTypeParmType(const TemplateTypeParmType *T, 464 unsigned Quals) const { 465 if (T->getDepth() == 0) { 466 // Replace the template type parameter with its corresponding 467 // template argument. 468 assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type && 469 "Template argument kind mismatch"); 470 QualType Result = TemplateArgs[T->getIndex()].getAsType(); 471 if (Result.isNull() || !Quals) 472 return Result; 473 474 // C++ [dcl.ref]p1: 475 // [...] Cv-qualified references are ill-formed except when 476 // the cv-qualifiers are introduced through the use of a 477 // typedef (7.1.3) or of a template type argument (14.3), in 478 // which case the cv-qualifiers are ignored. 479 if (Quals && Result->isReferenceType()) 480 Quals = 0; 481 482 return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers()); 483 } 484 485 // The template type parameter comes from an inner template (e.g., 486 // the template parameter list of a member template inside the 487 // template we are instantiating). Create a new template type 488 // parameter with the template "level" reduced by one. 489 return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1, 490 T->getIndex(), 491 T->getName()) 492 .getQualifiedType(Quals); 493} 494 495QualType 496TemplateTypeInstantiator:: 497InstantiateTemplateSpecializationType( 498 const TemplateSpecializationType *T, 499 unsigned Quals) const { 500 llvm::SmallVector<TemplateArgument, 4> InstantiatedTemplateArgs; 501 InstantiatedTemplateArgs.reserve(T->getNumArgs()); 502 for (TemplateSpecializationType::iterator Arg = T->begin(), ArgEnd = T->end(); 503 Arg != ArgEnd; ++Arg) { 504 switch (Arg->getKind()) { 505 case TemplateArgument::Type: { 506 QualType T = SemaRef.InstantiateType(Arg->getAsType(), 507 TemplateArgs, 508 Arg->getLocation(), 509 DeclarationName()); 510 if (T.isNull()) 511 return QualType(); 512 513 InstantiatedTemplateArgs.push_back( 514 TemplateArgument(Arg->getLocation(), T)); 515 break; 516 } 517 518 case TemplateArgument::Declaration: 519 case TemplateArgument::Integral: 520 InstantiatedTemplateArgs.push_back(*Arg); 521 break; 522 523 case TemplateArgument::Expression: 524 Sema::OwningExprResult E 525 = SemaRef.InstantiateExpr(Arg->getAsExpr(), TemplateArgs); 526 if (E.isInvalid()) 527 return QualType(); 528 InstantiatedTemplateArgs.push_back(E.takeAs<Expr>()); 529 break; 530 } 531 } 532 533 // FIXME: We're missing the locations of the template name, '<', and '>'. 534 535 TemplateName Name = SemaRef.InstantiateTemplateName(T->getTemplateName(), 536 Loc, 537 TemplateArgs); 538 539 return SemaRef.CheckTemplateIdType(Name, Loc, SourceLocation(), 540 &InstantiatedTemplateArgs[0], 541 InstantiatedTemplateArgs.size(), 542 SourceLocation()); 543} 544 545QualType 546TemplateTypeInstantiator:: 547InstantiateQualifiedNameType(const QualifiedNameType *T, 548 unsigned Quals) const { 549 // When we instantiated a qualified name type, there's no point in 550 // keeping the qualification around in the instantiated result. So, 551 // just instantiate the named type. 552 return (*this)(T->getNamedType()); 553} 554 555QualType 556TemplateTypeInstantiator:: 557InstantiateTypenameType(const TypenameType *T, unsigned Quals) const { 558 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) { 559 // When the typename type refers to a template-id, the template-id 560 // is dependent and has enough information to instantiate the 561 // result of the typename type. Since we don't care about keeping 562 // the spelling of the typename type in template instantiations, 563 // we just instantiate the template-id. 564 return InstantiateTemplateSpecializationType(TemplateId, Quals); 565 } 566 567 NestedNameSpecifier *NNS 568 = SemaRef.InstantiateNestedNameSpecifier(T->getQualifier(), 569 SourceRange(Loc), 570 TemplateArgs); 571 if (!NNS) 572 return QualType(); 573 574 return SemaRef.CheckTypenameType(NNS, *T->getIdentifier(), SourceRange(Loc)); 575} 576 577QualType 578TemplateTypeInstantiator:: 579InstantiateObjCInterfaceType(const ObjCInterfaceType *T, 580 unsigned Quals) const { 581 assert(false && "Objective-C types cannot be dependent"); 582 return QualType(); 583} 584 585QualType 586TemplateTypeInstantiator:: 587InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *T, 588 unsigned Quals) const { 589 assert(false && "Objective-C types cannot be dependent"); 590 return QualType(); 591} 592 593QualType 594TemplateTypeInstantiator:: 595InstantiateObjCQualifiedIdType(const ObjCQualifiedIdType *T, 596 unsigned Quals) const { 597 assert(false && "Objective-C types cannot be dependent"); 598 return QualType(); 599} 600 601/// \brief The actual implementation of Sema::InstantiateType(). 602QualType TemplateTypeInstantiator::Instantiate(QualType T) const { 603 // If T is not a dependent type, there is nothing to do. 604 if (!T->isDependentType()) 605 return T; 606 607 switch (T->getTypeClass()) { 608#define TYPE(Class, Base) \ 609 case Type::Class: \ 610 return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()), \ 611 T.getCVRQualifiers()); 612#define ABSTRACT_TYPE(Class, Base) 613#include "clang/AST/TypeNodes.def" 614 } 615 616 assert(false && "Not all types have been decoded for instantiation"); 617 return QualType(); 618} 619 620/// \brief Instantiate the type T with a given set of template arguments. 621/// 622/// This routine substitutes the given template arguments into the 623/// type T and produces the instantiated type. 624/// 625/// \param T the type into which the template arguments will be 626/// substituted. If this type is not dependent, it will be returned 627/// immediately. 628/// 629/// \param TemplateArgs the template arguments that will be 630/// substituted for the top-level template parameters within T. 631/// 632/// \param Loc the location in the source code where this substitution 633/// is being performed. It will typically be the location of the 634/// declarator (if we're instantiating the type of some declaration) 635/// or the location of the type in the source code (if, e.g., we're 636/// instantiating the type of a cast expression). 637/// 638/// \param Entity the name of the entity associated with a declaration 639/// being instantiated (if any). May be empty to indicate that there 640/// is no such entity (if, e.g., this is a type that occurs as part of 641/// a cast expression) or that the entity has no name (e.g., an 642/// unnamed function parameter). 643/// 644/// \returns If the instantiation succeeds, the instantiated 645/// type. Otherwise, produces diagnostics and returns a NULL type. 646QualType Sema::InstantiateType(QualType T, 647 const TemplateArgumentList &TemplateArgs, 648 SourceLocation Loc, DeclarationName Entity) { 649 assert(!ActiveTemplateInstantiations.empty() && 650 "Cannot perform an instantiation without some context on the " 651 "instantiation stack"); 652 653 // If T is not a dependent type, there is nothing to do. 654 if (!T->isDependentType()) 655 return T; 656 657 TemplateTypeInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); 658 return Instantiator(T); 659} 660 661/// \brief Instantiate the base class specifiers of the given class 662/// template specialization. 663/// 664/// Produces a diagnostic and returns true on error, returns false and 665/// attaches the instantiated base classes to the class template 666/// specialization if successful. 667bool 668Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation, 669 CXXRecordDecl *Pattern, 670 const TemplateArgumentList &TemplateArgs) { 671 bool Invalid = false; 672 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; 673 for (ClassTemplateSpecializationDecl::base_class_iterator 674 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end(); 675 Base != BaseEnd; ++Base) { 676 if (!Base->getType()->isDependentType()) { 677 // FIXME: Allocate via ASTContext 678 InstantiatedBases.push_back(new CXXBaseSpecifier(*Base)); 679 continue; 680 } 681 682 QualType BaseType = InstantiateType(Base->getType(), 683 TemplateArgs, 684 Base->getSourceRange().getBegin(), 685 DeclarationName()); 686 if (BaseType.isNull()) { 687 Invalid = true; 688 continue; 689 } 690 691 if (CXXBaseSpecifier *InstantiatedBase 692 = CheckBaseSpecifier(Instantiation, 693 Base->getSourceRange(), 694 Base->isVirtual(), 695 Base->getAccessSpecifierAsWritten(), 696 BaseType, 697 /*FIXME: Not totally accurate */ 698 Base->getSourceRange().getBegin())) 699 InstantiatedBases.push_back(InstantiatedBase); 700 else 701 Invalid = true; 702 } 703 704 if (!Invalid && 705 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(), 706 InstantiatedBases.size())) 707 Invalid = true; 708 709 return Invalid; 710} 711 712/// \brief Instantiate the definition of a class from a given pattern. 713/// 714/// \param PointOfInstantiation The point of instantiation within the 715/// source code. 716/// 717/// \param Instantiation is the declaration whose definition is being 718/// instantiated. This will be either a class template specialization 719/// or a member class of a class template specialization. 720/// 721/// \param Pattern is the pattern from which the instantiation 722/// occurs. This will be either the declaration of a class template or 723/// the declaration of a member class of a class template. 724/// 725/// \param TemplateArgs The template arguments to be substituted into 726/// the pattern. 727/// 728/// \returns true if an error occurred, false otherwise. 729bool 730Sema::InstantiateClass(SourceLocation PointOfInstantiation, 731 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 732 const TemplateArgumentList &TemplateArgs, 733 bool ExplicitInstantiation) { 734 bool Invalid = false; 735 736 CXXRecordDecl *PatternDef 737 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context)); 738 if (!PatternDef) { 739 if (Pattern == Instantiation->getInstantiatedFromMemberClass()) { 740 Diag(PointOfInstantiation, 741 diag::err_implicit_instantiate_member_undefined) 742 << Context.getTypeDeclType(Instantiation); 743 Diag(Pattern->getLocation(), diag::note_member_of_template_here); 744 } else { 745 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 746 << ExplicitInstantiation 747 << Context.getTypeDeclType(Instantiation); 748 Diag(Pattern->getLocation(), diag::note_template_decl_here); 749 } 750 return true; 751 } 752 Pattern = PatternDef; 753 754 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 755 if (Inst) 756 return true; 757 758 // Enter the scope of this instantiation. We don't use 759 // PushDeclContext because we don't have a scope. 760 DeclContext *PreviousContext = CurContext; 761 CurContext = Instantiation; 762 763 // Start the definition of this instantiation. 764 Instantiation->startDefinition(); 765 766 // Instantiate the base class specifiers. 767 if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) 768 Invalid = true; 769 770 llvm::SmallVector<DeclPtrTy, 4> Fields; 771 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(Context), 772 MemberEnd = Pattern->decls_end(Context); 773 Member != MemberEnd; ++Member) { 774 Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs); 775 if (NewMember) { 776 if (NewMember->isInvalidDecl()) 777 Invalid = true; 778 else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) 779 Fields.push_back(DeclPtrTy::make(Field)); 780 } else { 781 // FIXME: Eventually, a NULL return will mean that one of the 782 // instantiations was a semantic disaster, and we'll want to set Invalid = 783 // true. For now, we expect to skip some members that we can't yet handle. 784 } 785 } 786 787 // Finish checking fields. 788 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation), 789 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(), 790 0); 791 792 // Add any implicitly-declared members that we might need. 793 AddImplicitlyDeclaredMembersToClass(Instantiation); 794 795 // Exit the scope of this instantiation. 796 CurContext = PreviousContext; 797 798 if (!Invalid) 799 Consumer.HandleTagDeclDefinition(Instantiation); 800 801 // If this is an explicit instantiation, instantiate our members, too. 802 if (!Invalid && ExplicitInstantiation) { 803 Inst.Clear(); 804 InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs); 805 } 806 807 return Invalid; 808} 809 810bool 811Sema::InstantiateClassTemplateSpecialization( 812 ClassTemplateSpecializationDecl *ClassTemplateSpec, 813 bool ExplicitInstantiation) { 814 // Perform the actual instantiation on the canonical declaration. 815 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 816 Context.getCanonicalDecl(ClassTemplateSpec)); 817 818 // We can only instantiate something that hasn't already been 819 // instantiated or specialized. Fail without any diagnostics: our 820 // caller will provide an error message. 821 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) 822 return true; 823 824 // FIXME: Push this class template instantiation onto the instantiation stack, 825 // checking for recursion that exceeds a certain depth. 826 827 // FIXME: Perform class template partial specialization to select the best 828 // template. 829 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 830 831 CXXRecordDecl *Pattern = Template->getTemplatedDecl(); 832 833 // Note that this is an instantiation. 834 ClassTemplateSpec->setSpecializationKind( 835 ExplicitInstantiation? TSK_ExplicitInstantiation 836 : TSK_ImplicitInstantiation); 837 838 return InstantiateClass(ClassTemplateSpec->getLocation(), 839 ClassTemplateSpec, Pattern, 840 ClassTemplateSpec->getTemplateArgs(), 841 ExplicitInstantiation); 842} 843 844/// \brief Instantiate the definitions of all of the member of the 845/// given class, which is an instantiation of a class template or a 846/// member class of a template. 847void 848Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 849 CXXRecordDecl *Instantiation, 850 const TemplateArgumentList &TemplateArgs) { 851 for (DeclContext::decl_iterator D = Instantiation->decls_begin(Context), 852 DEnd = Instantiation->decls_end(Context); 853 D != DEnd; ++D) { 854 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) { 855 if (!Function->getBody(Context)) 856 InstantiateFunctionDefinition(PointOfInstantiation, Function); 857 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) { 858 const VarDecl *Def = 0; 859 if (!Var->getDefinition(Def)) 860 InstantiateVariableDefinition(Var); 861 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) { 862 if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) { 863 assert(Record->getInstantiatedFromMemberClass() && 864 "Missing instantiated-from-template information"); 865 InstantiateClass(PointOfInstantiation, Record, 866 Record->getInstantiatedFromMemberClass(), 867 TemplateArgs, true); 868 } 869 } 870 } 871} 872 873/// \brief Instantiate the definitions of all of the members of the 874/// given class template specialization, which was named as part of an 875/// explicit instantiation. 876void Sema::InstantiateClassTemplateSpecializationMembers( 877 SourceLocation PointOfInstantiation, 878 ClassTemplateSpecializationDecl *ClassTemplateSpec) { 879 // C++0x [temp.explicit]p7: 880 // An explicit instantiation that names a class template 881 // specialization is an explicit instantion of the same kind 882 // (declaration or definition) of each of its members (not 883 // including members inherited from base classes) that has not 884 // been previously explicitly specialized in the translation unit 885 // containing the explicit instantiation, except as described 886 // below. 887 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 888 ClassTemplateSpec->getTemplateArgs()); 889} 890 891/// \brief Instantiate a nested-name-specifier. 892NestedNameSpecifier * 893Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS, 894 SourceRange Range, 895 const TemplateArgumentList &TemplateArgs) { 896 // Instantiate the prefix of this nested name specifier. 897 NestedNameSpecifier *Prefix = NNS->getPrefix(); 898 if (Prefix) { 899 Prefix = InstantiateNestedNameSpecifier(Prefix, Range, TemplateArgs); 900 if (!Prefix) 901 return 0; 902 } 903 904 switch (NNS->getKind()) { 905 case NestedNameSpecifier::Identifier: { 906 assert(Prefix && 907 "Can't have an identifier nested-name-specifier with no prefix"); 908 CXXScopeSpec SS; 909 // FIXME: The source location information is all wrong. 910 SS.setRange(Range); 911 SS.setScopeRep(Prefix); 912 return static_cast<NestedNameSpecifier *>( 913 ActOnCXXNestedNameSpecifier(0, SS, 914 Range.getEnd(), 915 Range.getEnd(), 916 *NNS->getAsIdentifier())); 917 break; 918 } 919 920 case NestedNameSpecifier::Namespace: 921 case NestedNameSpecifier::Global: 922 return NNS; 923 924 case NestedNameSpecifier::TypeSpecWithTemplate: 925 case NestedNameSpecifier::TypeSpec: { 926 QualType T = QualType(NNS->getAsType(), 0); 927 if (!T->isDependentType()) 928 return NNS; 929 930 T = InstantiateType(T, TemplateArgs, Range.getBegin(), DeclarationName()); 931 if (T.isNull()) 932 return 0; 933 934 if (T->isRecordType() || 935 (getLangOptions().CPlusPlus0x && T->isEnumeralType())) { 936 assert(T.getCVRQualifiers() == 0 && "Can't get cv-qualifiers here"); 937 return NestedNameSpecifier::Create(Context, Prefix, 938 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, 939 T.getTypePtr()); 940 } 941 942 Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T; 943 return 0; 944 } 945 } 946 947 // Required to silence a GCC warning 948 return 0; 949} 950 951TemplateName 952Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc, 953 const TemplateArgumentList &TemplateArgs) { 954 if (TemplateTemplateParmDecl *TTP 955 = dyn_cast_or_null<TemplateTemplateParmDecl>( 956 Name.getAsTemplateDecl())) { 957 assert(TTP->getDepth() == 0 && 958 "Cannot reduce depth of a template template parameter"); 959 assert(TemplateArgs[TTP->getPosition()].getAsDecl() && 960 "Wrong kind of template template argument"); 961 ClassTemplateDecl *ClassTemplate 962 = dyn_cast<ClassTemplateDecl>( 963 TemplateArgs[TTP->getPosition()].getAsDecl()); 964 assert(ClassTemplate && "Expected a class template"); 965 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) { 966 NestedNameSpecifier *NNS 967 = InstantiateNestedNameSpecifier(QTN->getQualifier(), 968 /*FIXME=*/SourceRange(Loc), 969 TemplateArgs); 970 if (NNS) 971 return Context.getQualifiedTemplateName(NNS, 972 QTN->hasTemplateKeyword(), 973 ClassTemplate); 974 } 975 976 return TemplateName(ClassTemplate); 977 } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) { 978 NestedNameSpecifier *NNS 979 = InstantiateNestedNameSpecifier(DTN->getQualifier(), 980 /*FIXME=*/SourceRange(Loc), 981 TemplateArgs); 982 983 if (!NNS) // FIXME: Not the best recovery strategy. 984 return Name; 985 986 if (NNS->isDependent()) 987 return Context.getDependentTemplateName(NNS, DTN->getName()); 988 989 // Somewhat redundant with ActOnDependentTemplateName. 990 CXXScopeSpec SS; 991 SS.setRange(SourceRange(Loc)); 992 SS.setScopeRep(NNS); 993 TemplateTy Template; 994 TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS); 995 if (TNK == TNK_Non_template) { 996 Diag(Loc, diag::err_template_kw_refers_to_non_template) 997 << DTN->getName(); 998 return Name; 999 } else if (TNK == TNK_Function_template) { 1000 Diag(Loc, diag::err_template_kw_refers_to_non_template) 1001 << DTN->getName(); 1002 return Name; 1003 } 1004 1005 return Template.getAsVal<TemplateName>(); 1006 } 1007 1008 1009 1010 // FIXME: Even if we're referring to a Decl that isn't a template template 1011 // parameter, we may need to instantiate the outer contexts of that 1012 // Decl. However, this won't be needed until we implement member templates. 1013 return Name; 1014} 1015