SemaTemplateInstantiate.cpp revision 275313cbb0847f1f117f60d144d113804d4fa42d
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 "Lookup.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/DeclTemplate.h" 20#include "clang/Parse/DeclSpec.h" 21#include "clang/Basic/LangOptions.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. 31/// 32/// \param D the declaration for which we are computing template instantiation 33/// arguments. 34/// 35/// \param Innermost if non-NULL, the innermost template argument list. 36/// 37/// \param RelativeToPrimary true if we should get the template 38/// arguments relative to the primary template, even when we're 39/// dealing with a specialization. This is only relevant for function 40/// template specializations. 41MultiLevelTemplateArgumentList 42Sema::getTemplateInstantiationArgs(NamedDecl *D, 43 const TemplateArgumentList *Innermost, 44 bool RelativeToPrimary) { 45 // Accumulate the set of template argument lists in this structure. 46 MultiLevelTemplateArgumentList Result; 47 48 if (Innermost) 49 Result.addOuterTemplateArguments(Innermost); 50 51 DeclContext *Ctx = dyn_cast<DeclContext>(D); 52 if (!Ctx) 53 Ctx = D->getDeclContext(); 54 55 while (!Ctx->isFileContext()) { 56 // Add template arguments from a class template instantiation. 57 if (ClassTemplateSpecializationDecl *Spec 58 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) { 59 // We're done when we hit an explicit specialization. 60 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization) 61 break; 62 63 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); 64 65 // If this class template specialization was instantiated from a 66 // specialized member that is a class template, we're done. 67 assert(Spec->getSpecializedTemplate() && "No class template?"); 68 if (Spec->getSpecializedTemplate()->isMemberSpecialization()) 69 break; 70 } 71 // Add template arguments from a function template specialization. 72 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) { 73 if (!RelativeToPrimary && 74 Function->getTemplateSpecializationKind() 75 == TSK_ExplicitSpecialization) 76 break; 77 78 if (const TemplateArgumentList *TemplateArgs 79 = Function->getTemplateSpecializationArgs()) { 80 // Add the template arguments for this specialization. 81 Result.addOuterTemplateArguments(TemplateArgs); 82 83 // If this function was instantiated from a specialized member that is 84 // a function template, we're done. 85 assert(Function->getPrimaryTemplate() && "No function template?"); 86 if (Function->getPrimaryTemplate()->isMemberSpecialization()) 87 break; 88 } 89 90 // If this is a friend declaration and it declares an entity at 91 // namespace scope, take arguments from its lexical parent 92 // instead of its semantic parent. 93 if (Function->getFriendObjectKind() && 94 Function->getDeclContext()->isFileContext()) { 95 Ctx = Function->getLexicalDeclContext(); 96 RelativeToPrimary = false; 97 continue; 98 } 99 } 100 101 Ctx = Ctx->getParent(); 102 RelativeToPrimary = false; 103 } 104 105 return Result; 106} 107 108bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const { 109 switch (Kind) { 110 case TemplateInstantiation: 111 case DefaultTemplateArgumentInstantiation: 112 case DefaultFunctionArgumentInstantiation: 113 return true; 114 115 case ExplicitTemplateArgumentSubstitution: 116 case DeducedTemplateArgumentSubstitution: 117 case PriorTemplateArgumentSubstitution: 118 case DefaultTemplateArgumentChecking: 119 return false; 120 } 121 122 return true; 123} 124 125Sema::InstantiatingTemplate:: 126InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 127 Decl *Entity, 128 SourceRange InstantiationRange) 129 : SemaRef(SemaRef) { 130 131 Invalid = CheckInstantiationDepth(PointOfInstantiation, 132 InstantiationRange); 133 if (!Invalid) { 134 ActiveTemplateInstantiation Inst; 135 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation; 136 Inst.PointOfInstantiation = PointOfInstantiation; 137 Inst.Entity = reinterpret_cast<uintptr_t>(Entity); 138 Inst.TemplateArgs = 0; 139 Inst.NumTemplateArgs = 0; 140 Inst.InstantiationRange = InstantiationRange; 141 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 142 } 143} 144 145Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 146 SourceLocation PointOfInstantiation, 147 TemplateDecl *Template, 148 const TemplateArgument *TemplateArgs, 149 unsigned NumTemplateArgs, 150 SourceRange InstantiationRange) 151 : SemaRef(SemaRef) { 152 153 Invalid = CheckInstantiationDepth(PointOfInstantiation, 154 InstantiationRange); 155 if (!Invalid) { 156 ActiveTemplateInstantiation Inst; 157 Inst.Kind 158 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation; 159 Inst.PointOfInstantiation = PointOfInstantiation; 160 Inst.Entity = reinterpret_cast<uintptr_t>(Template); 161 Inst.TemplateArgs = TemplateArgs; 162 Inst.NumTemplateArgs = NumTemplateArgs; 163 Inst.InstantiationRange = InstantiationRange; 164 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 165 } 166} 167 168Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 169 SourceLocation PointOfInstantiation, 170 FunctionTemplateDecl *FunctionTemplate, 171 const TemplateArgument *TemplateArgs, 172 unsigned NumTemplateArgs, 173 ActiveTemplateInstantiation::InstantiationKind Kind, 174 SourceRange InstantiationRange) 175: SemaRef(SemaRef) { 176 177 Invalid = CheckInstantiationDepth(PointOfInstantiation, 178 InstantiationRange); 179 if (!Invalid) { 180 ActiveTemplateInstantiation Inst; 181 Inst.Kind = Kind; 182 Inst.PointOfInstantiation = PointOfInstantiation; 183 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate); 184 Inst.TemplateArgs = TemplateArgs; 185 Inst.NumTemplateArgs = NumTemplateArgs; 186 Inst.InstantiationRange = InstantiationRange; 187 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 188 189 if (!Inst.isInstantiationRecord()) 190 ++SemaRef.NonInstantiationEntries; 191 } 192} 193 194Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 195 SourceLocation PointOfInstantiation, 196 ClassTemplatePartialSpecializationDecl *PartialSpec, 197 const TemplateArgument *TemplateArgs, 198 unsigned NumTemplateArgs, 199 SourceRange InstantiationRange) 200 : SemaRef(SemaRef) { 201 202 Invalid = false; 203 204 ActiveTemplateInstantiation Inst; 205 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution; 206 Inst.PointOfInstantiation = PointOfInstantiation; 207 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec); 208 Inst.TemplateArgs = TemplateArgs; 209 Inst.NumTemplateArgs = NumTemplateArgs; 210 Inst.InstantiationRange = InstantiationRange; 211 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 212 213 assert(!Inst.isInstantiationRecord()); 214 ++SemaRef.NonInstantiationEntries; 215} 216 217Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 218 SourceLocation PointOfInstantiation, 219 ParmVarDecl *Param, 220 const TemplateArgument *TemplateArgs, 221 unsigned NumTemplateArgs, 222 SourceRange InstantiationRange) 223 : SemaRef(SemaRef) { 224 225 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange); 226 227 if (!Invalid) { 228 ActiveTemplateInstantiation Inst; 229 Inst.Kind 230 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 231 Inst.PointOfInstantiation = PointOfInstantiation; 232 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 233 Inst.TemplateArgs = TemplateArgs; 234 Inst.NumTemplateArgs = NumTemplateArgs; 235 Inst.InstantiationRange = InstantiationRange; 236 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 237 } 238} 239 240Sema::InstantiatingTemplate:: 241InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 242 TemplateDecl *Template, 243 NonTypeTemplateParmDecl *Param, 244 const TemplateArgument *TemplateArgs, 245 unsigned NumTemplateArgs, 246 SourceRange InstantiationRange) : SemaRef(SemaRef) { 247 Invalid = false; 248 249 ActiveTemplateInstantiation Inst; 250 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution; 251 Inst.PointOfInstantiation = PointOfInstantiation; 252 Inst.Template = Template; 253 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 254 Inst.TemplateArgs = TemplateArgs; 255 Inst.NumTemplateArgs = NumTemplateArgs; 256 Inst.InstantiationRange = InstantiationRange; 257 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 258 259 assert(!Inst.isInstantiationRecord()); 260 ++SemaRef.NonInstantiationEntries; 261} 262 263Sema::InstantiatingTemplate:: 264InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 265 TemplateDecl *Template, 266 TemplateTemplateParmDecl *Param, 267 const TemplateArgument *TemplateArgs, 268 unsigned NumTemplateArgs, 269 SourceRange InstantiationRange) : SemaRef(SemaRef) { 270 Invalid = false; 271 ActiveTemplateInstantiation Inst; 272 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution; 273 Inst.PointOfInstantiation = PointOfInstantiation; 274 Inst.Template = Template; 275 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 276 Inst.TemplateArgs = TemplateArgs; 277 Inst.NumTemplateArgs = NumTemplateArgs; 278 Inst.InstantiationRange = InstantiationRange; 279 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 280 281 assert(!Inst.isInstantiationRecord()); 282 ++SemaRef.NonInstantiationEntries; 283} 284 285Sema::InstantiatingTemplate:: 286InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 287 TemplateDecl *Template, 288 NamedDecl *Param, 289 const TemplateArgument *TemplateArgs, 290 unsigned NumTemplateArgs, 291 SourceRange InstantiationRange) : SemaRef(SemaRef) { 292 Invalid = false; 293 294 ActiveTemplateInstantiation Inst; 295 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking; 296 Inst.PointOfInstantiation = PointOfInstantiation; 297 Inst.Template = Template; 298 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 299 Inst.TemplateArgs = TemplateArgs; 300 Inst.NumTemplateArgs = NumTemplateArgs; 301 Inst.InstantiationRange = InstantiationRange; 302 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 303 304 assert(!Inst.isInstantiationRecord()); 305 ++SemaRef.NonInstantiationEntries; 306} 307 308void Sema::InstantiatingTemplate::Clear() { 309 if (!Invalid) { 310 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) { 311 assert(SemaRef.NonInstantiationEntries > 0); 312 --SemaRef.NonInstantiationEntries; 313 } 314 315 SemaRef.ActiveTemplateInstantiations.pop_back(); 316 Invalid = true; 317 } 318} 319 320bool Sema::InstantiatingTemplate::CheckInstantiationDepth( 321 SourceLocation PointOfInstantiation, 322 SourceRange InstantiationRange) { 323 assert(SemaRef.NonInstantiationEntries <= 324 SemaRef.ActiveTemplateInstantiations.size()); 325 if ((SemaRef.ActiveTemplateInstantiations.size() - 326 SemaRef.NonInstantiationEntries) 327 <= SemaRef.getLangOptions().InstantiationDepth) 328 return false; 329 330 SemaRef.Diag(PointOfInstantiation, 331 diag::err_template_recursion_depth_exceeded) 332 << SemaRef.getLangOptions().InstantiationDepth 333 << InstantiationRange; 334 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) 335 << SemaRef.getLangOptions().InstantiationDepth; 336 return true; 337} 338 339/// \brief Prints the current instantiation stack through a series of 340/// notes. 341void Sema::PrintInstantiationStack() { 342 // FIXME: In all of these cases, we need to show the template arguments 343 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator 344 Active = ActiveTemplateInstantiations.rbegin(), 345 ActiveEnd = ActiveTemplateInstantiations.rend(); 346 Active != ActiveEnd; 347 ++Active) { 348 switch (Active->Kind) { 349 case ActiveTemplateInstantiation::TemplateInstantiation: { 350 Decl *D = reinterpret_cast<Decl *>(Active->Entity); 351 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 352 unsigned DiagID = diag::note_template_member_class_here; 353 if (isa<ClassTemplateSpecializationDecl>(Record)) 354 DiagID = diag::note_template_class_instantiation_here; 355 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 356 DiagID) 357 << Context.getTypeDeclType(Record) 358 << Active->InstantiationRange; 359 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 360 unsigned DiagID; 361 if (Function->getPrimaryTemplate()) 362 DiagID = diag::note_function_template_spec_here; 363 else 364 DiagID = diag::note_template_member_function_here; 365 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 366 DiagID) 367 << Function 368 << Active->InstantiationRange; 369 } else { 370 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 371 diag::note_template_static_data_member_def_here) 372 << cast<VarDecl>(D) 373 << Active->InstantiationRange; 374 } 375 break; 376 } 377 378 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: { 379 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity); 380 std::string TemplateArgsStr 381 = TemplateSpecializationType::PrintTemplateArgumentList( 382 Active->TemplateArgs, 383 Active->NumTemplateArgs, 384 Context.PrintingPolicy); 385 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 386 diag::note_default_arg_instantiation_here) 387 << (Template->getNameAsString() + TemplateArgsStr) 388 << Active->InstantiationRange; 389 break; 390 } 391 392 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: { 393 FunctionTemplateDecl *FnTmpl 394 = cast<FunctionTemplateDecl>((Decl *)Active->Entity); 395 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 396 diag::note_explicit_template_arg_substitution_here) 397 << FnTmpl 398 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 399 Active->TemplateArgs, 400 Active->NumTemplateArgs) 401 << Active->InstantiationRange; 402 break; 403 } 404 405 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 406 if (ClassTemplatePartialSpecializationDecl *PartialSpec 407 = dyn_cast<ClassTemplatePartialSpecializationDecl>( 408 (Decl *)Active->Entity)) { 409 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 410 diag::note_partial_spec_deduct_instantiation_here) 411 << Context.getTypeDeclType(PartialSpec) 412 << getTemplateArgumentBindingsText( 413 PartialSpec->getTemplateParameters(), 414 Active->TemplateArgs, 415 Active->NumTemplateArgs) 416 << Active->InstantiationRange; 417 } else { 418 FunctionTemplateDecl *FnTmpl 419 = cast<FunctionTemplateDecl>((Decl *)Active->Entity); 420 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 421 diag::note_function_template_deduction_instantiation_here) 422 << FnTmpl 423 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 424 Active->TemplateArgs, 425 Active->NumTemplateArgs) 426 << Active->InstantiationRange; 427 } 428 break; 429 430 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: { 431 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity); 432 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); 433 434 std::string TemplateArgsStr 435 = TemplateSpecializationType::PrintTemplateArgumentList( 436 Active->TemplateArgs, 437 Active->NumTemplateArgs, 438 Context.PrintingPolicy); 439 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 440 diag::note_default_function_arg_instantiation_here) 441 << (FD->getNameAsString() + TemplateArgsStr) 442 << Active->InstantiationRange; 443 break; 444 } 445 446 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: { 447 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity); 448 std::string Name; 449 if (!Parm->getName().empty()) 450 Name = std::string(" '") + Parm->getName().str() + "'"; 451 452 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 453 diag::note_prior_template_arg_substitution) 454 << isa<TemplateTemplateParmDecl>(Parm) 455 << Name 456 << getTemplateArgumentBindingsText( 457 Active->Template->getTemplateParameters(), 458 Active->TemplateArgs, 459 Active->NumTemplateArgs) 460 << Active->InstantiationRange; 461 break; 462 } 463 464 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: { 465 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 466 diag::note_template_default_arg_checking) 467 << getTemplateArgumentBindingsText( 468 Active->Template->getTemplateParameters(), 469 Active->TemplateArgs, 470 Active->NumTemplateArgs) 471 << Active->InstantiationRange; 472 break; 473 } 474 } 475 } 476} 477 478bool Sema::isSFINAEContext() const { 479 using llvm::SmallVector; 480 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator 481 Active = ActiveTemplateInstantiations.rbegin(), 482 ActiveEnd = ActiveTemplateInstantiations.rend(); 483 Active != ActiveEnd; 484 ++Active) 485 { 486 switch(Active->Kind) { 487 case ActiveTemplateInstantiation::TemplateInstantiation: 488 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: 489 // This is a template instantiation, so there is no SFINAE. 490 return false; 491 492 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: 493 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: 494 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: 495 // A default template argument instantiation and substitution into 496 // template parameters with arguments for prior parameters may or may 497 // not be a SFINAE context; look further up the stack. 498 break; 499 500 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: 501 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 502 // We're either substitution explicitly-specified template arguments 503 // or deduced template arguments, so SFINAE applies. 504 return true; 505 } 506 } 507 508 return false; 509} 510 511//===----------------------------------------------------------------------===/ 512// Template Instantiation for Types 513//===----------------------------------------------------------------------===/ 514namespace { 515 class TemplateInstantiator 516 : public TreeTransform<TemplateInstantiator> { 517 const MultiLevelTemplateArgumentList &TemplateArgs; 518 SourceLocation Loc; 519 DeclarationName Entity; 520 521 public: 522 typedef TreeTransform<TemplateInstantiator> inherited; 523 524 TemplateInstantiator(Sema &SemaRef, 525 const MultiLevelTemplateArgumentList &TemplateArgs, 526 SourceLocation Loc, 527 DeclarationName Entity) 528 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), 529 Entity(Entity) { } 530 531 /// \brief Determine whether the given type \p T has already been 532 /// transformed. 533 /// 534 /// For the purposes of template instantiation, a type has already been 535 /// transformed if it is NULL or if it is not dependent. 536 bool AlreadyTransformed(QualType T) { 537 return T.isNull() || !T->isDependentType(); 538 } 539 540 /// \brief Returns the location of the entity being instantiated, if known. 541 SourceLocation getBaseLocation() { return Loc; } 542 543 /// \brief Returns the name of the entity being instantiated, if any. 544 DeclarationName getBaseEntity() { return Entity; } 545 546 /// \brief Sets the "base" location and entity when that 547 /// information is known based on another transformation. 548 void setBase(SourceLocation Loc, DeclarationName Entity) { 549 this->Loc = Loc; 550 this->Entity = Entity; 551 } 552 553 /// \brief Transform the given declaration by instantiating a reference to 554 /// this declaration. 555 Decl *TransformDecl(SourceLocation Loc, Decl *D); 556 557 /// \brief Transform the definition of the given declaration by 558 /// instantiating it. 559 Decl *TransformDefinition(SourceLocation Loc, Decl *D); 560 561 /// \bried Transform the first qualifier within a scope by instantiating the 562 /// declaration. 563 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); 564 565 /// \brief Rebuild the exception declaration and register the declaration 566 /// as an instantiated local. 567 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, QualType T, 568 TypeSourceInfo *Declarator, 569 IdentifierInfo *Name, 570 SourceLocation Loc, SourceRange TypeRange); 571 572 /// \brief Check for tag mismatches when instantiating an 573 /// elaborated type. 574 QualType RebuildElaboratedType(QualType T, ElaboratedType::TagKind Tag); 575 576 Sema::OwningExprResult TransformPredefinedExpr(PredefinedExpr *E); 577 Sema::OwningExprResult TransformDeclRefExpr(DeclRefExpr *E); 578 Sema::OwningExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E); 579 Sema::OwningExprResult TransformTemplateParmRefExpr(DeclRefExpr *E, 580 NonTypeTemplateParmDecl *D); 581 582 /// \brief Transforms a function proto type by performing 583 /// substitution in the function parameters, possibly adjusting 584 /// their types and marking default arguments as uninstantiated. 585 bool TransformFunctionTypeParams(FunctionProtoTypeLoc TL, 586 llvm::SmallVectorImpl<QualType> &PTypes, 587 llvm::SmallVectorImpl<ParmVarDecl*> &PVars); 588 589 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm); 590 591 /// \brief Transforms a template type parameter type by performing 592 /// substitution of the corresponding template type argument. 593 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, 594 TemplateTypeParmTypeLoc TL, 595 QualType ObjectType); 596 }; 597} 598 599Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { 600 if (!D) 601 return 0; 602 603 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) { 604 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 605 // If the corresponding template argument is NULL or non-existent, it's 606 // because we are performing instantiation from explicitly-specified 607 // template arguments in a function template, but there were some 608 // arguments left unspecified. 609 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), 610 TTP->getPosition())) 611 return D; 612 613 TemplateName Template 614 = TemplateArgs(TTP->getDepth(), TTP->getPosition()).getAsTemplate(); 615 assert(!Template.isNull() && Template.getAsTemplateDecl() && 616 "Wrong kind of template template argument"); 617 return Template.getAsTemplateDecl(); 618 } 619 620 // Fall through to find the instantiated declaration for this template 621 // template parameter. 622 } 623 624 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs); 625} 626 627Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { 628 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs); 629 if (!Inst) 630 return 0; 631 632 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); 633 return Inst; 634} 635 636NamedDecl * 637TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, 638 SourceLocation Loc) { 639 // If the first part of the nested-name-specifier was a template type 640 // parameter, instantiate that type parameter down to a tag type. 641 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) { 642 const TemplateTypeParmType *TTP 643 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD)); 644 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 645 QualType T = TemplateArgs(TTP->getDepth(), TTP->getIndex()).getAsType(); 646 if (T.isNull()) 647 return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); 648 649 if (const TagType *Tag = T->getAs<TagType>()) 650 return Tag->getDecl(); 651 652 // The resulting type is not a tag; complain. 653 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T; 654 return 0; 655 } 656 } 657 658 return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); 659} 660 661VarDecl * 662TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, 663 QualType T, 664 TypeSourceInfo *Declarator, 665 IdentifierInfo *Name, 666 SourceLocation Loc, 667 SourceRange TypeRange) { 668 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, T, Declarator, 669 Name, Loc, TypeRange); 670 if (Var && !Var->isInvalidDecl()) 671 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); 672 return Var; 673} 674 675QualType 676TemplateInstantiator::RebuildElaboratedType(QualType T, 677 ElaboratedType::TagKind Tag) { 678 if (const TagType *TT = T->getAs<TagType>()) { 679 TagDecl* TD = TT->getDecl(); 680 681 // FIXME: this location is very wrong; we really need typelocs. 682 SourceLocation TagLocation = TD->getTagKeywordLoc(); 683 684 // FIXME: type might be anonymous. 685 IdentifierInfo *Id = TD->getIdentifier(); 686 687 // TODO: should we even warn on struct/class mismatches for this? Seems 688 // like it's likely to produce a lot of spurious errors. 689 if (!SemaRef.isAcceptableTagRedeclaration(TD, Tag, TagLocation, *Id)) { 690 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag) 691 << Id 692 << CodeModificationHint::CreateReplacement(SourceRange(TagLocation), 693 TD->getKindName()); 694 SemaRef.Diag(TD->getLocation(), diag::note_previous_use); 695 } 696 } 697 698 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(T, Tag); 699} 700 701Sema::OwningExprResult 702TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { 703 if (!E->isTypeDependent()) 704 return SemaRef.Owned(E->Retain()); 705 706 FunctionDecl *currentDecl = getSema().getCurFunctionDecl(); 707 assert(currentDecl && "Must have current function declaration when " 708 "instantiating."); 709 710 PredefinedExpr::IdentType IT = E->getIdentType(); 711 712 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 713 714 llvm::APInt LengthI(32, Length + 1); 715 QualType ResTy = getSema().Context.CharTy.withConst(); 716 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI, 717 ArrayType::Normal, 0); 718 PredefinedExpr *PE = 719 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT); 720 return getSema().Owned(PE); 721} 722 723Sema::OwningExprResult 724TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, 725 NonTypeTemplateParmDecl *NTTP) { 726 // If the corresponding template argument is NULL or non-existent, it's 727 // because we are performing instantiation from explicitly-specified 728 // template arguments in a function template, but there were some 729 // arguments left unspecified. 730 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(), 731 NTTP->getPosition())) 732 return SemaRef.Owned(E->Retain()); 733 734 const TemplateArgument &Arg = TemplateArgs(NTTP->getDepth(), 735 NTTP->getPosition()); 736 737 // The template argument itself might be an expression, in which 738 // case we just return that expression. 739 if (Arg.getKind() == TemplateArgument::Expression) 740 return SemaRef.Owned(Arg.getAsExpr()->Retain()); 741 742 if (Arg.getKind() == TemplateArgument::Declaration) { 743 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl()); 744 745 // Find the instantiation of the template argument. This is 746 // required for nested templates. 747 VD = cast_or_null<ValueDecl>( 748 getSema().FindInstantiatedDecl(E->getLocation(), 749 VD, TemplateArgs)); 750 if (!VD) 751 return SemaRef.ExprError(); 752 753 // Derive the type we want the substituted decl to have. This had 754 // better be non-dependent, or these checks will have serious problems. 755 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs, 756 E->getLocation(), 757 DeclarationName()); 758 assert(!TargetType.isNull() && "type substitution failed for param type"); 759 assert(!TargetType->isDependentType() && "param type still dependent"); 760 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg, 761 TargetType, 762 E->getLocation()); 763 } 764 765 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg, 766 E->getSourceRange().getBegin()); 767} 768 769 770Sema::OwningExprResult 771TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { 772 NamedDecl *D = E->getDecl(); 773 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { 774 if (NTTP->getDepth() < TemplateArgs.getNumLevels()) 775 return TransformTemplateParmRefExpr(E, NTTP); 776 777 // We have a non-type template parameter that isn't fully substituted; 778 // FindInstantiatedDecl will find it in the local instantiation scope. 779 } 780 781 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E); 782} 783 784Sema::OwningExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( 785 CXXDefaultArgExpr *E) { 786 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())-> 787 getDescribedFunctionTemplate() && 788 "Default arg expressions are never formed in dependent cases."); 789 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(), 790 cast<FunctionDecl>(E->getParam()->getDeclContext()), 791 E->getParam()); 792} 793 794 795bool 796TemplateInstantiator::TransformFunctionTypeParams(FunctionProtoTypeLoc TL, 797 llvm::SmallVectorImpl<QualType> &PTypes, 798 llvm::SmallVectorImpl<ParmVarDecl*> &PVars) { 799 // Create a local instantiation scope for the parameters. 800 // FIXME: When we implement the C++0x late-specified return type, 801 // we will need to move this scope out to the function type itself. 802 bool IsTemporaryScope = (SemaRef.CurrentInstantiationScope != 0); 803 Sema::LocalInstantiationScope Scope(SemaRef, IsTemporaryScope, 804 IsTemporaryScope); 805 806 if (TreeTransform<TemplateInstantiator>:: 807 TransformFunctionTypeParams(TL, PTypes, PVars)) 808 return true; 809 810 // Check instantiated parameters. 811 if (SemaRef.CheckInstantiatedParams(PVars)) 812 return true; 813 814 return false; 815} 816 817ParmVarDecl * 818TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm) { 819 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo(); 820 TypeSourceInfo *NewDI = getDerived().TransformType(OldDI); 821 if (!NewDI) 822 return 0; 823 824 // TODO: do we have to clone this decl if the types match and 825 // there's no default argument? 826 827 ParmVarDecl *NewParm 828 = ParmVarDecl::Create(SemaRef.Context, 829 OldParm->getDeclContext(), 830 OldParm->getLocation(), 831 OldParm->getIdentifier(), 832 NewDI->getType(), 833 NewDI, 834 OldParm->getStorageClass(), 835 /* DefArg */ NULL); 836 837 // Maybe adjust new parameter type. 838 NewParm->setType(SemaRef.adjustParameterType(NewParm->getType())); 839 840 // Mark the (new) default argument as uninstantiated (if any). 841 if (OldParm->hasUninstantiatedDefaultArg()) { 842 Expr *Arg = OldParm->getUninstantiatedDefaultArg(); 843 NewParm->setUninstantiatedDefaultArg(Arg); 844 } else if (Expr *Arg = OldParm->getDefaultArg()) 845 NewParm->setUninstantiatedDefaultArg(Arg); 846 847 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); 848 849 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); 850 return NewParm; 851} 852 853QualType 854TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, 855 TemplateTypeParmTypeLoc TL, 856 QualType ObjectType) { 857 TemplateTypeParmType *T = TL.getTypePtr(); 858 if (T->getDepth() < TemplateArgs.getNumLevels()) { 859 // Replace the template type parameter with its corresponding 860 // template argument. 861 862 // If the corresponding template argument is NULL or doesn't exist, it's 863 // because we are performing instantiation from explicitly-specified 864 // template arguments in a function template class, but there were some 865 // arguments left unspecified. 866 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) { 867 TemplateTypeParmTypeLoc NewTL 868 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType()); 869 NewTL.setNameLoc(TL.getNameLoc()); 870 return TL.getType(); 871 } 872 873 assert(TemplateArgs(T->getDepth(), T->getIndex()).getKind() 874 == TemplateArgument::Type && 875 "Template argument kind mismatch"); 876 877 QualType Replacement 878 = TemplateArgs(T->getDepth(), T->getIndex()).getAsType(); 879 880 // TODO: only do this uniquing once, at the start of instantiation. 881 QualType Result 882 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement); 883 SubstTemplateTypeParmTypeLoc NewTL 884 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result); 885 NewTL.setNameLoc(TL.getNameLoc()); 886 return Result; 887 } 888 889 // The template type parameter comes from an inner template (e.g., 890 // the template parameter list of a member template inside the 891 // template we are instantiating). Create a new template type 892 // parameter with the template "level" reduced by one. 893 QualType Result 894 = getSema().Context.getTemplateTypeParmType(T->getDepth() 895 - TemplateArgs.getNumLevels(), 896 T->getIndex(), 897 T->isParameterPack(), 898 T->getName()); 899 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result); 900 NewTL.setNameLoc(TL.getNameLoc()); 901 return Result; 902} 903 904/// \brief Perform substitution on the type T with a given set of template 905/// arguments. 906/// 907/// This routine substitutes the given template arguments into the 908/// type T and produces the instantiated type. 909/// 910/// \param T the type into which the template arguments will be 911/// substituted. If this type is not dependent, it will be returned 912/// immediately. 913/// 914/// \param TemplateArgs the template arguments that will be 915/// substituted for the top-level template parameters within T. 916/// 917/// \param Loc the location in the source code where this substitution 918/// is being performed. It will typically be the location of the 919/// declarator (if we're instantiating the type of some declaration) 920/// or the location of the type in the source code (if, e.g., we're 921/// instantiating the type of a cast expression). 922/// 923/// \param Entity the name of the entity associated with a declaration 924/// being instantiated (if any). May be empty to indicate that there 925/// is no such entity (if, e.g., this is a type that occurs as part of 926/// a cast expression) or that the entity has no name (e.g., an 927/// unnamed function parameter). 928/// 929/// \returns If the instantiation succeeds, the instantiated 930/// type. Otherwise, produces diagnostics and returns a NULL type. 931TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, 932 const MultiLevelTemplateArgumentList &Args, 933 SourceLocation Loc, 934 DeclarationName Entity) { 935 assert(!ActiveTemplateInstantiations.empty() && 936 "Cannot perform an instantiation without some context on the " 937 "instantiation stack"); 938 939 if (!T->getType()->isDependentType()) 940 return T; 941 942 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 943 return Instantiator.TransformType(T); 944} 945 946/// Deprecated form of the above. 947QualType Sema::SubstType(QualType T, 948 const MultiLevelTemplateArgumentList &TemplateArgs, 949 SourceLocation Loc, DeclarationName Entity) { 950 assert(!ActiveTemplateInstantiations.empty() && 951 "Cannot perform an instantiation without some context on the " 952 "instantiation stack"); 953 954 // If T is not a dependent type, there is nothing to do. 955 if (!T->isDependentType()) 956 return T; 957 958 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); 959 return Instantiator.TransformType(T); 960} 961 962/// \brief Perform substitution on the base class specifiers of the 963/// given class template specialization. 964/// 965/// Produces a diagnostic and returns true on error, returns false and 966/// attaches the instantiated base classes to the class template 967/// specialization if successful. 968bool 969Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 970 CXXRecordDecl *Pattern, 971 const MultiLevelTemplateArgumentList &TemplateArgs) { 972 bool Invalid = false; 973 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; 974 for (ClassTemplateSpecializationDecl::base_class_iterator 975 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end(); 976 Base != BaseEnd; ++Base) { 977 if (!Base->getType()->isDependentType()) { 978 const CXXRecordDecl *BaseDecl = 979 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 980 981 // Make sure to set the attributes from the base. 982 SetClassDeclAttributesFromBase(Instantiation, BaseDecl, 983 Base->isVirtual()); 984 985 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base)); 986 continue; 987 } 988 989 QualType BaseType = SubstType(Base->getType(), 990 TemplateArgs, 991 Base->getSourceRange().getBegin(), 992 DeclarationName()); 993 if (BaseType.isNull()) { 994 Invalid = true; 995 continue; 996 } 997 998 if (CXXBaseSpecifier *InstantiatedBase 999 = CheckBaseSpecifier(Instantiation, 1000 Base->getSourceRange(), 1001 Base->isVirtual(), 1002 Base->getAccessSpecifierAsWritten(), 1003 BaseType, 1004 /*FIXME: Not totally accurate */ 1005 Base->getSourceRange().getBegin())) 1006 InstantiatedBases.push_back(InstantiatedBase); 1007 else 1008 Invalid = true; 1009 } 1010 1011 if (!Invalid && 1012 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(), 1013 InstantiatedBases.size())) 1014 Invalid = true; 1015 1016 return Invalid; 1017} 1018 1019/// \brief Instantiate the definition of a class from a given pattern. 1020/// 1021/// \param PointOfInstantiation The point of instantiation within the 1022/// source code. 1023/// 1024/// \param Instantiation is the declaration whose definition is being 1025/// instantiated. This will be either a class template specialization 1026/// or a member class of a class template specialization. 1027/// 1028/// \param Pattern is the pattern from which the instantiation 1029/// occurs. This will be either the declaration of a class template or 1030/// the declaration of a member class of a class template. 1031/// 1032/// \param TemplateArgs The template arguments to be substituted into 1033/// the pattern. 1034/// 1035/// \param TSK the kind of implicit or explicit instantiation to perform. 1036/// 1037/// \param Complain whether to complain if the class cannot be instantiated due 1038/// to the lack of a definition. 1039/// 1040/// \returns true if an error occurred, false otherwise. 1041bool 1042Sema::InstantiateClass(SourceLocation PointOfInstantiation, 1043 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 1044 const MultiLevelTemplateArgumentList &TemplateArgs, 1045 TemplateSpecializationKind TSK, 1046 bool Complain) { 1047 bool Invalid = false; 1048 1049 CXXRecordDecl *PatternDef 1050 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 1051 if (!PatternDef) { 1052 if (!Complain) { 1053 // Say nothing 1054 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) { 1055 Diag(PointOfInstantiation, 1056 diag::err_implicit_instantiate_member_undefined) 1057 << Context.getTypeDeclType(Instantiation); 1058 Diag(Pattern->getLocation(), diag::note_member_of_template_here); 1059 } else { 1060 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 1061 << (TSK != TSK_ImplicitInstantiation) 1062 << Context.getTypeDeclType(Instantiation); 1063 Diag(Pattern->getLocation(), diag::note_template_decl_here); 1064 } 1065 return true; 1066 } 1067 Pattern = PatternDef; 1068 1069 // \brief Record the point of instantiation. 1070 if (MemberSpecializationInfo *MSInfo 1071 = Instantiation->getMemberSpecializationInfo()) { 1072 MSInfo->setTemplateSpecializationKind(TSK); 1073 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1074 } else if (ClassTemplateSpecializationDecl *Spec 1075 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) { 1076 Spec->setTemplateSpecializationKind(TSK); 1077 Spec->setPointOfInstantiation(PointOfInstantiation); 1078 } 1079 1080 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 1081 if (Inst) 1082 return true; 1083 1084 // Enter the scope of this instantiation. We don't use 1085 // PushDeclContext because we don't have a scope. 1086 DeclContext *PreviousContext = CurContext; 1087 CurContext = Instantiation; 1088 1089 // If this is an instantiation of a local class, merge this local 1090 // instantiation scope with the enclosing scope. Otherwise, every 1091 // instantiation of a class has its own local instantiation scope. 1092 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); 1093 Sema::LocalInstantiationScope Scope(*this, MergeWithParentScope); 1094 1095 // Start the definition of this instantiation. 1096 Instantiation->startDefinition(); 1097 1098 // Do substitution on the base class specifiers. 1099 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) 1100 Invalid = true; 1101 1102 llvm::SmallVector<DeclPtrTy, 4> Fields; 1103 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(), 1104 MemberEnd = Pattern->decls_end(); 1105 Member != MemberEnd; ++Member) { 1106 Decl *NewMember = SubstDecl(*Member, Instantiation, TemplateArgs); 1107 if (NewMember) { 1108 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) 1109 Fields.push_back(DeclPtrTy::make(Field)); 1110 else if (NewMember->isInvalidDecl()) 1111 Invalid = true; 1112 } else { 1113 // FIXME: Eventually, a NULL return will mean that one of the 1114 // instantiations was a semantic disaster, and we'll want to set Invalid = 1115 // true. For now, we expect to skip some members that we can't yet handle. 1116 } 1117 } 1118 1119 // Finish checking fields. 1120 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation), 1121 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(), 1122 0); 1123 CheckCompletedCXXClass(Instantiation); 1124 if (Instantiation->isInvalidDecl()) 1125 Invalid = true; 1126 1127 // Exit the scope of this instantiation. 1128 CurContext = PreviousContext; 1129 1130 // If this is a polymorphic C++ class without a key function, we'll 1131 // have to mark all of the virtual members to allow emission of a vtable 1132 // in this translation unit. 1133 if (Instantiation->isDynamicClass() && 1134 !Context.getKeyFunction(Instantiation)) { 1135 // Local classes need to have their methods instantiated immediately in 1136 // order to have the correct instantiation scope. 1137 if (Instantiation->isLocalClass()) { 1138 MarkVirtualMembersReferenced(PointOfInstantiation, 1139 Instantiation); 1140 } else { 1141 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Instantiation, 1142 PointOfInstantiation)); 1143 } 1144 } 1145 1146 if (!Invalid) 1147 Consumer.HandleTagDeclDefinition(Instantiation); 1148 1149 return Invalid; 1150} 1151 1152bool 1153Sema::InstantiateClassTemplateSpecialization( 1154 SourceLocation PointOfInstantiation, 1155 ClassTemplateSpecializationDecl *ClassTemplateSpec, 1156 TemplateSpecializationKind TSK, 1157 bool Complain) { 1158 // Perform the actual instantiation on the canonical declaration. 1159 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 1160 ClassTemplateSpec->getCanonicalDecl()); 1161 1162 // Check whether we have already instantiated or specialized this class 1163 // template specialization. 1164 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) { 1165 if (ClassTemplateSpec->getSpecializationKind() == 1166 TSK_ExplicitInstantiationDeclaration && 1167 TSK == TSK_ExplicitInstantiationDefinition) { 1168 // An explicit instantiation definition follows an explicit instantiation 1169 // declaration (C++0x [temp.explicit]p10); go ahead and perform the 1170 // explicit instantiation. 1171 ClassTemplateSpec->setSpecializationKind(TSK); 1172 return false; 1173 } 1174 1175 // We can only instantiate something that hasn't already been 1176 // instantiated or specialized. Fail without any diagnostics: our 1177 // caller will provide an error message. 1178 return true; 1179 } 1180 1181 if (ClassTemplateSpec->isInvalidDecl()) 1182 return true; 1183 1184 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 1185 CXXRecordDecl *Pattern = 0; 1186 1187 // C++ [temp.class.spec.match]p1: 1188 // When a class template is used in a context that requires an 1189 // instantiation of the class, it is necessary to determine 1190 // whether the instantiation is to be generated using the primary 1191 // template or one of the partial specializations. This is done by 1192 // matching the template arguments of the class template 1193 // specialization with the template argument lists of the partial 1194 // specializations. 1195 typedef std::pair<ClassTemplatePartialSpecializationDecl *, 1196 TemplateArgumentList *> MatchResult; 1197 llvm::SmallVector<MatchResult, 4> Matched; 1198 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 1199 Partial = Template->getPartialSpecializations().begin(), 1200 PartialEnd = Template->getPartialSpecializations().end(); 1201 Partial != PartialEnd; 1202 ++Partial) { 1203 TemplateDeductionInfo Info(Context, PointOfInstantiation); 1204 if (TemplateDeductionResult Result 1205 = DeduceTemplateArguments(&*Partial, 1206 ClassTemplateSpec->getTemplateArgs(), 1207 Info)) { 1208 // FIXME: Store the failed-deduction information for use in 1209 // diagnostics, later. 1210 (void)Result; 1211 } else { 1212 Matched.push_back(std::make_pair(&*Partial, Info.take())); 1213 } 1214 } 1215 1216 if (Matched.size() >= 1) { 1217 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); 1218 if (Matched.size() == 1) { 1219 // -- If exactly one matching specialization is found, the 1220 // instantiation is generated from that specialization. 1221 // We don't need to do anything for this. 1222 } else { 1223 // -- If more than one matching specialization is found, the 1224 // partial order rules (14.5.4.2) are used to determine 1225 // whether one of the specializations is more specialized 1226 // than the others. If none of the specializations is more 1227 // specialized than all of the other matching 1228 // specializations, then the use of the class template is 1229 // ambiguous and the program is ill-formed. 1230 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1, 1231 PEnd = Matched.end(); 1232 P != PEnd; ++P) { 1233 if (getMoreSpecializedPartialSpecialization(P->first, Best->first, 1234 PointOfInstantiation) 1235 == P->first) 1236 Best = P; 1237 } 1238 1239 // Determine if the best partial specialization is more specialized than 1240 // the others. 1241 bool Ambiguous = false; 1242 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 1243 PEnd = Matched.end(); 1244 P != PEnd; ++P) { 1245 if (P != Best && 1246 getMoreSpecializedPartialSpecialization(P->first, Best->first, 1247 PointOfInstantiation) 1248 != Best->first) { 1249 Ambiguous = true; 1250 break; 1251 } 1252 } 1253 1254 if (Ambiguous) { 1255 // Partial ordering did not produce a clear winner. Complain. 1256 ClassTemplateSpec->setInvalidDecl(); 1257 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) 1258 << ClassTemplateSpec; 1259 1260 // Print the matching partial specializations. 1261 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 1262 PEnd = Matched.end(); 1263 P != PEnd; ++P) 1264 Diag(P->first->getLocation(), diag::note_partial_spec_match) 1265 << getTemplateArgumentBindingsText(P->first->getTemplateParameters(), 1266 *P->second); 1267 1268 return true; 1269 } 1270 } 1271 1272 // Instantiate using the best class template partial specialization. 1273 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->first; 1274 while (OrigPartialSpec->getInstantiatedFromMember()) { 1275 // If we've found an explicit specialization of this class template, 1276 // stop here and use that as the pattern. 1277 if (OrigPartialSpec->isMemberSpecialization()) 1278 break; 1279 1280 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember(); 1281 } 1282 1283 Pattern = OrigPartialSpec; 1284 ClassTemplateSpec->setInstantiationOf(Best->first, Best->second); 1285 } else { 1286 // -- If no matches are found, the instantiation is generated 1287 // from the primary template. 1288 ClassTemplateDecl *OrigTemplate = Template; 1289 while (OrigTemplate->getInstantiatedFromMemberTemplate()) { 1290 // If we've found an explicit specialization of this class template, 1291 // stop here and use that as the pattern. 1292 if (OrigTemplate->isMemberSpecialization()) 1293 break; 1294 1295 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate(); 1296 } 1297 1298 Pattern = OrigTemplate->getTemplatedDecl(); 1299 } 1300 1301 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec, 1302 Pattern, 1303 getTemplateInstantiationArgs(ClassTemplateSpec), 1304 TSK, 1305 Complain); 1306 1307 for (unsigned I = 0, N = Matched.size(); I != N; ++I) { 1308 // FIXME: Implement TemplateArgumentList::Destroy! 1309 // if (Matched[I].first != Pattern) 1310 // Matched[I].second->Destroy(Context); 1311 } 1312 1313 return Result; 1314} 1315 1316/// \brief Instantiates the definitions of all of the member 1317/// of the given class, which is an instantiation of a class template 1318/// or a member class of a template. 1319void 1320Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 1321 CXXRecordDecl *Instantiation, 1322 const MultiLevelTemplateArgumentList &TemplateArgs, 1323 TemplateSpecializationKind TSK) { 1324 for (DeclContext::decl_iterator D = Instantiation->decls_begin(), 1325 DEnd = Instantiation->decls_end(); 1326 D != DEnd; ++D) { 1327 bool SuppressNew = false; 1328 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) { 1329 if (FunctionDecl *Pattern 1330 = Function->getInstantiatedFromMemberFunction()) { 1331 MemberSpecializationInfo *MSInfo 1332 = Function->getMemberSpecializationInfo(); 1333 assert(MSInfo && "No member specialization information?"); 1334 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 1335 Function, 1336 MSInfo->getTemplateSpecializationKind(), 1337 MSInfo->getPointOfInstantiation(), 1338 SuppressNew) || 1339 SuppressNew) 1340 continue; 1341 1342 if (Function->getBody()) 1343 continue; 1344 1345 if (TSK == TSK_ExplicitInstantiationDefinition) { 1346 // C++0x [temp.explicit]p8: 1347 // An explicit instantiation definition that names a class template 1348 // specialization explicitly instantiates the class template 1349 // specialization and is only an explicit instantiation definition 1350 // of members whose definition is visible at the point of 1351 // instantiation. 1352 if (!Pattern->getBody()) 1353 continue; 1354 1355 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 1356 1357 InstantiateFunctionDefinition(PointOfInstantiation, Function); 1358 } else { 1359 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 1360 } 1361 } 1362 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) { 1363 if (Var->isStaticDataMember()) { 1364 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 1365 assert(MSInfo && "No member specialization information?"); 1366 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 1367 Var, 1368 MSInfo->getTemplateSpecializationKind(), 1369 MSInfo->getPointOfInstantiation(), 1370 SuppressNew) || 1371 SuppressNew) 1372 continue; 1373 1374 if (TSK == TSK_ExplicitInstantiationDefinition) { 1375 // C++0x [temp.explicit]p8: 1376 // An explicit instantiation definition that names a class template 1377 // specialization explicitly instantiates the class template 1378 // specialization and is only an explicit instantiation definition 1379 // of members whose definition is visible at the point of 1380 // instantiation. 1381 if (!Var->getInstantiatedFromStaticDataMember() 1382 ->getOutOfLineDefinition()) 1383 continue; 1384 1385 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 1386 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var); 1387 } else { 1388 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 1389 } 1390 } 1391 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) { 1392 if (Record->isInjectedClassName()) 1393 continue; 1394 1395 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); 1396 assert(MSInfo && "No member specialization information?"); 1397 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 1398 Record, 1399 MSInfo->getTemplateSpecializationKind(), 1400 MSInfo->getPointOfInstantiation(), 1401 SuppressNew) || 1402 SuppressNew) 1403 continue; 1404 1405 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 1406 assert(Pattern && "Missing instantiated-from-template information"); 1407 1408 if (!Record->getDefinition()) { 1409 if (!Pattern->getDefinition()) { 1410 // C++0x [temp.explicit]p8: 1411 // An explicit instantiation definition that names a class template 1412 // specialization explicitly instantiates the class template 1413 // specialization and is only an explicit instantiation definition 1414 // of members whose definition is visible at the point of 1415 // instantiation. 1416 if (TSK == TSK_ExplicitInstantiationDeclaration) { 1417 MSInfo->setTemplateSpecializationKind(TSK); 1418 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1419 } 1420 1421 continue; 1422 } 1423 1424 InstantiateClass(PointOfInstantiation, Record, Pattern, 1425 TemplateArgs, 1426 TSK); 1427 } 1428 1429 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 1430 if (Pattern) 1431 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, 1432 TSK); 1433 } 1434 } 1435} 1436 1437/// \brief Instantiate the definitions of all of the members of the 1438/// given class template specialization, which was named as part of an 1439/// explicit instantiation. 1440void 1441Sema::InstantiateClassTemplateSpecializationMembers( 1442 SourceLocation PointOfInstantiation, 1443 ClassTemplateSpecializationDecl *ClassTemplateSpec, 1444 TemplateSpecializationKind TSK) { 1445 // C++0x [temp.explicit]p7: 1446 // An explicit instantiation that names a class template 1447 // specialization is an explicit instantion of the same kind 1448 // (declaration or definition) of each of its members (not 1449 // including members inherited from base classes) that has not 1450 // been previously explicitly specialized in the translation unit 1451 // containing the explicit instantiation, except as described 1452 // below. 1453 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 1454 getTemplateInstantiationArgs(ClassTemplateSpec), 1455 TSK); 1456} 1457 1458Sema::OwningStmtResult 1459Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { 1460 if (!S) 1461 return Owned(S); 1462 1463 TemplateInstantiator Instantiator(*this, TemplateArgs, 1464 SourceLocation(), 1465 DeclarationName()); 1466 return Instantiator.TransformStmt(S); 1467} 1468 1469Sema::OwningExprResult 1470Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 1471 if (!E) 1472 return Owned(E); 1473 1474 TemplateInstantiator Instantiator(*this, TemplateArgs, 1475 SourceLocation(), 1476 DeclarationName()); 1477 return Instantiator.TransformExpr(E); 1478} 1479 1480/// \brief Do template substitution on a nested-name-specifier. 1481NestedNameSpecifier * 1482Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS, 1483 SourceRange Range, 1484 const MultiLevelTemplateArgumentList &TemplateArgs) { 1485 TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(), 1486 DeclarationName()); 1487 return Instantiator.TransformNestedNameSpecifier(NNS, Range); 1488} 1489 1490TemplateName 1491Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc, 1492 const MultiLevelTemplateArgumentList &TemplateArgs) { 1493 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 1494 DeclarationName()); 1495 return Instantiator.TransformTemplateName(Name); 1496} 1497 1498bool Sema::Subst(const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output, 1499 const MultiLevelTemplateArgumentList &TemplateArgs) { 1500 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 1501 DeclarationName()); 1502 1503 return Instantiator.TransformTemplateArgument(Input, Output); 1504} 1505