SemaTemplateInstantiate.cpp revision fd056bc86a8b22a9421b5d921bbca276d0f9d0f7
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 "TreeTransform.h" 15#include "clang/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/Expr.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/Parse/DeclSpec.h" 20#include "clang/Basic/LangOptions.h" 21#include "llvm/Support/Compiler.h" 22 23using namespace clang; 24 25//===----------------------------------------------------------------------===/ 26// Template Instantiation Support 27//===----------------------------------------------------------------------===/ 28 29/// \brief Retrieve the template argument list(s) that should be used to 30/// instantiate the definition of the given declaration. 31MultiLevelTemplateArgumentList 32Sema::getTemplateInstantiationArgs(NamedDecl *D) { 33 // Accumulate the set of template argument lists in this structure. 34 MultiLevelTemplateArgumentList Result; 35 36 DeclContext *Ctx = dyn_cast<DeclContext>(D); 37 if (!Ctx) 38 Ctx = D->getDeclContext(); 39 40 while (!Ctx->isFileContext()) { 41 // Add template arguments from a class template instantiation. 42 if (ClassTemplateSpecializationDecl *Spec 43 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) { 44 // We're done when we hit an explicit specialization. 45 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization) 46 break; 47 48 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); 49 50 // If this class template specialization was instantiated from a 51 // specialized member that is a class template, we're done. 52 assert(Spec->getSpecializedTemplate() && "No class template?"); 53 if (Spec->getSpecializedTemplate()->isMemberSpecialization()) 54 break; 55 } 56 // Add template arguments from a function template specialization. 57 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) { 58 if (Function->getTemplateSpecializationKind() 59 == TSK_ExplicitSpecialization) 60 break; 61 62 if (const TemplateArgumentList *TemplateArgs 63 = Function->getTemplateSpecializationArgs()) { 64 // Add the template arguments for this specialization. 65 Result.addOuterTemplateArguments(TemplateArgs); 66 67 // If this function was instantiated from a specialized member that is 68 // a function template, we're done. 69 assert(Function->getPrimaryTemplate() && "No function template?"); 70 if (Function->getPrimaryTemplate()->isMemberSpecialization()) 71 break; 72 } 73 74 // If this is a friend declaration and it declares an entity at 75 // namespace scope, take arguments from its lexical parent 76 // instead of its semantic parent. 77 if (Function->getFriendObjectKind() && 78 Function->getDeclContext()->isFileContext()) { 79 Ctx = Function->getLexicalDeclContext(); 80 continue; 81 } 82 } 83 84 Ctx = Ctx->getParent(); 85 } 86 87 return Result; 88} 89 90Sema::InstantiatingTemplate:: 91InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 92 Decl *Entity, 93 SourceRange InstantiationRange) 94 : SemaRef(SemaRef) { 95 96 Invalid = CheckInstantiationDepth(PointOfInstantiation, 97 InstantiationRange); 98 if (!Invalid) { 99 ActiveTemplateInstantiation Inst; 100 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation; 101 Inst.PointOfInstantiation = PointOfInstantiation; 102 Inst.Entity = reinterpret_cast<uintptr_t>(Entity); 103 Inst.TemplateArgs = 0; 104 Inst.NumTemplateArgs = 0; 105 Inst.InstantiationRange = InstantiationRange; 106 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 107 Invalid = false; 108 } 109} 110 111Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 112 SourceLocation PointOfInstantiation, 113 TemplateDecl *Template, 114 const TemplateArgument *TemplateArgs, 115 unsigned NumTemplateArgs, 116 SourceRange InstantiationRange) 117 : SemaRef(SemaRef) { 118 119 Invalid = CheckInstantiationDepth(PointOfInstantiation, 120 InstantiationRange); 121 if (!Invalid) { 122 ActiveTemplateInstantiation Inst; 123 Inst.Kind 124 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation; 125 Inst.PointOfInstantiation = PointOfInstantiation; 126 Inst.Entity = reinterpret_cast<uintptr_t>(Template); 127 Inst.TemplateArgs = TemplateArgs; 128 Inst.NumTemplateArgs = NumTemplateArgs; 129 Inst.InstantiationRange = InstantiationRange; 130 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 131 Invalid = false; 132 } 133} 134 135Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 136 SourceLocation PointOfInstantiation, 137 FunctionTemplateDecl *FunctionTemplate, 138 const TemplateArgument *TemplateArgs, 139 unsigned NumTemplateArgs, 140 ActiveTemplateInstantiation::InstantiationKind Kind, 141 SourceRange InstantiationRange) 142: SemaRef(SemaRef) { 143 144 Invalid = CheckInstantiationDepth(PointOfInstantiation, 145 InstantiationRange); 146 if (!Invalid) { 147 ActiveTemplateInstantiation Inst; 148 Inst.Kind = Kind; 149 Inst.PointOfInstantiation = PointOfInstantiation; 150 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate); 151 Inst.TemplateArgs = TemplateArgs; 152 Inst.NumTemplateArgs = NumTemplateArgs; 153 Inst.InstantiationRange = InstantiationRange; 154 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 155 Invalid = false; 156 } 157} 158 159Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 160 SourceLocation PointOfInstantiation, 161 ClassTemplatePartialSpecializationDecl *PartialSpec, 162 const TemplateArgument *TemplateArgs, 163 unsigned NumTemplateArgs, 164 SourceRange InstantiationRange) 165 : SemaRef(SemaRef) { 166 167 Invalid = CheckInstantiationDepth(PointOfInstantiation, 168 InstantiationRange); 169 if (!Invalid) { 170 ActiveTemplateInstantiation Inst; 171 Inst.Kind 172 = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution; 173 Inst.PointOfInstantiation = PointOfInstantiation; 174 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec); 175 Inst.TemplateArgs = TemplateArgs; 176 Inst.NumTemplateArgs = NumTemplateArgs; 177 Inst.InstantiationRange = InstantiationRange; 178 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 179 Invalid = false; 180 } 181} 182 183Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 184 SourceLocation PointOfInstantation, 185 ParmVarDecl *Param, 186 const TemplateArgument *TemplateArgs, 187 unsigned NumTemplateArgs, 188 SourceRange InstantiationRange) 189 : SemaRef(SemaRef) { 190 191 Invalid = CheckInstantiationDepth(PointOfInstantation, InstantiationRange); 192 193 if (!Invalid) { 194 ActiveTemplateInstantiation Inst; 195 Inst.Kind 196 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 197 Inst.PointOfInstantiation = PointOfInstantation; 198 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 199 Inst.TemplateArgs = TemplateArgs; 200 Inst.NumTemplateArgs = NumTemplateArgs; 201 Inst.InstantiationRange = InstantiationRange; 202 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 203 Invalid = false; 204 } 205} 206 207void Sema::InstantiatingTemplate::Clear() { 208 if (!Invalid) { 209 SemaRef.ActiveTemplateInstantiations.pop_back(); 210 Invalid = true; 211 } 212} 213 214bool Sema::InstantiatingTemplate::CheckInstantiationDepth( 215 SourceLocation PointOfInstantiation, 216 SourceRange InstantiationRange) { 217 if (SemaRef.ActiveTemplateInstantiations.size() 218 <= SemaRef.getLangOptions().InstantiationDepth) 219 return false; 220 221 SemaRef.Diag(PointOfInstantiation, 222 diag::err_template_recursion_depth_exceeded) 223 << SemaRef.getLangOptions().InstantiationDepth 224 << InstantiationRange; 225 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) 226 << SemaRef.getLangOptions().InstantiationDepth; 227 return true; 228} 229 230/// \brief Prints the current instantiation stack through a series of 231/// notes. 232void Sema::PrintInstantiationStack() { 233 // FIXME: In all of these cases, we need to show the template arguments 234 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator 235 Active = ActiveTemplateInstantiations.rbegin(), 236 ActiveEnd = ActiveTemplateInstantiations.rend(); 237 Active != ActiveEnd; 238 ++Active) { 239 switch (Active->Kind) { 240 case ActiveTemplateInstantiation::TemplateInstantiation: { 241 Decl *D = reinterpret_cast<Decl *>(Active->Entity); 242 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 243 unsigned DiagID = diag::note_template_member_class_here; 244 if (isa<ClassTemplateSpecializationDecl>(Record)) 245 DiagID = diag::note_template_class_instantiation_here; 246 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 247 DiagID) 248 << Context.getTypeDeclType(Record) 249 << Active->InstantiationRange; 250 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 251 unsigned DiagID; 252 if (Function->getPrimaryTemplate()) 253 DiagID = diag::note_function_template_spec_here; 254 else 255 DiagID = diag::note_template_member_function_here; 256 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 257 DiagID) 258 << Function 259 << Active->InstantiationRange; 260 } else { 261 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 262 diag::note_template_static_data_member_def_here) 263 << cast<VarDecl>(D) 264 << Active->InstantiationRange; 265 } 266 break; 267 } 268 269 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: { 270 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity); 271 std::string TemplateArgsStr 272 = TemplateSpecializationType::PrintTemplateArgumentList( 273 Active->TemplateArgs, 274 Active->NumTemplateArgs, 275 Context.PrintingPolicy); 276 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 277 diag::note_default_arg_instantiation_here) 278 << (Template->getNameAsString() + TemplateArgsStr) 279 << Active->InstantiationRange; 280 break; 281 } 282 283 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: { 284 FunctionTemplateDecl *FnTmpl 285 = cast<FunctionTemplateDecl>((Decl *)Active->Entity); 286 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 287 diag::note_explicit_template_arg_substitution_here) 288 << FnTmpl << Active->InstantiationRange; 289 break; 290 } 291 292 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 293 if (ClassTemplatePartialSpecializationDecl *PartialSpec 294 = dyn_cast<ClassTemplatePartialSpecializationDecl>( 295 (Decl *)Active->Entity)) { 296 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 297 diag::note_partial_spec_deduct_instantiation_here) 298 << Context.getTypeDeclType(PartialSpec) 299 << Active->InstantiationRange; 300 } else { 301 FunctionTemplateDecl *FnTmpl 302 = cast<FunctionTemplateDecl>((Decl *)Active->Entity); 303 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 304 diag::note_function_template_deduction_instantiation_here) 305 << FnTmpl << Active->InstantiationRange; 306 } 307 break; 308 309 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: { 310 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity); 311 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); 312 313 std::string TemplateArgsStr 314 = TemplateSpecializationType::PrintTemplateArgumentList( 315 Active->TemplateArgs, 316 Active->NumTemplateArgs, 317 Context.PrintingPolicy); 318 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 319 diag::note_default_function_arg_instantiation_here) 320 << (FD->getNameAsString() + TemplateArgsStr) 321 << Active->InstantiationRange; 322 break; 323 } 324 325 } 326 } 327} 328 329bool Sema::isSFINAEContext() const { 330 using llvm::SmallVector; 331 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator 332 Active = ActiveTemplateInstantiations.rbegin(), 333 ActiveEnd = ActiveTemplateInstantiations.rend(); 334 Active != ActiveEnd; 335 ++Active) { 336 337 switch(Active->Kind) { 338 case ActiveTemplateInstantiation::TemplateInstantiation: 339 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: 340 341 // This is a template instantiation, so there is no SFINAE. 342 return false; 343 344 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: 345 // A default template argument instantiation may or may not be a 346 // SFINAE context; look further up the stack. 347 break; 348 349 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: 350 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 351 // We're either substitution explicitly-specified template arguments 352 // or deduced template arguments, so SFINAE applies. 353 return true; 354 } 355 } 356 357 return false; 358} 359 360//===----------------------------------------------------------------------===/ 361// Template Instantiation for Types 362//===----------------------------------------------------------------------===/ 363namespace { 364 class VISIBILITY_HIDDEN TemplateInstantiator 365 : public TreeTransform<TemplateInstantiator> { 366 const MultiLevelTemplateArgumentList &TemplateArgs; 367 SourceLocation Loc; 368 DeclarationName Entity; 369 370 public: 371 typedef TreeTransform<TemplateInstantiator> inherited; 372 373 TemplateInstantiator(Sema &SemaRef, 374 const MultiLevelTemplateArgumentList &TemplateArgs, 375 SourceLocation Loc, 376 DeclarationName Entity) 377 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), 378 Entity(Entity) { } 379 380 /// \brief Determine whether the given type \p T has already been 381 /// transformed. 382 /// 383 /// For the purposes of template instantiation, a type has already been 384 /// transformed if it is NULL or if it is not dependent. 385 bool AlreadyTransformed(QualType T) { 386 return T.isNull() || !T->isDependentType(); 387 } 388 389 /// \brief Returns the location of the entity being instantiated, if known. 390 SourceLocation getBaseLocation() { return Loc; } 391 392 /// \brief Returns the name of the entity being instantiated, if any. 393 DeclarationName getBaseEntity() { return Entity; } 394 395 /// \brief Transform the given declaration by instantiating a reference to 396 /// this declaration. 397 Decl *TransformDecl(Decl *D); 398 399 /// \brief Transform the definition of the given declaration by 400 /// instantiating it. 401 Decl *TransformDefinition(Decl *D); 402 403 /// \brief Rebuild the exception declaration and register the declaration 404 /// as an instantiated local. 405 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, QualType T, 406 DeclaratorInfo *Declarator, 407 IdentifierInfo *Name, 408 SourceLocation Loc, SourceRange TypeRange); 409 410 /// \brief Check for tag mismatches when instantiating an 411 /// elaborated type. 412 QualType RebuildElaboratedType(QualType T, ElaboratedType::TagKind Tag); 413 414 Sema::OwningExprResult TransformPredefinedExpr(PredefinedExpr *E); 415 Sema::OwningExprResult TransformDeclRefExpr(DeclRefExpr *E); 416 417 /// \brief Transforms a template type parameter type by performing 418 /// substitution of the corresponding template type argument. 419 QualType TransformTemplateTypeParmType(const TemplateTypeParmType *T); 420 }; 421} 422 423Decl *TemplateInstantiator::TransformDecl(Decl *D) { 424 if (!D) 425 return 0; 426 427 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) { 428 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 429 assert(TemplateArgs(TTP->getDepth(), TTP->getPosition()).getAsDecl() && 430 "Wrong kind of template template argument"); 431 return cast<TemplateDecl>(TemplateArgs(TTP->getDepth(), 432 TTP->getPosition()).getAsDecl()); 433 } 434 435 // If the corresponding template argument is NULL or non-existent, it's 436 // because we are performing instantiation from explicitly-specified 437 // template arguments in a function template, but there were some 438 // arguments left unspecified. 439 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), 440 TTP->getPosition())) 441 return D; 442 443 // FIXME: Implement depth reduction of template template parameters 444 assert(false && 445 "Reducing depth of template template parameters is not yet implemented"); 446 } 447 448 return SemaRef.FindInstantiatedDecl(cast<NamedDecl>(D), TemplateArgs); 449} 450 451Decl *TemplateInstantiator::TransformDefinition(Decl *D) { 452 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs); 453 if (!Inst) 454 return 0; 455 456 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); 457 return Inst; 458} 459 460VarDecl * 461TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, 462 QualType T, 463 DeclaratorInfo *Declarator, 464 IdentifierInfo *Name, 465 SourceLocation Loc, 466 SourceRange TypeRange) { 467 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, T, Declarator, 468 Name, Loc, TypeRange); 469 if (Var && !Var->isInvalidDecl()) 470 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); 471 return Var; 472} 473 474QualType 475TemplateInstantiator::RebuildElaboratedType(QualType T, 476 ElaboratedType::TagKind Tag) { 477 if (const TagType *TT = T->getAs<TagType>()) { 478 TagDecl* TD = TT->getDecl(); 479 480 // FIXME: this location is very wrong; we really need typelocs. 481 SourceLocation TagLocation = TD->getTagKeywordLoc(); 482 483 // FIXME: type might be anonymous. 484 IdentifierInfo *Id = TD->getIdentifier(); 485 486 // TODO: should we even warn on struct/class mismatches for this? Seems 487 // like it's likely to produce a lot of spurious errors. 488 if (!SemaRef.isAcceptableTagRedeclaration(TD, Tag, TagLocation, *Id)) { 489 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag) 490 << Id 491 << CodeModificationHint::CreateReplacement(SourceRange(TagLocation), 492 TD->getKindName()); 493 SemaRef.Diag(TD->getLocation(), diag::note_previous_use); 494 } 495 } 496 497 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(T, Tag); 498} 499 500Sema::OwningExprResult 501TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { 502 if (!E->isTypeDependent()) 503 return SemaRef.Owned(E->Retain()); 504 505 FunctionDecl *currentDecl = getSema().getCurFunctionDecl(); 506 assert(currentDecl && "Must have current function declaration when " 507 "instantiating."); 508 509 PredefinedExpr::IdentType IT = E->getIdentType(); 510 511 unsigned Length = 512 PredefinedExpr::ComputeName(getSema().Context, IT, currentDecl).length(); 513 514 llvm::APInt LengthI(32, Length + 1); 515 QualType ResTy = getSema().Context.CharTy.withConst(); 516 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI, 517 ArrayType::Normal, 0); 518 PredefinedExpr *PE = 519 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT); 520 return getSema().Owned(PE); 521} 522 523Sema::OwningExprResult 524TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { 525 // FIXME: Clean this up a bit 526 NamedDecl *D = E->getDecl(); 527 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { 528 if (NTTP->getDepth() >= TemplateArgs.getNumLevels()) { 529 assert(false && "Cannot reduce non-type template parameter depth yet"); 530 return getSema().ExprError(); 531 } 532 533 // If the corresponding template argument is NULL or non-existent, it's 534 // because we are performing instantiation from explicitly-specified 535 // template arguments in a function template, but there were some 536 // arguments left unspecified. 537 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(), 538 NTTP->getPosition())) 539 return SemaRef.Owned(E->Retain()); 540 541 const TemplateArgument &Arg = TemplateArgs(NTTP->getDepth(), 542 NTTP->getPosition()); 543 544 // The template argument itself might be an expression, in which 545 // case we just return that expression. 546 if (Arg.getKind() == TemplateArgument::Expression) 547 return SemaRef.Owned(Arg.getAsExpr()->Retain()); 548 549 if (Arg.getKind() == TemplateArgument::Declaration) { 550 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl()); 551 552 VD = cast_or_null<ValueDecl>( 553 getSema().FindInstantiatedDecl(VD, TemplateArgs)); 554 if (!VD) 555 return SemaRef.ExprError(); 556 557 return SemaRef.BuildDeclRefExpr(VD, VD->getType(), E->getLocation(), 558 /*FIXME:*/false, /*FIXME:*/false); 559 } 560 561 assert(Arg.getKind() == TemplateArgument::Integral); 562 QualType T = Arg.getIntegralType(); 563 if (T->isCharType() || T->isWideCharType()) 564 return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral( 565 Arg.getAsIntegral()->getZExtValue(), 566 T->isWideCharType(), 567 T, 568 E->getSourceRange().getBegin())); 569 if (T->isBooleanType()) 570 return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr( 571 Arg.getAsIntegral()->getBoolValue(), 572 T, 573 E->getSourceRange().getBegin())); 574 575 assert(Arg.getAsIntegral()->getBitWidth() == SemaRef.Context.getIntWidth(T)); 576 return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral( 577 *Arg.getAsIntegral(), 578 T, 579 E->getSourceRange().getBegin())); 580 } 581 582 NamedDecl *InstD = SemaRef.FindInstantiatedDecl(D, TemplateArgs); 583 if (!InstD) 584 return SemaRef.ExprError(); 585 586 // If we instantiated an UnresolvedUsingDecl and got back an UsingDecl, 587 // we need to get the underlying decl. 588 // FIXME: Is this correct? Maybe FindInstantiatedDecl should do this? 589 InstD = InstD->getUnderlyingDecl(); 590 591 // FIXME: nested-name-specifier for QualifiedDeclRefExpr 592 return SemaRef.BuildDeclarationNameExpr(E->getLocation(), InstD, 593 /*FIXME:*/false, 594 /*FIXME:*/0, 595 /*FIXME:*/false); 596} 597 598QualType 599TemplateInstantiator::TransformTemplateTypeParmType( 600 const TemplateTypeParmType *T) { 601 if (T->getDepth() < TemplateArgs.getNumLevels()) { 602 // Replace the template type parameter with its corresponding 603 // template argument. 604 605 // If the corresponding template argument is NULL or doesn't exist, it's 606 // because we are performing instantiation from explicitly-specified 607 // template arguments in a function template class, but there were some 608 // arguments left unspecified. 609 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) 610 return QualType(T, 0); 611 612 assert(TemplateArgs(T->getDepth(), T->getIndex()).getKind() 613 == TemplateArgument::Type && 614 "Template argument kind mismatch"); 615 616 return TemplateArgs(T->getDepth(), T->getIndex()).getAsType(); 617 } 618 619 // The template type parameter comes from an inner template (e.g., 620 // the template parameter list of a member template inside the 621 // template we are instantiating). Create a new template type 622 // parameter with the template "level" reduced by one. 623 return getSema().Context.getTemplateTypeParmType( 624 T->getDepth() - TemplateArgs.getNumLevels(), 625 T->getIndex(), 626 T->isParameterPack(), 627 T->getName()); 628} 629 630/// \brief Perform substitution on the type T with a given set of template 631/// arguments. 632/// 633/// This routine substitutes the given template arguments into the 634/// type T and produces the instantiated type. 635/// 636/// \param T the type into which the template arguments will be 637/// substituted. If this type is not dependent, it will be returned 638/// immediately. 639/// 640/// \param TemplateArgs the template arguments that will be 641/// substituted for the top-level template parameters within T. 642/// 643/// \param Loc the location in the source code where this substitution 644/// is being performed. It will typically be the location of the 645/// declarator (if we're instantiating the type of some declaration) 646/// or the location of the type in the source code (if, e.g., we're 647/// instantiating the type of a cast expression). 648/// 649/// \param Entity the name of the entity associated with a declaration 650/// being instantiated (if any). May be empty to indicate that there 651/// is no such entity (if, e.g., this is a type that occurs as part of 652/// a cast expression) or that the entity has no name (e.g., an 653/// unnamed function parameter). 654/// 655/// \returns If the instantiation succeeds, the instantiated 656/// type. Otherwise, produces diagnostics and returns a NULL type. 657QualType Sema::SubstType(QualType T, 658 const MultiLevelTemplateArgumentList &TemplateArgs, 659 SourceLocation Loc, DeclarationName Entity) { 660 assert(!ActiveTemplateInstantiations.empty() && 661 "Cannot perform an instantiation without some context on the " 662 "instantiation stack"); 663 664 // If T is not a dependent type, there is nothing to do. 665 if (!T->isDependentType()) 666 return T; 667 668 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); 669 return Instantiator.TransformType(T); 670} 671 672/// \brief Perform substitution on the base class specifiers of the 673/// given class template specialization. 674/// 675/// Produces a diagnostic and returns true on error, returns false and 676/// attaches the instantiated base classes to the class template 677/// specialization if successful. 678bool 679Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 680 CXXRecordDecl *Pattern, 681 const MultiLevelTemplateArgumentList &TemplateArgs) { 682 bool Invalid = false; 683 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; 684 for (ClassTemplateSpecializationDecl::base_class_iterator 685 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end(); 686 Base != BaseEnd; ++Base) { 687 if (!Base->getType()->isDependentType()) { 688 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base)); 689 continue; 690 } 691 692 QualType BaseType = SubstType(Base->getType(), 693 TemplateArgs, 694 Base->getSourceRange().getBegin(), 695 DeclarationName()); 696 if (BaseType.isNull()) { 697 Invalid = true; 698 continue; 699 } 700 701 if (CXXBaseSpecifier *InstantiatedBase 702 = CheckBaseSpecifier(Instantiation, 703 Base->getSourceRange(), 704 Base->isVirtual(), 705 Base->getAccessSpecifierAsWritten(), 706 BaseType, 707 /*FIXME: Not totally accurate */ 708 Base->getSourceRange().getBegin())) 709 InstantiatedBases.push_back(InstantiatedBase); 710 else 711 Invalid = true; 712 } 713 714 if (!Invalid && 715 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(), 716 InstantiatedBases.size())) 717 Invalid = true; 718 719 return Invalid; 720} 721 722/// \brief Instantiate the definition of a class from a given pattern. 723/// 724/// \param PointOfInstantiation The point of instantiation within the 725/// source code. 726/// 727/// \param Instantiation is the declaration whose definition is being 728/// instantiated. This will be either a class template specialization 729/// or a member class of a class template specialization. 730/// 731/// \param Pattern is the pattern from which the instantiation 732/// occurs. This will be either the declaration of a class template or 733/// the declaration of a member class of a class template. 734/// 735/// \param TemplateArgs The template arguments to be substituted into 736/// the pattern. 737/// 738/// \param TSK the kind of implicit or explicit instantiation to perform. 739/// 740/// \param Complain whether to complain if the class cannot be instantiated due 741/// to the lack of a definition. 742/// 743/// \returns true if an error occurred, false otherwise. 744bool 745Sema::InstantiateClass(SourceLocation PointOfInstantiation, 746 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 747 const MultiLevelTemplateArgumentList &TemplateArgs, 748 TemplateSpecializationKind TSK, 749 bool Complain) { 750 bool Invalid = false; 751 752 CXXRecordDecl *PatternDef 753 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context)); 754 if (!PatternDef) { 755 if (!Complain) { 756 // Say nothing 757 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) { 758 Diag(PointOfInstantiation, 759 diag::err_implicit_instantiate_member_undefined) 760 << Context.getTypeDeclType(Instantiation); 761 Diag(Pattern->getLocation(), diag::note_member_of_template_here); 762 } else { 763 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 764 << (TSK != TSK_ImplicitInstantiation) 765 << Context.getTypeDeclType(Instantiation); 766 Diag(Pattern->getLocation(), diag::note_template_decl_here); 767 } 768 return true; 769 } 770 Pattern = PatternDef; 771 772 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 773 if (Inst) 774 return true; 775 776 // Enter the scope of this instantiation. We don't use 777 // PushDeclContext because we don't have a scope. 778 DeclContext *PreviousContext = CurContext; 779 CurContext = Instantiation; 780 781 // Start the definition of this instantiation. 782 Instantiation->startDefinition(); 783 784 // Do substitution on the base class specifiers. 785 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) 786 Invalid = true; 787 788 llvm::SmallVector<DeclPtrTy, 4> Fields; 789 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(), 790 MemberEnd = Pattern->decls_end(); 791 Member != MemberEnd; ++Member) { 792 Decl *NewMember = SubstDecl(*Member, Instantiation, TemplateArgs); 793 if (NewMember) { 794 if (NewMember->isInvalidDecl()) 795 Invalid = true; 796 else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) 797 Fields.push_back(DeclPtrTy::make(Field)); 798 else if (UsingDecl *UD = dyn_cast<UsingDecl>(NewMember)) 799 Instantiation->addDecl(UD); 800 } else { 801 // FIXME: Eventually, a NULL return will mean that one of the 802 // instantiations was a semantic disaster, and we'll want to set Invalid = 803 // true. For now, we expect to skip some members that we can't yet handle. 804 } 805 } 806 807 // Finish checking fields. 808 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation), 809 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(), 810 0); 811 812 // Add any implicitly-declared members that we might need. 813 AddImplicitlyDeclaredMembersToClass(Instantiation); 814 815 // Exit the scope of this instantiation. 816 CurContext = PreviousContext; 817 818 if (!Invalid) 819 Consumer.HandleTagDeclDefinition(Instantiation); 820 821 // If this is an explicit instantiation, instantiate our members, too. 822 if (!Invalid && TSK != TSK_ImplicitInstantiation) { 823 Inst.Clear(); 824 InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs, 825 TSK); 826 } 827 828 return Invalid; 829} 830 831bool 832Sema::InstantiateClassTemplateSpecialization( 833 ClassTemplateSpecializationDecl *ClassTemplateSpec, 834 TemplateSpecializationKind TSK, 835 bool Complain) { 836 // Perform the actual instantiation on the canonical declaration. 837 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 838 ClassTemplateSpec->getCanonicalDecl()); 839 840 // Check whether we have already instantiated or specialized this class 841 // template specialization. 842 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) { 843 if (ClassTemplateSpec->getSpecializationKind() == 844 TSK_ExplicitInstantiationDeclaration && 845 TSK == TSK_ExplicitInstantiationDefinition) { 846 // An explicit instantiation definition follows an explicit instantiation 847 // declaration (C++0x [temp.explicit]p10); go ahead and perform the 848 // explicit instantiation. 849 ClassTemplateSpec->setSpecializationKind(TSK); 850 InstantiateClassTemplateSpecializationMembers( 851 /*FIXME?*/ClassTemplateSpec->getPointOfInstantiation(), 852 ClassTemplateSpec, 853 TSK); 854 return false; 855 } 856 857 // We can only instantiate something that hasn't already been 858 // instantiated or specialized. Fail without any diagnostics: our 859 // caller will provide an error message. 860 return true; 861 } 862 863 if (ClassTemplateSpec->isInvalidDecl()) 864 return true; 865 866 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 867 CXXRecordDecl *Pattern = 0; 868 869 // C++ [temp.class.spec.match]p1: 870 // When a class template is used in a context that requires an 871 // instantiation of the class, it is necessary to determine 872 // whether the instantiation is to be generated using the primary 873 // template or one of the partial specializations. This is done by 874 // matching the template arguments of the class template 875 // specialization with the template argument lists of the partial 876 // specializations. 877 typedef std::pair<ClassTemplatePartialSpecializationDecl *, 878 TemplateArgumentList *> MatchResult; 879 llvm::SmallVector<MatchResult, 4> Matched; 880 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 881 Partial = Template->getPartialSpecializations().begin(), 882 PartialEnd = Template->getPartialSpecializations().end(); 883 Partial != PartialEnd; 884 ++Partial) { 885 TemplateDeductionInfo Info(Context); 886 if (TemplateDeductionResult Result 887 = DeduceTemplateArguments(&*Partial, 888 ClassTemplateSpec->getTemplateArgs(), 889 Info)) { 890 // FIXME: Store the failed-deduction information for use in 891 // diagnostics, later. 892 (void)Result; 893 } else { 894 Matched.push_back(std::make_pair(&*Partial, Info.take())); 895 } 896 } 897 898 if (Matched.size() == 1) { 899 // -- If exactly one matching specialization is found, the 900 // instantiation is generated from that specialization. 901 Pattern = Matched[0].first; 902 ClassTemplateSpec->setInstantiationOf(Matched[0].first, Matched[0].second); 903 } else if (Matched.size() > 1) { 904 // -- If more than one matching specialization is found, the 905 // partial order rules (14.5.4.2) are used to determine 906 // whether one of the specializations is more specialized 907 // than the others. If none of the specializations is more 908 // specialized than all of the other matching 909 // specializations, then the use of the class template is 910 // ambiguous and the program is ill-formed. 911 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); 912 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1, 913 PEnd = Matched.end(); 914 P != PEnd; ++P) { 915 if (getMoreSpecializedPartialSpecialization(P->first, Best->first) 916 == P->first) 917 Best = P; 918 } 919 920 // Determine if the best partial specialization is more specialized than 921 // the others. 922 bool Ambiguous = false; 923 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 924 PEnd = Matched.end(); 925 P != PEnd; ++P) { 926 if (P != Best && 927 getMoreSpecializedPartialSpecialization(P->first, Best->first) 928 != Best->first) { 929 Ambiguous = true; 930 break; 931 } 932 } 933 934 if (Ambiguous) { 935 // Partial ordering did not produce a clear winner. Complain. 936 ClassTemplateSpec->setInvalidDecl(); 937 Diag(ClassTemplateSpec->getPointOfInstantiation(), 938 diag::err_partial_spec_ordering_ambiguous) 939 << ClassTemplateSpec; 940 941 // Print the matching partial specializations. 942 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 943 PEnd = Matched.end(); 944 P != PEnd; ++P) 945 Diag(P->first->getLocation(), diag::note_partial_spec_match) 946 << getTemplateArgumentBindingsText(P->first->getTemplateParameters(), 947 *P->second); 948 949 return true; 950 } 951 952 // Instantiate using the best class template partial specialization. 953 Pattern = Best->first; 954 ClassTemplateSpec->setInstantiationOf(Best->first, Best->second); 955 } else { 956 // -- If no matches are found, the instantiation is generated 957 // from the primary template. 958 ClassTemplateDecl *OrigTemplate = Template; 959 while (OrigTemplate->getInstantiatedFromMemberTemplate()) { 960 // If we've found an explicit specialization of this class template, 961 // stop here and use that as the pattern. 962 if (OrigTemplate->isMemberSpecialization()) 963 break; 964 965 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate(); 966 } 967 968 Pattern = OrigTemplate->getTemplatedDecl(); 969 } 970 971 // Note that this is an instantiation. 972 ClassTemplateSpec->setSpecializationKind(TSK); 973 974 bool Result = InstantiateClass(ClassTemplateSpec->getPointOfInstantiation(), 975 ClassTemplateSpec, Pattern, 976 getTemplateInstantiationArgs(ClassTemplateSpec), 977 TSK, 978 Complain); 979 980 for (unsigned I = 0, N = Matched.size(); I != N; ++I) { 981 // FIXME: Implement TemplateArgumentList::Destroy! 982 // if (Matched[I].first != Pattern) 983 // Matched[I].second->Destroy(Context); 984 } 985 986 return Result; 987} 988 989/// \brief Instantiates the definitions of all of the member 990/// of the given class, which is an instantiation of a class template 991/// or a member class of a template. 992void 993Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 994 CXXRecordDecl *Instantiation, 995 const MultiLevelTemplateArgumentList &TemplateArgs, 996 TemplateSpecializationKind TSK) { 997 for (DeclContext::decl_iterator D = Instantiation->decls_begin(), 998 DEnd = Instantiation->decls_end(); 999 D != DEnd; ++D) { 1000 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) { 1001 if (Function->getInstantiatedFromMemberFunction()) { 1002 // If this member was explicitly specialized, do nothing. 1003 if (Function->getTemplateSpecializationKind() == 1004 TSK_ExplicitSpecialization) 1005 continue; 1006 1007 Function->setTemplateSpecializationKind(TSK); 1008 } 1009 1010 if (!Function->getBody() && TSK == TSK_ExplicitInstantiationDefinition) 1011 InstantiateFunctionDefinition(PointOfInstantiation, Function); 1012 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) { 1013 if (Var->isStaticDataMember()) { 1014 // If this member was explicitly specialized, do nothing. 1015 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1016 continue; 1017 1018 Var->setTemplateSpecializationKind(TSK); 1019 1020 if (TSK == TSK_ExplicitInstantiationDefinition) 1021 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var); 1022 } 1023 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) { 1024 if (Record->isInjectedClassName()) 1025 continue; 1026 1027 assert(Record->getInstantiatedFromMemberClass() && 1028 "Missing instantiated-from-template information"); 1029 1030 // If this member was explicitly specialized, do nothing. 1031 if (Record->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1032 continue; 1033 1034 if (!Record->getDefinition(Context)) 1035 InstantiateClass(PointOfInstantiation, Record, 1036 Record->getInstantiatedFromMemberClass(), 1037 TemplateArgs, 1038 TSK); 1039 1040 InstantiateClassMembers(PointOfInstantiation, Record, TemplateArgs, 1041 TSK); 1042 } 1043 } 1044} 1045 1046/// \brief Instantiate the definitions of all of the members of the 1047/// given class template specialization, which was named as part of an 1048/// explicit instantiation. 1049void 1050Sema::InstantiateClassTemplateSpecializationMembers( 1051 SourceLocation PointOfInstantiation, 1052 ClassTemplateSpecializationDecl *ClassTemplateSpec, 1053 TemplateSpecializationKind TSK) { 1054 // C++0x [temp.explicit]p7: 1055 // An explicit instantiation that names a class template 1056 // specialization is an explicit instantion of the same kind 1057 // (declaration or definition) of each of its members (not 1058 // including members inherited from base classes) that has not 1059 // been previously explicitly specialized in the translation unit 1060 // containing the explicit instantiation, except as described 1061 // below. 1062 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 1063 getTemplateInstantiationArgs(ClassTemplateSpec), 1064 TSK); 1065} 1066 1067Sema::OwningStmtResult 1068Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { 1069 if (!S) 1070 return Owned(S); 1071 1072 TemplateInstantiator Instantiator(*this, TemplateArgs, 1073 SourceLocation(), 1074 DeclarationName()); 1075 return Instantiator.TransformStmt(S); 1076} 1077 1078Sema::OwningExprResult 1079Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 1080 if (!E) 1081 return Owned(E); 1082 1083 TemplateInstantiator Instantiator(*this, TemplateArgs, 1084 SourceLocation(), 1085 DeclarationName()); 1086 return Instantiator.TransformExpr(E); 1087} 1088 1089/// \brief Do template substitution on a nested-name-specifier. 1090NestedNameSpecifier * 1091Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS, 1092 SourceRange Range, 1093 const MultiLevelTemplateArgumentList &TemplateArgs) { 1094 TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(), 1095 DeclarationName()); 1096 return Instantiator.TransformNestedNameSpecifier(NNS, Range); 1097} 1098 1099TemplateName 1100Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc, 1101 const MultiLevelTemplateArgumentList &TemplateArgs) { 1102 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 1103 DeclarationName()); 1104 return Instantiator.TransformTemplateName(Name); 1105} 1106 1107TemplateArgument Sema::Subst(TemplateArgument Arg, 1108 const MultiLevelTemplateArgumentList &TemplateArgs) { 1109 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 1110 DeclarationName()); 1111 return Instantiator.TransformTemplateArgument(Arg); 1112} 1113