SemaTemplateInstantiate.cpp revision c42b6520b607cda57e850a60143e9f98bf421dbb
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 << FixItHint::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 962static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) { 963 if (T->getType()->isDependentType()) 964 return true; 965 966 TypeLoc TL = T->getTypeLoc(); 967 if (!isa<FunctionProtoTypeLoc>(TL)) 968 return false; 969 970 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL); 971 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) { 972 ParmVarDecl *P = FP.getArg(I); 973 974 // TODO: currently we always rebuild expressions. When we 975 // properly get lazier about this, we should use the same 976 // logic to avoid rebuilding prototypes here. 977 if (P->hasInit()) 978 return true; 979 } 980 981 return false; 982} 983 984/// A form of SubstType intended specifically for instantiating the 985/// type of a FunctionDecl. Its purpose is solely to force the 986/// instantiation of default-argument expressions. 987TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T, 988 const MultiLevelTemplateArgumentList &Args, 989 SourceLocation Loc, 990 DeclarationName Entity) { 991 assert(!ActiveTemplateInstantiations.empty() && 992 "Cannot perform an instantiation without some context on the " 993 "instantiation stack"); 994 995 if (!NeedsInstantiationAsFunctionType(T)) 996 return T; 997 998 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 999 1000 TypeLocBuilder TLB; 1001 1002 TypeLoc TL = T->getTypeLoc(); 1003 TLB.reserve(TL.getFullDataSize()); 1004 1005 QualType Result = Instantiator.TransformType(TLB, TL, QualType()); 1006 if (Result.isNull()) 1007 return 0; 1008 1009 return TLB.getTypeSourceInfo(Context, Result); 1010} 1011 1012/// \brief Perform substitution on the base class specifiers of the 1013/// given class template specialization. 1014/// 1015/// Produces a diagnostic and returns true on error, returns false and 1016/// attaches the instantiated base classes to the class template 1017/// specialization if successful. 1018bool 1019Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 1020 CXXRecordDecl *Pattern, 1021 const MultiLevelTemplateArgumentList &TemplateArgs) { 1022 bool Invalid = false; 1023 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; 1024 for (ClassTemplateSpecializationDecl::base_class_iterator 1025 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end(); 1026 Base != BaseEnd; ++Base) { 1027 if (!Base->getType()->isDependentType()) { 1028 const CXXRecordDecl *BaseDecl = 1029 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1030 1031 // Make sure to set the attributes from the base. 1032 SetClassDeclAttributesFromBase(Instantiation, BaseDecl, 1033 Base->isVirtual()); 1034 1035 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base)); 1036 continue; 1037 } 1038 1039 QualType BaseType = SubstType(Base->getType(), 1040 TemplateArgs, 1041 Base->getSourceRange().getBegin(), 1042 DeclarationName()); 1043 if (BaseType.isNull()) { 1044 Invalid = true; 1045 continue; 1046 } 1047 1048 if (CXXBaseSpecifier *InstantiatedBase 1049 = CheckBaseSpecifier(Instantiation, 1050 Base->getSourceRange(), 1051 Base->isVirtual(), 1052 Base->getAccessSpecifierAsWritten(), 1053 BaseType, 1054 /*FIXME: Not totally accurate */ 1055 Base->getSourceRange().getBegin())) 1056 InstantiatedBases.push_back(InstantiatedBase); 1057 else 1058 Invalid = true; 1059 } 1060 1061 if (!Invalid && 1062 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(), 1063 InstantiatedBases.size())) 1064 Invalid = true; 1065 1066 return Invalid; 1067} 1068 1069/// \brief Instantiate the definition of a class from a given pattern. 1070/// 1071/// \param PointOfInstantiation The point of instantiation within the 1072/// source code. 1073/// 1074/// \param Instantiation is the declaration whose definition is being 1075/// instantiated. This will be either a class template specialization 1076/// or a member class of a class template specialization. 1077/// 1078/// \param Pattern is the pattern from which the instantiation 1079/// occurs. This will be either the declaration of a class template or 1080/// the declaration of a member class of a class template. 1081/// 1082/// \param TemplateArgs The template arguments to be substituted into 1083/// the pattern. 1084/// 1085/// \param TSK the kind of implicit or explicit instantiation to perform. 1086/// 1087/// \param Complain whether to complain if the class cannot be instantiated due 1088/// to the lack of a definition. 1089/// 1090/// \returns true if an error occurred, false otherwise. 1091bool 1092Sema::InstantiateClass(SourceLocation PointOfInstantiation, 1093 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 1094 const MultiLevelTemplateArgumentList &TemplateArgs, 1095 TemplateSpecializationKind TSK, 1096 bool Complain) { 1097 bool Invalid = false; 1098 1099 CXXRecordDecl *PatternDef 1100 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 1101 if (!PatternDef) { 1102 if (!Complain) { 1103 // Say nothing 1104 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) { 1105 Diag(PointOfInstantiation, 1106 diag::err_implicit_instantiate_member_undefined) 1107 << Context.getTypeDeclType(Instantiation); 1108 Diag(Pattern->getLocation(), diag::note_member_of_template_here); 1109 } else { 1110 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 1111 << (TSK != TSK_ImplicitInstantiation) 1112 << Context.getTypeDeclType(Instantiation); 1113 Diag(Pattern->getLocation(), diag::note_template_decl_here); 1114 } 1115 return true; 1116 } 1117 Pattern = PatternDef; 1118 1119 // \brief Record the point of instantiation. 1120 if (MemberSpecializationInfo *MSInfo 1121 = Instantiation->getMemberSpecializationInfo()) { 1122 MSInfo->setTemplateSpecializationKind(TSK); 1123 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1124 } else if (ClassTemplateSpecializationDecl *Spec 1125 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) { 1126 Spec->setTemplateSpecializationKind(TSK); 1127 Spec->setPointOfInstantiation(PointOfInstantiation); 1128 } 1129 1130 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 1131 if (Inst) 1132 return true; 1133 1134 // Enter the scope of this instantiation. We don't use 1135 // PushDeclContext because we don't have a scope. 1136 DeclContext *PreviousContext = CurContext; 1137 CurContext = Instantiation; 1138 1139 // If this is an instantiation of a local class, merge this local 1140 // instantiation scope with the enclosing scope. Otherwise, every 1141 // instantiation of a class has its own local instantiation scope. 1142 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); 1143 Sema::LocalInstantiationScope Scope(*this, MergeWithParentScope); 1144 1145 // Start the definition of this instantiation. 1146 Instantiation->startDefinition(); 1147 1148 // Do substitution on the base class specifiers. 1149 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) 1150 Invalid = true; 1151 1152 llvm::SmallVector<DeclPtrTy, 4> Fields; 1153 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(), 1154 MemberEnd = Pattern->decls_end(); 1155 Member != MemberEnd; ++Member) { 1156 Decl *NewMember = SubstDecl(*Member, Instantiation, TemplateArgs); 1157 if (NewMember) { 1158 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) 1159 Fields.push_back(DeclPtrTy::make(Field)); 1160 else if (NewMember->isInvalidDecl()) 1161 Invalid = true; 1162 } else { 1163 // FIXME: Eventually, a NULL return will mean that one of the 1164 // instantiations was a semantic disaster, and we'll want to set Invalid = 1165 // true. For now, we expect to skip some members that we can't yet handle. 1166 } 1167 } 1168 1169 // Finish checking fields. 1170 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation), 1171 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(), 1172 0); 1173 CheckCompletedCXXClass(Instantiation); 1174 if (Instantiation->isInvalidDecl()) 1175 Invalid = true; 1176 1177 // Exit the scope of this instantiation. 1178 CurContext = PreviousContext; 1179 1180 // If this is a polymorphic C++ class without a key function, we'll 1181 // have to mark all of the virtual members to allow emission of a vtable 1182 // in this translation unit. 1183 if (Instantiation->isDynamicClass() && 1184 !Context.getKeyFunction(Instantiation)) { 1185 // Local classes need to have their methods instantiated immediately in 1186 // order to have the correct instantiation scope. 1187 if (Instantiation->isLocalClass()) { 1188 MarkVirtualMembersReferenced(PointOfInstantiation, 1189 Instantiation); 1190 } else { 1191 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Instantiation, 1192 PointOfInstantiation)); 1193 } 1194 } 1195 1196 if (!Invalid) 1197 Consumer.HandleTagDeclDefinition(Instantiation); 1198 1199 return Invalid; 1200} 1201 1202bool 1203Sema::InstantiateClassTemplateSpecialization( 1204 SourceLocation PointOfInstantiation, 1205 ClassTemplateSpecializationDecl *ClassTemplateSpec, 1206 TemplateSpecializationKind TSK, 1207 bool Complain) { 1208 // Perform the actual instantiation on the canonical declaration. 1209 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 1210 ClassTemplateSpec->getCanonicalDecl()); 1211 1212 // Check whether we have already instantiated or specialized this class 1213 // template specialization. 1214 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) { 1215 if (ClassTemplateSpec->getSpecializationKind() == 1216 TSK_ExplicitInstantiationDeclaration && 1217 TSK == TSK_ExplicitInstantiationDefinition) { 1218 // An explicit instantiation definition follows an explicit instantiation 1219 // declaration (C++0x [temp.explicit]p10); go ahead and perform the 1220 // explicit instantiation. 1221 ClassTemplateSpec->setSpecializationKind(TSK); 1222 return false; 1223 } 1224 1225 // We can only instantiate something that hasn't already been 1226 // instantiated or specialized. Fail without any diagnostics: our 1227 // caller will provide an error message. 1228 return true; 1229 } 1230 1231 if (ClassTemplateSpec->isInvalidDecl()) 1232 return true; 1233 1234 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 1235 CXXRecordDecl *Pattern = 0; 1236 1237 // C++ [temp.class.spec.match]p1: 1238 // When a class template is used in a context that requires an 1239 // instantiation of the class, it is necessary to determine 1240 // whether the instantiation is to be generated using the primary 1241 // template or one of the partial specializations. This is done by 1242 // matching the template arguments of the class template 1243 // specialization with the template argument lists of the partial 1244 // specializations. 1245 typedef std::pair<ClassTemplatePartialSpecializationDecl *, 1246 TemplateArgumentList *> MatchResult; 1247 llvm::SmallVector<MatchResult, 4> Matched; 1248 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 1249 Partial = Template->getPartialSpecializations().begin(), 1250 PartialEnd = Template->getPartialSpecializations().end(); 1251 Partial != PartialEnd; 1252 ++Partial) { 1253 TemplateDeductionInfo Info(Context, PointOfInstantiation); 1254 if (TemplateDeductionResult Result 1255 = DeduceTemplateArguments(&*Partial, 1256 ClassTemplateSpec->getTemplateArgs(), 1257 Info)) { 1258 // FIXME: Store the failed-deduction information for use in 1259 // diagnostics, later. 1260 (void)Result; 1261 } else { 1262 Matched.push_back(std::make_pair(&*Partial, Info.take())); 1263 } 1264 } 1265 1266 if (Matched.size() >= 1) { 1267 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); 1268 if (Matched.size() == 1) { 1269 // -- If exactly one matching specialization is found, the 1270 // instantiation is generated from that specialization. 1271 // We don't need to do anything for this. 1272 } else { 1273 // -- If more than one matching specialization is found, the 1274 // partial order rules (14.5.4.2) are used to determine 1275 // whether one of the specializations is more specialized 1276 // than the others. If none of the specializations is more 1277 // specialized than all of the other matching 1278 // specializations, then the use of the class template is 1279 // ambiguous and the program is ill-formed. 1280 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1, 1281 PEnd = Matched.end(); 1282 P != PEnd; ++P) { 1283 if (getMoreSpecializedPartialSpecialization(P->first, Best->first, 1284 PointOfInstantiation) 1285 == P->first) 1286 Best = P; 1287 } 1288 1289 // Determine if the best partial specialization is more specialized than 1290 // the others. 1291 bool Ambiguous = false; 1292 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 1293 PEnd = Matched.end(); 1294 P != PEnd; ++P) { 1295 if (P != Best && 1296 getMoreSpecializedPartialSpecialization(P->first, Best->first, 1297 PointOfInstantiation) 1298 != Best->first) { 1299 Ambiguous = true; 1300 break; 1301 } 1302 } 1303 1304 if (Ambiguous) { 1305 // Partial ordering did not produce a clear winner. Complain. 1306 ClassTemplateSpec->setInvalidDecl(); 1307 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) 1308 << ClassTemplateSpec; 1309 1310 // Print the matching partial specializations. 1311 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 1312 PEnd = Matched.end(); 1313 P != PEnd; ++P) 1314 Diag(P->first->getLocation(), diag::note_partial_spec_match) 1315 << getTemplateArgumentBindingsText(P->first->getTemplateParameters(), 1316 *P->second); 1317 1318 return true; 1319 } 1320 } 1321 1322 // Instantiate using the best class template partial specialization. 1323 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->first; 1324 while (OrigPartialSpec->getInstantiatedFromMember()) { 1325 // If we've found an explicit specialization of this class template, 1326 // stop here and use that as the pattern. 1327 if (OrigPartialSpec->isMemberSpecialization()) 1328 break; 1329 1330 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember(); 1331 } 1332 1333 Pattern = OrigPartialSpec; 1334 ClassTemplateSpec->setInstantiationOf(Best->first, Best->second); 1335 } else { 1336 // -- If no matches are found, the instantiation is generated 1337 // from the primary template. 1338 ClassTemplateDecl *OrigTemplate = Template; 1339 while (OrigTemplate->getInstantiatedFromMemberTemplate()) { 1340 // If we've found an explicit specialization of this class template, 1341 // stop here and use that as the pattern. 1342 if (OrigTemplate->isMemberSpecialization()) 1343 break; 1344 1345 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate(); 1346 } 1347 1348 Pattern = OrigTemplate->getTemplatedDecl(); 1349 } 1350 1351 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec, 1352 Pattern, 1353 getTemplateInstantiationArgs(ClassTemplateSpec), 1354 TSK, 1355 Complain); 1356 1357 for (unsigned I = 0, N = Matched.size(); I != N; ++I) { 1358 // FIXME: Implement TemplateArgumentList::Destroy! 1359 // if (Matched[I].first != Pattern) 1360 // Matched[I].second->Destroy(Context); 1361 } 1362 1363 return Result; 1364} 1365 1366/// \brief Instantiates the definitions of all of the member 1367/// of the given class, which is an instantiation of a class template 1368/// or a member class of a template. 1369void 1370Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 1371 CXXRecordDecl *Instantiation, 1372 const MultiLevelTemplateArgumentList &TemplateArgs, 1373 TemplateSpecializationKind TSK) { 1374 for (DeclContext::decl_iterator D = Instantiation->decls_begin(), 1375 DEnd = Instantiation->decls_end(); 1376 D != DEnd; ++D) { 1377 bool SuppressNew = false; 1378 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) { 1379 if (FunctionDecl *Pattern 1380 = Function->getInstantiatedFromMemberFunction()) { 1381 MemberSpecializationInfo *MSInfo 1382 = Function->getMemberSpecializationInfo(); 1383 assert(MSInfo && "No member specialization information?"); 1384 if (MSInfo->getTemplateSpecializationKind() 1385 == TSK_ExplicitSpecialization) 1386 continue; 1387 1388 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 1389 Function, 1390 MSInfo->getTemplateSpecializationKind(), 1391 MSInfo->getPointOfInstantiation(), 1392 SuppressNew) || 1393 SuppressNew) 1394 continue; 1395 1396 if (Function->getBody()) 1397 continue; 1398 1399 if (TSK == TSK_ExplicitInstantiationDefinition) { 1400 // C++0x [temp.explicit]p8: 1401 // An explicit instantiation definition that names a class template 1402 // specialization explicitly instantiates the class template 1403 // specialization and is only an explicit instantiation definition 1404 // of members whose definition is visible at the point of 1405 // instantiation. 1406 if (!Pattern->getBody()) 1407 continue; 1408 1409 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 1410 1411 InstantiateFunctionDefinition(PointOfInstantiation, Function); 1412 } else { 1413 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 1414 } 1415 } 1416 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) { 1417 if (Var->isStaticDataMember()) { 1418 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 1419 assert(MSInfo && "No member specialization information?"); 1420 if (MSInfo->getTemplateSpecializationKind() 1421 == TSK_ExplicitSpecialization) 1422 continue; 1423 1424 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 1425 Var, 1426 MSInfo->getTemplateSpecializationKind(), 1427 MSInfo->getPointOfInstantiation(), 1428 SuppressNew) || 1429 SuppressNew) 1430 continue; 1431 1432 if (TSK == TSK_ExplicitInstantiationDefinition) { 1433 // C++0x [temp.explicit]p8: 1434 // An explicit instantiation definition that names a class template 1435 // specialization explicitly instantiates the class template 1436 // specialization and is only an explicit instantiation definition 1437 // of members whose definition is visible at the point of 1438 // instantiation. 1439 if (!Var->getInstantiatedFromStaticDataMember() 1440 ->getOutOfLineDefinition()) 1441 continue; 1442 1443 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 1444 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var); 1445 } else { 1446 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 1447 } 1448 } 1449 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) { 1450 if (Record->isInjectedClassName()) 1451 continue; 1452 1453 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); 1454 assert(MSInfo && "No member specialization information?"); 1455 1456 if (MSInfo->getTemplateSpecializationKind() 1457 == TSK_ExplicitSpecialization) 1458 continue; 1459 1460 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 1461 Record, 1462 MSInfo->getTemplateSpecializationKind(), 1463 MSInfo->getPointOfInstantiation(), 1464 SuppressNew) || 1465 SuppressNew) 1466 continue; 1467 1468 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 1469 assert(Pattern && "Missing instantiated-from-template information"); 1470 1471 if (!Record->getDefinition()) { 1472 if (!Pattern->getDefinition()) { 1473 // C++0x [temp.explicit]p8: 1474 // An explicit instantiation definition that names a class template 1475 // specialization explicitly instantiates the class template 1476 // specialization and is only an explicit instantiation definition 1477 // of members whose definition is visible at the point of 1478 // instantiation. 1479 if (TSK == TSK_ExplicitInstantiationDeclaration) { 1480 MSInfo->setTemplateSpecializationKind(TSK); 1481 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1482 } 1483 1484 continue; 1485 } 1486 1487 InstantiateClass(PointOfInstantiation, Record, Pattern, 1488 TemplateArgs, 1489 TSK); 1490 } 1491 1492 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 1493 if (Pattern) 1494 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, 1495 TSK); 1496 } 1497 } 1498} 1499 1500/// \brief Instantiate the definitions of all of the members of the 1501/// given class template specialization, which was named as part of an 1502/// explicit instantiation. 1503void 1504Sema::InstantiateClassTemplateSpecializationMembers( 1505 SourceLocation PointOfInstantiation, 1506 ClassTemplateSpecializationDecl *ClassTemplateSpec, 1507 TemplateSpecializationKind TSK) { 1508 // C++0x [temp.explicit]p7: 1509 // An explicit instantiation that names a class template 1510 // specialization is an explicit instantion of the same kind 1511 // (declaration or definition) of each of its members (not 1512 // including members inherited from base classes) that has not 1513 // been previously explicitly specialized in the translation unit 1514 // containing the explicit instantiation, except as described 1515 // below. 1516 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 1517 getTemplateInstantiationArgs(ClassTemplateSpec), 1518 TSK); 1519} 1520 1521Sema::OwningStmtResult 1522Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { 1523 if (!S) 1524 return Owned(S); 1525 1526 TemplateInstantiator Instantiator(*this, TemplateArgs, 1527 SourceLocation(), 1528 DeclarationName()); 1529 return Instantiator.TransformStmt(S); 1530} 1531 1532Sema::OwningExprResult 1533Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 1534 if (!E) 1535 return Owned(E); 1536 1537 TemplateInstantiator Instantiator(*this, TemplateArgs, 1538 SourceLocation(), 1539 DeclarationName()); 1540 return Instantiator.TransformExpr(E); 1541} 1542 1543/// \brief Do template substitution on a nested-name-specifier. 1544NestedNameSpecifier * 1545Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS, 1546 SourceRange Range, 1547 const MultiLevelTemplateArgumentList &TemplateArgs) { 1548 TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(), 1549 DeclarationName()); 1550 return Instantiator.TransformNestedNameSpecifier(NNS, Range); 1551} 1552 1553TemplateName 1554Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc, 1555 const MultiLevelTemplateArgumentList &TemplateArgs) { 1556 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 1557 DeclarationName()); 1558 return Instantiator.TransformTemplateName(Name); 1559} 1560 1561bool Sema::Subst(const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output, 1562 const MultiLevelTemplateArgumentList &TemplateArgs) { 1563 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 1564 DeclarationName()); 1565 1566 return Instantiator.TransformTemplateArgument(Input, Output); 1567} 1568