SemaTemplateInstantiate.cpp revision 234353
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 "clang/Sema/SemaInternal.h" 14#include "TreeTransform.h" 15#include "clang/Sema/DeclSpec.h" 16#include "clang/Sema/Initialization.h" 17#include "clang/Sema/Lookup.h" 18#include "clang/Sema/Template.h" 19#include "clang/Sema/TemplateDeduction.h" 20#include "clang/AST/ASTConsumer.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/Expr.h" 23#include "clang/AST/DeclTemplate.h" 24#include "clang/Basic/LangOptions.h" 25 26using namespace clang; 27using namespace sema; 28 29//===----------------------------------------------------------------------===/ 30// Template Instantiation Support 31//===----------------------------------------------------------------------===/ 32 33/// \brief Retrieve the template argument list(s) that should be used to 34/// instantiate the definition of the given declaration. 35/// 36/// \param D the declaration for which we are computing template instantiation 37/// arguments. 38/// 39/// \param Innermost if non-NULL, the innermost template argument list. 40/// 41/// \param RelativeToPrimary true if we should get the template 42/// arguments relative to the primary template, even when we're 43/// dealing with a specialization. This is only relevant for function 44/// template specializations. 45/// 46/// \param Pattern If non-NULL, indicates the pattern from which we will be 47/// instantiating the definition of the given declaration, \p D. This is 48/// used to determine the proper set of template instantiation arguments for 49/// friend function template specializations. 50MultiLevelTemplateArgumentList 51Sema::getTemplateInstantiationArgs(NamedDecl *D, 52 const TemplateArgumentList *Innermost, 53 bool RelativeToPrimary, 54 const FunctionDecl *Pattern) { 55 // Accumulate the set of template argument lists in this structure. 56 MultiLevelTemplateArgumentList Result; 57 58 if (Innermost) 59 Result.addOuterTemplateArguments(Innermost); 60 61 DeclContext *Ctx = dyn_cast<DeclContext>(D); 62 if (!Ctx) { 63 Ctx = D->getDeclContext(); 64 65 // If we have a template template parameter with translation unit context, 66 // then we're performing substitution into a default template argument of 67 // this template template parameter before we've constructed the template 68 // that will own this template template parameter. In this case, we 69 // use empty template parameter lists for all of the outer templates 70 // to avoid performing any substitutions. 71 if (Ctx->isTranslationUnit()) { 72 if (TemplateTemplateParmDecl *TTP 73 = dyn_cast<TemplateTemplateParmDecl>(D)) { 74 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I) 75 Result.addOuterTemplateArguments(0, 0); 76 return Result; 77 } 78 } 79 } 80 81 while (!Ctx->isFileContext()) { 82 // Add template arguments from a class template instantiation. 83 if (ClassTemplateSpecializationDecl *Spec 84 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) { 85 // We're done when we hit an explicit specialization. 86 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization && 87 !isa<ClassTemplatePartialSpecializationDecl>(Spec)) 88 break; 89 90 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); 91 92 // If this class template specialization was instantiated from a 93 // specialized member that is a class template, we're done. 94 assert(Spec->getSpecializedTemplate() && "No class template?"); 95 if (Spec->getSpecializedTemplate()->isMemberSpecialization()) 96 break; 97 } 98 // Add template arguments from a function template specialization. 99 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) { 100 if (!RelativeToPrimary && 101 (Function->getTemplateSpecializationKind() == 102 TSK_ExplicitSpecialization && 103 !Function->getClassScopeSpecializationPattern())) 104 break; 105 106 if (const TemplateArgumentList *TemplateArgs 107 = Function->getTemplateSpecializationArgs()) { 108 // Add the template arguments for this specialization. 109 Result.addOuterTemplateArguments(TemplateArgs); 110 111 // If this function was instantiated from a specialized member that is 112 // a function template, we're done. 113 assert(Function->getPrimaryTemplate() && "No function template?"); 114 if (Function->getPrimaryTemplate()->isMemberSpecialization()) 115 break; 116 } else if (FunctionTemplateDecl *FunTmpl 117 = Function->getDescribedFunctionTemplate()) { 118 // Add the "injected" template arguments. 119 std::pair<const TemplateArgument *, unsigned> 120 Injected = FunTmpl->getInjectedTemplateArgs(); 121 Result.addOuterTemplateArguments(Injected.first, Injected.second); 122 } 123 124 // If this is a friend declaration and it declares an entity at 125 // namespace scope, take arguments from its lexical parent 126 // instead of its semantic parent, unless of course the pattern we're 127 // instantiating actually comes from the file's context! 128 if (Function->getFriendObjectKind() && 129 Function->getDeclContext()->isFileContext() && 130 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) { 131 Ctx = Function->getLexicalDeclContext(); 132 RelativeToPrimary = false; 133 continue; 134 } 135 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) { 136 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) { 137 QualType T = ClassTemplate->getInjectedClassNameSpecialization(); 138 const TemplateSpecializationType *TST 139 = cast<TemplateSpecializationType>(Context.getCanonicalType(T)); 140 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs()); 141 if (ClassTemplate->isMemberSpecialization()) 142 break; 143 } 144 } 145 146 Ctx = Ctx->getParent(); 147 RelativeToPrimary = false; 148 } 149 150 return Result; 151} 152 153bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const { 154 switch (Kind) { 155 case TemplateInstantiation: 156 case DefaultTemplateArgumentInstantiation: 157 case DefaultFunctionArgumentInstantiation: 158 return true; 159 160 case ExplicitTemplateArgumentSubstitution: 161 case DeducedTemplateArgumentSubstitution: 162 case PriorTemplateArgumentSubstitution: 163 case DefaultTemplateArgumentChecking: 164 return false; 165 } 166 167 llvm_unreachable("Invalid InstantiationKind!"); 168} 169 170Sema::InstantiatingTemplate:: 171InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 172 Decl *Entity, 173 SourceRange InstantiationRange) 174 : SemaRef(SemaRef), 175 SavedInNonInstantiationSFINAEContext( 176 SemaRef.InNonInstantiationSFINAEContext) 177{ 178 Invalid = CheckInstantiationDepth(PointOfInstantiation, 179 InstantiationRange); 180 if (!Invalid) { 181 ActiveTemplateInstantiation Inst; 182 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation; 183 Inst.PointOfInstantiation = PointOfInstantiation; 184 Inst.Entity = reinterpret_cast<uintptr_t>(Entity); 185 Inst.TemplateArgs = 0; 186 Inst.NumTemplateArgs = 0; 187 Inst.InstantiationRange = InstantiationRange; 188 SemaRef.InNonInstantiationSFINAEContext = false; 189 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 190 } 191} 192 193Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 194 SourceLocation PointOfInstantiation, 195 TemplateDecl *Template, 196 const TemplateArgument *TemplateArgs, 197 unsigned NumTemplateArgs, 198 SourceRange InstantiationRange) 199 : SemaRef(SemaRef), 200 SavedInNonInstantiationSFINAEContext( 201 SemaRef.InNonInstantiationSFINAEContext) 202{ 203 Invalid = CheckInstantiationDepth(PointOfInstantiation, 204 InstantiationRange); 205 if (!Invalid) { 206 ActiveTemplateInstantiation Inst; 207 Inst.Kind 208 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation; 209 Inst.PointOfInstantiation = PointOfInstantiation; 210 Inst.Entity = reinterpret_cast<uintptr_t>(Template); 211 Inst.TemplateArgs = TemplateArgs; 212 Inst.NumTemplateArgs = NumTemplateArgs; 213 Inst.InstantiationRange = InstantiationRange; 214 SemaRef.InNonInstantiationSFINAEContext = false; 215 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 216 } 217} 218 219Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 220 SourceLocation PointOfInstantiation, 221 FunctionTemplateDecl *FunctionTemplate, 222 const TemplateArgument *TemplateArgs, 223 unsigned NumTemplateArgs, 224 ActiveTemplateInstantiation::InstantiationKind Kind, 225 sema::TemplateDeductionInfo &DeductionInfo, 226 SourceRange InstantiationRange) 227 : SemaRef(SemaRef), 228 SavedInNonInstantiationSFINAEContext( 229 SemaRef.InNonInstantiationSFINAEContext) 230{ 231 Invalid = CheckInstantiationDepth(PointOfInstantiation, 232 InstantiationRange); 233 if (!Invalid) { 234 ActiveTemplateInstantiation Inst; 235 Inst.Kind = Kind; 236 Inst.PointOfInstantiation = PointOfInstantiation; 237 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate); 238 Inst.TemplateArgs = TemplateArgs; 239 Inst.NumTemplateArgs = NumTemplateArgs; 240 Inst.DeductionInfo = &DeductionInfo; 241 Inst.InstantiationRange = InstantiationRange; 242 SemaRef.InNonInstantiationSFINAEContext = false; 243 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 244 245 if (!Inst.isInstantiationRecord()) 246 ++SemaRef.NonInstantiationEntries; 247 } 248} 249 250Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 251 SourceLocation PointOfInstantiation, 252 ClassTemplatePartialSpecializationDecl *PartialSpec, 253 const TemplateArgument *TemplateArgs, 254 unsigned NumTemplateArgs, 255 sema::TemplateDeductionInfo &DeductionInfo, 256 SourceRange InstantiationRange) 257 : SemaRef(SemaRef), 258 SavedInNonInstantiationSFINAEContext( 259 SemaRef.InNonInstantiationSFINAEContext) 260{ 261 Invalid = false; 262 263 ActiveTemplateInstantiation Inst; 264 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution; 265 Inst.PointOfInstantiation = PointOfInstantiation; 266 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec); 267 Inst.TemplateArgs = TemplateArgs; 268 Inst.NumTemplateArgs = NumTemplateArgs; 269 Inst.DeductionInfo = &DeductionInfo; 270 Inst.InstantiationRange = InstantiationRange; 271 SemaRef.InNonInstantiationSFINAEContext = false; 272 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 273 274 assert(!Inst.isInstantiationRecord()); 275 ++SemaRef.NonInstantiationEntries; 276} 277 278Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 279 SourceLocation PointOfInstantiation, 280 ParmVarDecl *Param, 281 const TemplateArgument *TemplateArgs, 282 unsigned NumTemplateArgs, 283 SourceRange InstantiationRange) 284 : SemaRef(SemaRef), 285 SavedInNonInstantiationSFINAEContext( 286 SemaRef.InNonInstantiationSFINAEContext) 287{ 288 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange); 289 290 if (!Invalid) { 291 ActiveTemplateInstantiation Inst; 292 Inst.Kind 293 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 294 Inst.PointOfInstantiation = PointOfInstantiation; 295 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 296 Inst.TemplateArgs = TemplateArgs; 297 Inst.NumTemplateArgs = NumTemplateArgs; 298 Inst.InstantiationRange = InstantiationRange; 299 SemaRef.InNonInstantiationSFINAEContext = false; 300 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 301 } 302} 303 304Sema::InstantiatingTemplate:: 305InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 306 NamedDecl *Template, 307 NonTypeTemplateParmDecl *Param, 308 const TemplateArgument *TemplateArgs, 309 unsigned NumTemplateArgs, 310 SourceRange InstantiationRange) 311 : SemaRef(SemaRef), 312 SavedInNonInstantiationSFINAEContext( 313 SemaRef.InNonInstantiationSFINAEContext) 314{ 315 Invalid = false; 316 317 ActiveTemplateInstantiation Inst; 318 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution; 319 Inst.PointOfInstantiation = PointOfInstantiation; 320 Inst.Template = Template; 321 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 322 Inst.TemplateArgs = TemplateArgs; 323 Inst.NumTemplateArgs = NumTemplateArgs; 324 Inst.InstantiationRange = InstantiationRange; 325 SemaRef.InNonInstantiationSFINAEContext = false; 326 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 327 328 assert(!Inst.isInstantiationRecord()); 329 ++SemaRef.NonInstantiationEntries; 330} 331 332Sema::InstantiatingTemplate:: 333InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 334 NamedDecl *Template, 335 TemplateTemplateParmDecl *Param, 336 const TemplateArgument *TemplateArgs, 337 unsigned NumTemplateArgs, 338 SourceRange InstantiationRange) 339 : SemaRef(SemaRef), 340 SavedInNonInstantiationSFINAEContext( 341 SemaRef.InNonInstantiationSFINAEContext) 342{ 343 Invalid = false; 344 ActiveTemplateInstantiation Inst; 345 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution; 346 Inst.PointOfInstantiation = PointOfInstantiation; 347 Inst.Template = Template; 348 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 349 Inst.TemplateArgs = TemplateArgs; 350 Inst.NumTemplateArgs = NumTemplateArgs; 351 Inst.InstantiationRange = InstantiationRange; 352 SemaRef.InNonInstantiationSFINAEContext = false; 353 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 354 355 assert(!Inst.isInstantiationRecord()); 356 ++SemaRef.NonInstantiationEntries; 357} 358 359Sema::InstantiatingTemplate:: 360InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 361 TemplateDecl *Template, 362 NamedDecl *Param, 363 const TemplateArgument *TemplateArgs, 364 unsigned NumTemplateArgs, 365 SourceRange InstantiationRange) 366 : SemaRef(SemaRef), 367 SavedInNonInstantiationSFINAEContext( 368 SemaRef.InNonInstantiationSFINAEContext) 369{ 370 Invalid = false; 371 372 ActiveTemplateInstantiation Inst; 373 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking; 374 Inst.PointOfInstantiation = PointOfInstantiation; 375 Inst.Template = Template; 376 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 377 Inst.TemplateArgs = TemplateArgs; 378 Inst.NumTemplateArgs = NumTemplateArgs; 379 Inst.InstantiationRange = InstantiationRange; 380 SemaRef.InNonInstantiationSFINAEContext = false; 381 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 382 383 assert(!Inst.isInstantiationRecord()); 384 ++SemaRef.NonInstantiationEntries; 385} 386 387void Sema::InstantiatingTemplate::Clear() { 388 if (!Invalid) { 389 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) { 390 assert(SemaRef.NonInstantiationEntries > 0); 391 --SemaRef.NonInstantiationEntries; 392 } 393 SemaRef.InNonInstantiationSFINAEContext 394 = SavedInNonInstantiationSFINAEContext; 395 SemaRef.ActiveTemplateInstantiations.pop_back(); 396 Invalid = true; 397 } 398} 399 400bool Sema::InstantiatingTemplate::CheckInstantiationDepth( 401 SourceLocation PointOfInstantiation, 402 SourceRange InstantiationRange) { 403 assert(SemaRef.NonInstantiationEntries <= 404 SemaRef.ActiveTemplateInstantiations.size()); 405 if ((SemaRef.ActiveTemplateInstantiations.size() - 406 SemaRef.NonInstantiationEntries) 407 <= SemaRef.getLangOpts().InstantiationDepth) 408 return false; 409 410 SemaRef.Diag(PointOfInstantiation, 411 diag::err_template_recursion_depth_exceeded) 412 << SemaRef.getLangOpts().InstantiationDepth 413 << InstantiationRange; 414 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) 415 << SemaRef.getLangOpts().InstantiationDepth; 416 return true; 417} 418 419/// \brief Prints the current instantiation stack through a series of 420/// notes. 421void Sema::PrintInstantiationStack() { 422 // Determine which template instantiations to skip, if any. 423 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart; 424 unsigned Limit = Diags.getTemplateBacktraceLimit(); 425 if (Limit && Limit < ActiveTemplateInstantiations.size()) { 426 SkipStart = Limit / 2 + Limit % 2; 427 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2; 428 } 429 430 // FIXME: In all of these cases, we need to show the template arguments 431 unsigned InstantiationIdx = 0; 432 for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator 433 Active = ActiveTemplateInstantiations.rbegin(), 434 ActiveEnd = ActiveTemplateInstantiations.rend(); 435 Active != ActiveEnd; 436 ++Active, ++InstantiationIdx) { 437 // Skip this instantiation? 438 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) { 439 if (InstantiationIdx == SkipStart) { 440 // Note that we're skipping instantiations. 441 Diags.Report(Active->PointOfInstantiation, 442 diag::note_instantiation_contexts_suppressed) 443 << unsigned(ActiveTemplateInstantiations.size() - Limit); 444 } 445 continue; 446 } 447 448 switch (Active->Kind) { 449 case ActiveTemplateInstantiation::TemplateInstantiation: { 450 Decl *D = reinterpret_cast<Decl *>(Active->Entity); 451 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 452 unsigned DiagID = diag::note_template_member_class_here; 453 if (isa<ClassTemplateSpecializationDecl>(Record)) 454 DiagID = diag::note_template_class_instantiation_here; 455 Diags.Report(Active->PointOfInstantiation, DiagID) 456 << Context.getTypeDeclType(Record) 457 << Active->InstantiationRange; 458 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 459 unsigned DiagID; 460 if (Function->getPrimaryTemplate()) 461 DiagID = diag::note_function_template_spec_here; 462 else 463 DiagID = diag::note_template_member_function_here; 464 Diags.Report(Active->PointOfInstantiation, DiagID) 465 << Function 466 << Active->InstantiationRange; 467 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 468 Diags.Report(Active->PointOfInstantiation, 469 diag::note_template_static_data_member_def_here) 470 << VD 471 << Active->InstantiationRange; 472 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 473 Diags.Report(Active->PointOfInstantiation, 474 diag::note_template_enum_def_here) 475 << ED 476 << Active->InstantiationRange; 477 } else { 478 Diags.Report(Active->PointOfInstantiation, 479 diag::note_template_type_alias_instantiation_here) 480 << cast<TypeAliasTemplateDecl>(D) 481 << Active->InstantiationRange; 482 } 483 break; 484 } 485 486 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: { 487 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity); 488 std::string TemplateArgsStr 489 = TemplateSpecializationType::PrintTemplateArgumentList( 490 Active->TemplateArgs, 491 Active->NumTemplateArgs, 492 getPrintingPolicy()); 493 Diags.Report(Active->PointOfInstantiation, 494 diag::note_default_arg_instantiation_here) 495 << (Template->getNameAsString() + TemplateArgsStr) 496 << Active->InstantiationRange; 497 break; 498 } 499 500 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: { 501 FunctionTemplateDecl *FnTmpl 502 = cast<FunctionTemplateDecl>((Decl *)Active->Entity); 503 Diags.Report(Active->PointOfInstantiation, 504 diag::note_explicit_template_arg_substitution_here) 505 << FnTmpl 506 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 507 Active->TemplateArgs, 508 Active->NumTemplateArgs) 509 << Active->InstantiationRange; 510 break; 511 } 512 513 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 514 if (ClassTemplatePartialSpecializationDecl *PartialSpec 515 = dyn_cast<ClassTemplatePartialSpecializationDecl>( 516 (Decl *)Active->Entity)) { 517 Diags.Report(Active->PointOfInstantiation, 518 diag::note_partial_spec_deduct_instantiation_here) 519 << Context.getTypeDeclType(PartialSpec) 520 << getTemplateArgumentBindingsText( 521 PartialSpec->getTemplateParameters(), 522 Active->TemplateArgs, 523 Active->NumTemplateArgs) 524 << Active->InstantiationRange; 525 } else { 526 FunctionTemplateDecl *FnTmpl 527 = cast<FunctionTemplateDecl>((Decl *)Active->Entity); 528 Diags.Report(Active->PointOfInstantiation, 529 diag::note_function_template_deduction_instantiation_here) 530 << FnTmpl 531 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 532 Active->TemplateArgs, 533 Active->NumTemplateArgs) 534 << Active->InstantiationRange; 535 } 536 break; 537 538 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: { 539 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity); 540 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); 541 542 std::string TemplateArgsStr 543 = TemplateSpecializationType::PrintTemplateArgumentList( 544 Active->TemplateArgs, 545 Active->NumTemplateArgs, 546 getPrintingPolicy()); 547 Diags.Report(Active->PointOfInstantiation, 548 diag::note_default_function_arg_instantiation_here) 549 << (FD->getNameAsString() + TemplateArgsStr) 550 << Active->InstantiationRange; 551 break; 552 } 553 554 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: { 555 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity); 556 std::string Name; 557 if (!Parm->getName().empty()) 558 Name = std::string(" '") + Parm->getName().str() + "'"; 559 560 TemplateParameterList *TemplateParams = 0; 561 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template)) 562 TemplateParams = Template->getTemplateParameters(); 563 else 564 TemplateParams = 565 cast<ClassTemplatePartialSpecializationDecl>(Active->Template) 566 ->getTemplateParameters(); 567 Diags.Report(Active->PointOfInstantiation, 568 diag::note_prior_template_arg_substitution) 569 << isa<TemplateTemplateParmDecl>(Parm) 570 << Name 571 << getTemplateArgumentBindingsText(TemplateParams, 572 Active->TemplateArgs, 573 Active->NumTemplateArgs) 574 << Active->InstantiationRange; 575 break; 576 } 577 578 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: { 579 TemplateParameterList *TemplateParams = 0; 580 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template)) 581 TemplateParams = Template->getTemplateParameters(); 582 else 583 TemplateParams = 584 cast<ClassTemplatePartialSpecializationDecl>(Active->Template) 585 ->getTemplateParameters(); 586 587 Diags.Report(Active->PointOfInstantiation, 588 diag::note_template_default_arg_checking) 589 << getTemplateArgumentBindingsText(TemplateParams, 590 Active->TemplateArgs, 591 Active->NumTemplateArgs) 592 << Active->InstantiationRange; 593 break; 594 } 595 } 596 } 597} 598 599llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { 600 if (InNonInstantiationSFINAEContext) 601 return llvm::Optional<TemplateDeductionInfo *>(0); 602 603 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator 604 Active = ActiveTemplateInstantiations.rbegin(), 605 ActiveEnd = ActiveTemplateInstantiations.rend(); 606 Active != ActiveEnd; 607 ++Active) 608 { 609 switch(Active->Kind) { 610 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: 611 case ActiveTemplateInstantiation::TemplateInstantiation: 612 // This is a template instantiation, so there is no SFINAE. 613 return llvm::Optional<TemplateDeductionInfo *>(); 614 615 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: 616 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: 617 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: 618 // A default template argument instantiation and substitution into 619 // template parameters with arguments for prior parameters may or may 620 // not be a SFINAE context; look further up the stack. 621 break; 622 623 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: 624 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 625 // We're either substitution explicitly-specified template arguments 626 // or deduced template arguments, so SFINAE applies. 627 assert(Active->DeductionInfo && "Missing deduction info pointer"); 628 return Active->DeductionInfo; 629 } 630 } 631 632 return llvm::Optional<TemplateDeductionInfo *>(); 633} 634 635/// \brief Retrieve the depth and index of a parameter pack. 636static std::pair<unsigned, unsigned> 637getDepthAndIndex(NamedDecl *ND) { 638 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND)) 639 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 640 641 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND)) 642 return std::make_pair(NTTP->getDepth(), NTTP->getIndex()); 643 644 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND); 645 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 646} 647 648//===----------------------------------------------------------------------===/ 649// Template Instantiation for Types 650//===----------------------------------------------------------------------===/ 651namespace { 652 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> { 653 const MultiLevelTemplateArgumentList &TemplateArgs; 654 SourceLocation Loc; 655 DeclarationName Entity; 656 657 public: 658 typedef TreeTransform<TemplateInstantiator> inherited; 659 660 TemplateInstantiator(Sema &SemaRef, 661 const MultiLevelTemplateArgumentList &TemplateArgs, 662 SourceLocation Loc, 663 DeclarationName Entity) 664 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), 665 Entity(Entity) { } 666 667 /// \brief Determine whether the given type \p T has already been 668 /// transformed. 669 /// 670 /// For the purposes of template instantiation, a type has already been 671 /// transformed if it is NULL or if it is not dependent. 672 bool AlreadyTransformed(QualType T); 673 674 /// \brief Returns the location of the entity being instantiated, if known. 675 SourceLocation getBaseLocation() { return Loc; } 676 677 /// \brief Returns the name of the entity being instantiated, if any. 678 DeclarationName getBaseEntity() { return Entity; } 679 680 /// \brief Sets the "base" location and entity when that 681 /// information is known based on another transformation. 682 void setBase(SourceLocation Loc, DeclarationName Entity) { 683 this->Loc = Loc; 684 this->Entity = Entity; 685 } 686 687 bool TryExpandParameterPacks(SourceLocation EllipsisLoc, 688 SourceRange PatternRange, 689 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded, 690 bool &ShouldExpand, 691 bool &RetainExpansion, 692 llvm::Optional<unsigned> &NumExpansions) { 693 return getSema().CheckParameterPacksForExpansion(EllipsisLoc, 694 PatternRange, Unexpanded, 695 TemplateArgs, 696 ShouldExpand, 697 RetainExpansion, 698 NumExpansions); 699 } 700 701 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { 702 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack); 703 } 704 705 TemplateArgument ForgetPartiallySubstitutedPack() { 706 TemplateArgument Result; 707 if (NamedDecl *PartialPack 708 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ 709 MultiLevelTemplateArgumentList &TemplateArgs 710 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); 711 unsigned Depth, Index; 712 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack); 713 if (TemplateArgs.hasTemplateArgument(Depth, Index)) { 714 Result = TemplateArgs(Depth, Index); 715 TemplateArgs.setArgument(Depth, Index, TemplateArgument()); 716 } 717 } 718 719 return Result; 720 } 721 722 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { 723 if (Arg.isNull()) 724 return; 725 726 if (NamedDecl *PartialPack 727 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ 728 MultiLevelTemplateArgumentList &TemplateArgs 729 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); 730 unsigned Depth, Index; 731 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack); 732 TemplateArgs.setArgument(Depth, Index, Arg); 733 } 734 } 735 736 /// \brief Transform the given declaration by instantiating a reference to 737 /// this declaration. 738 Decl *TransformDecl(SourceLocation Loc, Decl *D); 739 740 void transformAttrs(Decl *Old, Decl *New) { 741 SemaRef.InstantiateAttrs(TemplateArgs, Old, New); 742 } 743 744 void transformedLocalDecl(Decl *Old, Decl *New) { 745 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New); 746 } 747 748 /// \brief Transform the definition of the given declaration by 749 /// instantiating it. 750 Decl *TransformDefinition(SourceLocation Loc, Decl *D); 751 752 /// \bried Transform the first qualifier within a scope by instantiating the 753 /// declaration. 754 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); 755 756 /// \brief Rebuild the exception declaration and register the declaration 757 /// as an instantiated local. 758 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, 759 TypeSourceInfo *Declarator, 760 SourceLocation StartLoc, 761 SourceLocation NameLoc, 762 IdentifierInfo *Name); 763 764 /// \brief Rebuild the Objective-C exception declaration and register the 765 /// declaration as an instantiated local. 766 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 767 TypeSourceInfo *TSInfo, QualType T); 768 769 /// \brief Check for tag mismatches when instantiating an 770 /// elaborated type. 771 QualType RebuildElaboratedType(SourceLocation KeywordLoc, 772 ElaboratedTypeKeyword Keyword, 773 NestedNameSpecifierLoc QualifierLoc, 774 QualType T); 775 776 TemplateName TransformTemplateName(CXXScopeSpec &SS, 777 TemplateName Name, 778 SourceLocation NameLoc, 779 QualType ObjectType = QualType(), 780 NamedDecl *FirstQualifierInScope = 0); 781 782 ExprResult TransformPredefinedExpr(PredefinedExpr *E); 783 ExprResult TransformDeclRefExpr(DeclRefExpr *E); 784 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E); 785 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E, 786 NonTypeTemplateParmDecl *D); 787 ExprResult TransformSubstNonTypeTemplateParmPackExpr( 788 SubstNonTypeTemplateParmPackExpr *E); 789 790 QualType TransformFunctionProtoType(TypeLocBuilder &TLB, 791 FunctionProtoTypeLoc TL); 792 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm, 793 int indexAdjustment, 794 llvm::Optional<unsigned> NumExpansions, 795 bool ExpectParameterPack); 796 797 /// \brief Transforms a template type parameter type by performing 798 /// substitution of the corresponding template type argument. 799 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, 800 TemplateTypeParmTypeLoc TL); 801 802 /// \brief Transforms an already-substituted template type parameter pack 803 /// into either itself (if we aren't substituting into its pack expansion) 804 /// or the appropriate substituted argument. 805 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB, 806 SubstTemplateTypeParmPackTypeLoc TL); 807 808 ExprResult TransformCallExpr(CallExpr *CE) { 809 getSema().CallsUndergoingInstantiation.push_back(CE); 810 ExprResult Result = 811 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE); 812 getSema().CallsUndergoingInstantiation.pop_back(); 813 return move(Result); 814 } 815 816 private: 817 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm, 818 SourceLocation loc, 819 const TemplateArgument &arg); 820 }; 821} 822 823bool TemplateInstantiator::AlreadyTransformed(QualType T) { 824 if (T.isNull()) 825 return true; 826 827 if (T->isInstantiationDependentType() || T->isVariablyModifiedType()) 828 return false; 829 830 getSema().MarkDeclarationsReferencedInType(Loc, T); 831 return true; 832} 833 834Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { 835 if (!D) 836 return 0; 837 838 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) { 839 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 840 // If the corresponding template argument is NULL or non-existent, it's 841 // because we are performing instantiation from explicitly-specified 842 // template arguments in a function template, but there were some 843 // arguments left unspecified. 844 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), 845 TTP->getPosition())) 846 return D; 847 848 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); 849 850 if (TTP->isParameterPack()) { 851 assert(Arg.getKind() == TemplateArgument::Pack && 852 "Missing argument pack"); 853 854 assert(getSema().ArgumentPackSubstitutionIndex >= 0); 855 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size()); 856 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex]; 857 } 858 859 TemplateName Template = Arg.getAsTemplate(); 860 assert(!Template.isNull() && Template.getAsTemplateDecl() && 861 "Wrong kind of template template argument"); 862 return Template.getAsTemplateDecl(); 863 } 864 865 // Fall through to find the instantiated declaration for this template 866 // template parameter. 867 } 868 869 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs); 870} 871 872Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { 873 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs); 874 if (!Inst) 875 return 0; 876 877 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); 878 return Inst; 879} 880 881NamedDecl * 882TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, 883 SourceLocation Loc) { 884 // If the first part of the nested-name-specifier was a template type 885 // parameter, instantiate that type parameter down to a tag type. 886 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) { 887 const TemplateTypeParmType *TTP 888 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD)); 889 890 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 891 // FIXME: This needs testing w/ member access expressions. 892 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex()); 893 894 if (TTP->isParameterPack()) { 895 assert(Arg.getKind() == TemplateArgument::Pack && 896 "Missing argument pack"); 897 898 if (getSema().ArgumentPackSubstitutionIndex == -1) 899 return 0; 900 901 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size()); 902 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex]; 903 } 904 905 QualType T = Arg.getAsType(); 906 if (T.isNull()) 907 return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); 908 909 if (const TagType *Tag = T->getAs<TagType>()) 910 return Tag->getDecl(); 911 912 // The resulting type is not a tag; complain. 913 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T; 914 return 0; 915 } 916 } 917 918 return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); 919} 920 921VarDecl * 922TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, 923 TypeSourceInfo *Declarator, 924 SourceLocation StartLoc, 925 SourceLocation NameLoc, 926 IdentifierInfo *Name) { 927 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator, 928 StartLoc, NameLoc, Name); 929 if (Var) 930 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); 931 return Var; 932} 933 934VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 935 TypeSourceInfo *TSInfo, 936 QualType T) { 937 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T); 938 if (Var) 939 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); 940 return Var; 941} 942 943QualType 944TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc, 945 ElaboratedTypeKeyword Keyword, 946 NestedNameSpecifierLoc QualifierLoc, 947 QualType T) { 948 if (const TagType *TT = T->getAs<TagType>()) { 949 TagDecl* TD = TT->getDecl(); 950 951 SourceLocation TagLocation = KeywordLoc; 952 953 // FIXME: type might be anonymous. 954 IdentifierInfo *Id = TD->getIdentifier(); 955 956 // TODO: should we even warn on struct/class mismatches for this? Seems 957 // like it's likely to produce a lot of spurious errors. 958 if (Keyword != ETK_None && Keyword != ETK_Typename) { 959 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword); 960 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false, 961 TagLocation, *Id)) { 962 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag) 963 << Id 964 << FixItHint::CreateReplacement(SourceRange(TagLocation), 965 TD->getKindName()); 966 SemaRef.Diag(TD->getLocation(), diag::note_previous_use); 967 } 968 } 969 } 970 971 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc, 972 Keyword, 973 QualifierLoc, 974 T); 975} 976 977TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS, 978 TemplateName Name, 979 SourceLocation NameLoc, 980 QualType ObjectType, 981 NamedDecl *FirstQualifierInScope) { 982 if (TemplateTemplateParmDecl *TTP 983 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) { 984 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 985 // If the corresponding template argument is NULL or non-existent, it's 986 // because we are performing instantiation from explicitly-specified 987 // template arguments in a function template, but there were some 988 // arguments left unspecified. 989 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), 990 TTP->getPosition())) 991 return Name; 992 993 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); 994 995 if (TTP->isParameterPack()) { 996 assert(Arg.getKind() == TemplateArgument::Pack && 997 "Missing argument pack"); 998 999 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1000 // We have the template argument pack to substitute, but we're not 1001 // actually expanding the enclosing pack expansion yet. So, just 1002 // keep the entire argument pack. 1003 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg); 1004 } 1005 1006 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size()); 1007 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex]; 1008 } 1009 1010 TemplateName Template = Arg.getAsTemplate(); 1011 assert(!Template.isNull() && "Null template template argument"); 1012 1013 // We don't ever want to substitute for a qualified template name, since 1014 // the qualifier is handled separately. So, look through the qualified 1015 // template name to its underlying declaration. 1016 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 1017 Template = TemplateName(QTN->getTemplateDecl()); 1018 1019 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template); 1020 return Template; 1021 } 1022 } 1023 1024 if (SubstTemplateTemplateParmPackStorage *SubstPack 1025 = Name.getAsSubstTemplateTemplateParmPack()) { 1026 if (getSema().ArgumentPackSubstitutionIndex == -1) 1027 return Name; 1028 1029 const TemplateArgument &ArgPack = SubstPack->getArgumentPack(); 1030 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() && 1031 "Pack substitution index out-of-range"); 1032 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex] 1033 .getAsTemplate(); 1034 } 1035 1036 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType, 1037 FirstQualifierInScope); 1038} 1039 1040ExprResult 1041TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { 1042 if (!E->isTypeDependent()) 1043 return SemaRef.Owned(E); 1044 1045 FunctionDecl *currentDecl = getSema().getCurFunctionDecl(); 1046 assert(currentDecl && "Must have current function declaration when " 1047 "instantiating."); 1048 1049 PredefinedExpr::IdentType IT = E->getIdentType(); 1050 1051 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 1052 1053 llvm::APInt LengthI(32, Length + 1); 1054 QualType ResTy = getSema().Context.CharTy.withConst(); 1055 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI, 1056 ArrayType::Normal, 0); 1057 PredefinedExpr *PE = 1058 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT); 1059 return getSema().Owned(PE); 1060} 1061 1062ExprResult 1063TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, 1064 NonTypeTemplateParmDecl *NTTP) { 1065 // If the corresponding template argument is NULL or non-existent, it's 1066 // because we are performing instantiation from explicitly-specified 1067 // template arguments in a function template, but there were some 1068 // arguments left unspecified. 1069 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(), 1070 NTTP->getPosition())) 1071 return SemaRef.Owned(E); 1072 1073 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition()); 1074 if (NTTP->isParameterPack()) { 1075 assert(Arg.getKind() == TemplateArgument::Pack && 1076 "Missing argument pack"); 1077 1078 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1079 // We have an argument pack, but we can't select a particular argument 1080 // out of it yet. Therefore, we'll build an expression to hold on to that 1081 // argument pack. 1082 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs, 1083 E->getLocation(), 1084 NTTP->getDeclName()); 1085 if (TargetType.isNull()) 1086 return ExprError(); 1087 1088 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType, 1089 NTTP, 1090 E->getLocation(), 1091 Arg); 1092 } 1093 1094 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size()); 1095 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex]; 1096 } 1097 1098 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg); 1099} 1100 1101ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( 1102 NonTypeTemplateParmDecl *parm, 1103 SourceLocation loc, 1104 const TemplateArgument &arg) { 1105 ExprResult result; 1106 QualType type; 1107 1108 // The template argument itself might be an expression, in which 1109 // case we just return that expression. 1110 if (arg.getKind() == TemplateArgument::Expression) { 1111 Expr *argExpr = arg.getAsExpr(); 1112 result = SemaRef.Owned(argExpr); 1113 type = argExpr->getType(); 1114 1115 } else if (arg.getKind() == TemplateArgument::Declaration) { 1116 ValueDecl *VD; 1117 if (Decl *D = arg.getAsDecl()) { 1118 VD = cast<ValueDecl>(D); 1119 1120 // Find the instantiation of the template argument. This is 1121 // required for nested templates. 1122 VD = cast_or_null<ValueDecl>( 1123 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs)); 1124 if (!VD) 1125 return ExprError(); 1126 } else { 1127 // Propagate NULL template argument. 1128 VD = 0; 1129 } 1130 1131 // Derive the type we want the substituted decl to have. This had 1132 // better be non-dependent, or these checks will have serious problems. 1133 if (parm->isExpandedParameterPack()) { 1134 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex); 1135 } else if (parm->isParameterPack() && 1136 isa<PackExpansionType>(parm->getType())) { 1137 type = SemaRef.SubstType( 1138 cast<PackExpansionType>(parm->getType())->getPattern(), 1139 TemplateArgs, loc, parm->getDeclName()); 1140 } else { 1141 type = SemaRef.SubstType(parm->getType(), TemplateArgs, 1142 loc, parm->getDeclName()); 1143 } 1144 assert(!type.isNull() && "type substitution failed for param type"); 1145 assert(!type->isDependentType() && "param type still dependent"); 1146 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc); 1147 1148 if (!result.isInvalid()) type = result.get()->getType(); 1149 } else { 1150 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc); 1151 1152 // Note that this type can be different from the type of 'result', 1153 // e.g. if it's an enum type. 1154 type = arg.getIntegralType(); 1155 } 1156 if (result.isInvalid()) return ExprError(); 1157 1158 Expr *resultExpr = result.take(); 1159 return SemaRef.Owned(new (SemaRef.Context) 1160 SubstNonTypeTemplateParmExpr(type, 1161 resultExpr->getValueKind(), 1162 loc, parm, resultExpr)); 1163} 1164 1165ExprResult 1166TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr( 1167 SubstNonTypeTemplateParmPackExpr *E) { 1168 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1169 // We aren't expanding the parameter pack, so just return ourselves. 1170 return getSema().Owned(E); 1171 } 1172 1173 const TemplateArgument &ArgPack = E->getArgumentPack(); 1174 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex; 1175 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range"); 1176 1177 const TemplateArgument &Arg = ArgPack.pack_begin()[Index]; 1178 return transformNonTypeTemplateParmRef(E->getParameterPack(), 1179 E->getParameterPackLocation(), 1180 Arg); 1181} 1182 1183ExprResult 1184TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { 1185 NamedDecl *D = E->getDecl(); 1186 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { 1187 if (NTTP->getDepth() < TemplateArgs.getNumLevels()) 1188 return TransformTemplateParmRefExpr(E, NTTP); 1189 1190 // We have a non-type template parameter that isn't fully substituted; 1191 // FindInstantiatedDecl will find it in the local instantiation scope. 1192 } 1193 1194 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E); 1195} 1196 1197ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( 1198 CXXDefaultArgExpr *E) { 1199 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())-> 1200 getDescribedFunctionTemplate() && 1201 "Default arg expressions are never formed in dependent cases."); 1202 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(), 1203 cast<FunctionDecl>(E->getParam()->getDeclContext()), 1204 E->getParam()); 1205} 1206 1207QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB, 1208 FunctionProtoTypeLoc TL) { 1209 // We need a local instantiation scope for this function prototype. 1210 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); 1211 return inherited::TransformFunctionProtoType(TLB, TL); 1212} 1213 1214ParmVarDecl * 1215TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm, 1216 int indexAdjustment, 1217 llvm::Optional<unsigned> NumExpansions, 1218 bool ExpectParameterPack) { 1219 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment, 1220 NumExpansions, ExpectParameterPack); 1221} 1222 1223QualType 1224TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, 1225 TemplateTypeParmTypeLoc TL) { 1226 const TemplateTypeParmType *T = TL.getTypePtr(); 1227 if (T->getDepth() < TemplateArgs.getNumLevels()) { 1228 // Replace the template type parameter with its corresponding 1229 // template argument. 1230 1231 // If the corresponding template argument is NULL or doesn't exist, it's 1232 // because we are performing instantiation from explicitly-specified 1233 // template arguments in a function template class, but there were some 1234 // arguments left unspecified. 1235 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) { 1236 TemplateTypeParmTypeLoc NewTL 1237 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType()); 1238 NewTL.setNameLoc(TL.getNameLoc()); 1239 return TL.getType(); 1240 } 1241 1242 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex()); 1243 1244 if (T->isParameterPack()) { 1245 assert(Arg.getKind() == TemplateArgument::Pack && 1246 "Missing argument pack"); 1247 1248 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1249 // We have the template argument pack, but we're not expanding the 1250 // enclosing pack expansion yet. Just save the template argument 1251 // pack for later substitution. 1252 QualType Result 1253 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg); 1254 SubstTemplateTypeParmPackTypeLoc NewTL 1255 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result); 1256 NewTL.setNameLoc(TL.getNameLoc()); 1257 return Result; 1258 } 1259 1260 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size()); 1261 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex]; 1262 } 1263 1264 assert(Arg.getKind() == TemplateArgument::Type && 1265 "Template argument kind mismatch"); 1266 1267 QualType Replacement = Arg.getAsType(); 1268 1269 // TODO: only do this uniquing once, at the start of instantiation. 1270 QualType Result 1271 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement); 1272 SubstTemplateTypeParmTypeLoc NewTL 1273 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result); 1274 NewTL.setNameLoc(TL.getNameLoc()); 1275 return Result; 1276 } 1277 1278 // The template type parameter comes from an inner template (e.g., 1279 // the template parameter list of a member template inside the 1280 // template we are instantiating). Create a new template type 1281 // parameter with the template "level" reduced by one. 1282 TemplateTypeParmDecl *NewTTPDecl = 0; 1283 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl()) 1284 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>( 1285 TransformDecl(TL.getNameLoc(), OldTTPDecl)); 1286 1287 QualType Result 1288 = getSema().Context.getTemplateTypeParmType(T->getDepth() 1289 - TemplateArgs.getNumLevels(), 1290 T->getIndex(), 1291 T->isParameterPack(), 1292 NewTTPDecl); 1293 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result); 1294 NewTL.setNameLoc(TL.getNameLoc()); 1295 return Result; 1296} 1297 1298QualType 1299TemplateInstantiator::TransformSubstTemplateTypeParmPackType( 1300 TypeLocBuilder &TLB, 1301 SubstTemplateTypeParmPackTypeLoc TL) { 1302 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1303 // We aren't expanding the parameter pack, so just return ourselves. 1304 SubstTemplateTypeParmPackTypeLoc NewTL 1305 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType()); 1306 NewTL.setNameLoc(TL.getNameLoc()); 1307 return TL.getType(); 1308 } 1309 1310 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack(); 1311 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex; 1312 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range"); 1313 1314 QualType Result = ArgPack.pack_begin()[Index].getAsType(); 1315 Result = getSema().Context.getSubstTemplateTypeParmType( 1316 TL.getTypePtr()->getReplacedParameter(), 1317 Result); 1318 SubstTemplateTypeParmTypeLoc NewTL 1319 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result); 1320 NewTL.setNameLoc(TL.getNameLoc()); 1321 return Result; 1322} 1323 1324/// \brief Perform substitution on the type T with a given set of template 1325/// arguments. 1326/// 1327/// This routine substitutes the given template arguments into the 1328/// type T and produces the instantiated type. 1329/// 1330/// \param T the type into which the template arguments will be 1331/// substituted. If this type is not dependent, it will be returned 1332/// immediately. 1333/// 1334/// \param TemplateArgs the template arguments that will be 1335/// substituted for the top-level template parameters within T. 1336/// 1337/// \param Loc the location in the source code where this substitution 1338/// is being performed. It will typically be the location of the 1339/// declarator (if we're instantiating the type of some declaration) 1340/// or the location of the type in the source code (if, e.g., we're 1341/// instantiating the type of a cast expression). 1342/// 1343/// \param Entity the name of the entity associated with a declaration 1344/// being instantiated (if any). May be empty to indicate that there 1345/// is no such entity (if, e.g., this is a type that occurs as part of 1346/// a cast expression) or that the entity has no name (e.g., an 1347/// unnamed function parameter). 1348/// 1349/// \returns If the instantiation succeeds, the instantiated 1350/// type. Otherwise, produces diagnostics and returns a NULL type. 1351TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, 1352 const MultiLevelTemplateArgumentList &Args, 1353 SourceLocation Loc, 1354 DeclarationName Entity) { 1355 assert(!ActiveTemplateInstantiations.empty() && 1356 "Cannot perform an instantiation without some context on the " 1357 "instantiation stack"); 1358 1359 if (!T->getType()->isInstantiationDependentType() && 1360 !T->getType()->isVariablyModifiedType()) 1361 return T; 1362 1363 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 1364 return Instantiator.TransformType(T); 1365} 1366 1367TypeSourceInfo *Sema::SubstType(TypeLoc TL, 1368 const MultiLevelTemplateArgumentList &Args, 1369 SourceLocation Loc, 1370 DeclarationName Entity) { 1371 assert(!ActiveTemplateInstantiations.empty() && 1372 "Cannot perform an instantiation without some context on the " 1373 "instantiation stack"); 1374 1375 if (TL.getType().isNull()) 1376 return 0; 1377 1378 if (!TL.getType()->isInstantiationDependentType() && 1379 !TL.getType()->isVariablyModifiedType()) { 1380 // FIXME: Make a copy of the TypeLoc data here, so that we can 1381 // return a new TypeSourceInfo. Inefficient! 1382 TypeLocBuilder TLB; 1383 TLB.pushFullCopy(TL); 1384 return TLB.getTypeSourceInfo(Context, TL.getType()); 1385 } 1386 1387 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 1388 TypeLocBuilder TLB; 1389 TLB.reserve(TL.getFullDataSize()); 1390 QualType Result = Instantiator.TransformType(TLB, TL); 1391 if (Result.isNull()) 1392 return 0; 1393 1394 return TLB.getTypeSourceInfo(Context, Result); 1395} 1396 1397/// Deprecated form of the above. 1398QualType Sema::SubstType(QualType T, 1399 const MultiLevelTemplateArgumentList &TemplateArgs, 1400 SourceLocation Loc, DeclarationName Entity) { 1401 assert(!ActiveTemplateInstantiations.empty() && 1402 "Cannot perform an instantiation without some context on the " 1403 "instantiation stack"); 1404 1405 // If T is not a dependent type or a variably-modified type, there 1406 // is nothing to do. 1407 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType()) 1408 return T; 1409 1410 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); 1411 return Instantiator.TransformType(T); 1412} 1413 1414static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) { 1415 if (T->getType()->isInstantiationDependentType() || 1416 T->getType()->isVariablyModifiedType()) 1417 return true; 1418 1419 TypeLoc TL = T->getTypeLoc().IgnoreParens(); 1420 if (!isa<FunctionProtoTypeLoc>(TL)) 1421 return false; 1422 1423 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL); 1424 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) { 1425 ParmVarDecl *P = FP.getArg(I); 1426 1427 // The parameter's type as written might be dependent even if the 1428 // decayed type was not dependent. 1429 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo()) 1430 if (TSInfo->getType()->isInstantiationDependentType()) 1431 return true; 1432 1433 // TODO: currently we always rebuild expressions. When we 1434 // properly get lazier about this, we should use the same 1435 // logic to avoid rebuilding prototypes here. 1436 if (P->hasDefaultArg()) 1437 return true; 1438 } 1439 1440 return false; 1441} 1442 1443/// A form of SubstType intended specifically for instantiating the 1444/// type of a FunctionDecl. Its purpose is solely to force the 1445/// instantiation of default-argument expressions. 1446TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T, 1447 const MultiLevelTemplateArgumentList &Args, 1448 SourceLocation Loc, 1449 DeclarationName Entity) { 1450 assert(!ActiveTemplateInstantiations.empty() && 1451 "Cannot perform an instantiation without some context on the " 1452 "instantiation stack"); 1453 1454 if (!NeedsInstantiationAsFunctionType(T)) 1455 return T; 1456 1457 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 1458 1459 TypeLocBuilder TLB; 1460 1461 TypeLoc TL = T->getTypeLoc(); 1462 TLB.reserve(TL.getFullDataSize()); 1463 1464 QualType Result = Instantiator.TransformType(TLB, TL); 1465 if (Result.isNull()) 1466 return 0; 1467 1468 return TLB.getTypeSourceInfo(Context, Result); 1469} 1470 1471ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, 1472 const MultiLevelTemplateArgumentList &TemplateArgs, 1473 int indexAdjustment, 1474 llvm::Optional<unsigned> NumExpansions, 1475 bool ExpectParameterPack) { 1476 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo(); 1477 TypeSourceInfo *NewDI = 0; 1478 1479 TypeLoc OldTL = OldDI->getTypeLoc(); 1480 if (isa<PackExpansionTypeLoc>(OldTL)) { 1481 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL); 1482 1483 // We have a function parameter pack. Substitute into the pattern of the 1484 // expansion. 1485 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, 1486 OldParm->getLocation(), OldParm->getDeclName()); 1487 if (!NewDI) 1488 return 0; 1489 1490 if (NewDI->getType()->containsUnexpandedParameterPack()) { 1491 // We still have unexpanded parameter packs, which means that 1492 // our function parameter is still a function parameter pack. 1493 // Therefore, make its type a pack expansion type. 1494 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(), 1495 NumExpansions); 1496 } else if (ExpectParameterPack) { 1497 // We expected to get a parameter pack but didn't (because the type 1498 // itself is not a pack expansion type), so complain. This can occur when 1499 // the substitution goes through an alias template that "loses" the 1500 // pack expansion. 1501 Diag(OldParm->getLocation(), 1502 diag::err_function_parameter_pack_without_parameter_packs) 1503 << NewDI->getType(); 1504 return 0; 1505 } 1506 } else { 1507 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), 1508 OldParm->getDeclName()); 1509 } 1510 1511 if (!NewDI) 1512 return 0; 1513 1514 if (NewDI->getType()->isVoidType()) { 1515 Diag(OldParm->getLocation(), diag::err_param_with_void_type); 1516 return 0; 1517 } 1518 1519 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(), 1520 OldParm->getInnerLocStart(), 1521 OldParm->getLocation(), 1522 OldParm->getIdentifier(), 1523 NewDI->getType(), NewDI, 1524 OldParm->getStorageClass(), 1525 OldParm->getStorageClassAsWritten()); 1526 if (!NewParm) 1527 return 0; 1528 1529 // Mark the (new) default argument as uninstantiated (if any). 1530 if (OldParm->hasUninstantiatedDefaultArg()) { 1531 Expr *Arg = OldParm->getUninstantiatedDefaultArg(); 1532 NewParm->setUninstantiatedDefaultArg(Arg); 1533 } else if (OldParm->hasUnparsedDefaultArg()) { 1534 NewParm->setUnparsedDefaultArg(); 1535 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm); 1536 } else if (Expr *Arg = OldParm->getDefaultArg()) 1537 NewParm->setUninstantiatedDefaultArg(Arg); 1538 1539 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); 1540 1541 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) { 1542 // Add the new parameter to the instantiated parameter pack. 1543 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm); 1544 } else { 1545 // Introduce an Old -> New mapping 1546 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); 1547 } 1548 1549 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext 1550 // can be anything, is this right ? 1551 NewParm->setDeclContext(CurContext); 1552 1553 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(), 1554 OldParm->getFunctionScopeIndex() + indexAdjustment); 1555 1556 return NewParm; 1557} 1558 1559/// \brief Substitute the given template arguments into the given set of 1560/// parameters, producing the set of parameter types that would be generated 1561/// from such a substitution. 1562bool Sema::SubstParmTypes(SourceLocation Loc, 1563 ParmVarDecl **Params, unsigned NumParams, 1564 const MultiLevelTemplateArgumentList &TemplateArgs, 1565 SmallVectorImpl<QualType> &ParamTypes, 1566 SmallVectorImpl<ParmVarDecl *> *OutParams) { 1567 assert(!ActiveTemplateInstantiations.empty() && 1568 "Cannot perform an instantiation without some context on the " 1569 "instantiation stack"); 1570 1571 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 1572 DeclarationName()); 1573 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0, 1574 ParamTypes, OutParams); 1575} 1576 1577/// \brief Perform substitution on the base class specifiers of the 1578/// given class template specialization. 1579/// 1580/// Produces a diagnostic and returns true on error, returns false and 1581/// attaches the instantiated base classes to the class template 1582/// specialization if successful. 1583bool 1584Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 1585 CXXRecordDecl *Pattern, 1586 const MultiLevelTemplateArgumentList &TemplateArgs) { 1587 bool Invalid = false; 1588 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; 1589 for (ClassTemplateSpecializationDecl::base_class_iterator 1590 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end(); 1591 Base != BaseEnd; ++Base) { 1592 if (!Base->getType()->isDependentType()) { 1593 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base)); 1594 continue; 1595 } 1596 1597 SourceLocation EllipsisLoc; 1598 TypeSourceInfo *BaseTypeLoc; 1599 if (Base->isPackExpansion()) { 1600 // This is a pack expansion. See whether we should expand it now, or 1601 // wait until later. 1602 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1603 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(), 1604 Unexpanded); 1605 bool ShouldExpand = false; 1606 bool RetainExpansion = false; 1607 llvm::Optional<unsigned> NumExpansions; 1608 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(), 1609 Base->getSourceRange(), 1610 Unexpanded, 1611 TemplateArgs, ShouldExpand, 1612 RetainExpansion, 1613 NumExpansions)) { 1614 Invalid = true; 1615 continue; 1616 } 1617 1618 // If we should expand this pack expansion now, do so. 1619 if (ShouldExpand) { 1620 for (unsigned I = 0; I != *NumExpansions; ++I) { 1621 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 1622 1623 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(), 1624 TemplateArgs, 1625 Base->getSourceRange().getBegin(), 1626 DeclarationName()); 1627 if (!BaseTypeLoc) { 1628 Invalid = true; 1629 continue; 1630 } 1631 1632 if (CXXBaseSpecifier *InstantiatedBase 1633 = CheckBaseSpecifier(Instantiation, 1634 Base->getSourceRange(), 1635 Base->isVirtual(), 1636 Base->getAccessSpecifierAsWritten(), 1637 BaseTypeLoc, 1638 SourceLocation())) 1639 InstantiatedBases.push_back(InstantiatedBase); 1640 else 1641 Invalid = true; 1642 } 1643 1644 continue; 1645 } 1646 1647 // The resulting base specifier will (still) be a pack expansion. 1648 EllipsisLoc = Base->getEllipsisLoc(); 1649 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); 1650 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(), 1651 TemplateArgs, 1652 Base->getSourceRange().getBegin(), 1653 DeclarationName()); 1654 } else { 1655 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(), 1656 TemplateArgs, 1657 Base->getSourceRange().getBegin(), 1658 DeclarationName()); 1659 } 1660 1661 if (!BaseTypeLoc) { 1662 Invalid = true; 1663 continue; 1664 } 1665 1666 if (CXXBaseSpecifier *InstantiatedBase 1667 = CheckBaseSpecifier(Instantiation, 1668 Base->getSourceRange(), 1669 Base->isVirtual(), 1670 Base->getAccessSpecifierAsWritten(), 1671 BaseTypeLoc, 1672 EllipsisLoc)) 1673 InstantiatedBases.push_back(InstantiatedBase); 1674 else 1675 Invalid = true; 1676 } 1677 1678 if (!Invalid && 1679 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(), 1680 InstantiatedBases.size())) 1681 Invalid = true; 1682 1683 return Invalid; 1684} 1685 1686// Defined via #include from SemaTemplateInstantiateDecl.cpp 1687namespace clang { 1688 namespace sema { 1689 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, 1690 const MultiLevelTemplateArgumentList &TemplateArgs); 1691 } 1692} 1693 1694/// Determine whether we would be unable to instantiate this template (because 1695/// it either has no definition, or is in the process of being instantiated). 1696static bool DiagnoseUninstantiableTemplate(Sema &S, 1697 SourceLocation PointOfInstantiation, 1698 TagDecl *Instantiation, 1699 bool InstantiatedFromMember, 1700 TagDecl *Pattern, 1701 TagDecl *PatternDef, 1702 TemplateSpecializationKind TSK, 1703 bool Complain = true) { 1704 if (PatternDef && !PatternDef->isBeingDefined()) 1705 return false; 1706 1707 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) { 1708 // Say nothing 1709 } else if (PatternDef) { 1710 assert(PatternDef->isBeingDefined()); 1711 S.Diag(PointOfInstantiation, 1712 diag::err_template_instantiate_within_definition) 1713 << (TSK != TSK_ImplicitInstantiation) 1714 << S.Context.getTypeDeclType(Instantiation); 1715 // Not much point in noting the template declaration here, since 1716 // we're lexically inside it. 1717 Instantiation->setInvalidDecl(); 1718 } else if (InstantiatedFromMember) { 1719 S.Diag(PointOfInstantiation, 1720 diag::err_implicit_instantiate_member_undefined) 1721 << S.Context.getTypeDeclType(Instantiation); 1722 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here); 1723 } else { 1724 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 1725 << (TSK != TSK_ImplicitInstantiation) 1726 << S.Context.getTypeDeclType(Instantiation); 1727 S.Diag(Pattern->getLocation(), diag::note_template_decl_here); 1728 } 1729 1730 // In general, Instantiation isn't marked invalid to get more than one 1731 // error for multiple undefined instantiations. But the code that does 1732 // explicit declaration -> explicit definition conversion can't handle 1733 // invalid declarations, so mark as invalid in that case. 1734 if (TSK == TSK_ExplicitInstantiationDeclaration) 1735 Instantiation->setInvalidDecl(); 1736 return true; 1737} 1738 1739/// \brief Instantiate the definition of a class from a given pattern. 1740/// 1741/// \param PointOfInstantiation The point of instantiation within the 1742/// source code. 1743/// 1744/// \param Instantiation is the declaration whose definition is being 1745/// instantiated. This will be either a class template specialization 1746/// or a member class of a class template specialization. 1747/// 1748/// \param Pattern is the pattern from which the instantiation 1749/// occurs. This will be either the declaration of a class template or 1750/// the declaration of a member class of a class template. 1751/// 1752/// \param TemplateArgs The template arguments to be substituted into 1753/// the pattern. 1754/// 1755/// \param TSK the kind of implicit or explicit instantiation to perform. 1756/// 1757/// \param Complain whether to complain if the class cannot be instantiated due 1758/// to the lack of a definition. 1759/// 1760/// \returns true if an error occurred, false otherwise. 1761bool 1762Sema::InstantiateClass(SourceLocation PointOfInstantiation, 1763 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 1764 const MultiLevelTemplateArgumentList &TemplateArgs, 1765 TemplateSpecializationKind TSK, 1766 bool Complain) { 1767 bool Invalid = false; 1768 1769 CXXRecordDecl *PatternDef 1770 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 1771 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation, 1772 Instantiation->getInstantiatedFromMemberClass(), 1773 Pattern, PatternDef, TSK, Complain)) 1774 return true; 1775 Pattern = PatternDef; 1776 1777 // \brief Record the point of instantiation. 1778 if (MemberSpecializationInfo *MSInfo 1779 = Instantiation->getMemberSpecializationInfo()) { 1780 MSInfo->setTemplateSpecializationKind(TSK); 1781 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1782 } else if (ClassTemplateSpecializationDecl *Spec 1783 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) { 1784 Spec->setTemplateSpecializationKind(TSK); 1785 Spec->setPointOfInstantiation(PointOfInstantiation); 1786 } 1787 1788 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 1789 if (Inst) 1790 return true; 1791 1792 // Enter the scope of this instantiation. We don't use 1793 // PushDeclContext because we don't have a scope. 1794 ContextRAII SavedContext(*this, Instantiation); 1795 EnterExpressionEvaluationContext EvalContext(*this, 1796 Sema::PotentiallyEvaluated); 1797 1798 // If this is an instantiation of a local class, merge this local 1799 // instantiation scope with the enclosing scope. Otherwise, every 1800 // instantiation of a class has its own local instantiation scope. 1801 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); 1802 LocalInstantiationScope Scope(*this, MergeWithParentScope); 1803 1804 // Pull attributes from the pattern onto the instantiation. 1805 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 1806 1807 // Start the definition of this instantiation. 1808 Instantiation->startDefinition(); 1809 1810 Instantiation->setTagKind(Pattern->getTagKind()); 1811 1812 // Do substitution on the base class specifiers. 1813 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) 1814 Invalid = true; 1815 1816 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 1817 SmallVector<Decl*, 4> Fields; 1818 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4> 1819 FieldsWithMemberInitializers; 1820 // Delay instantiation of late parsed attributes. 1821 LateInstantiatedAttrVec LateAttrs; 1822 Instantiator.enableLateAttributeInstantiation(&LateAttrs); 1823 1824 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(), 1825 MemberEnd = Pattern->decls_end(); 1826 Member != MemberEnd; ++Member) { 1827 // Don't instantiate members not belonging in this semantic context. 1828 // e.g. for: 1829 // @code 1830 // template <int i> class A { 1831 // class B *g; 1832 // }; 1833 // @endcode 1834 // 'class B' has the template as lexical context but semantically it is 1835 // introduced in namespace scope. 1836 if ((*Member)->getDeclContext() != Pattern) 1837 continue; 1838 1839 if ((*Member)->isInvalidDecl()) { 1840 Invalid = true; 1841 continue; 1842 } 1843 1844 Decl *NewMember = Instantiator.Visit(*Member); 1845 if (NewMember) { 1846 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) { 1847 Fields.push_back(Field); 1848 FieldDecl *OldField = cast<FieldDecl>(*Member); 1849 if (OldField->getInClassInitializer()) 1850 FieldsWithMemberInitializers.push_back(std::make_pair(OldField, 1851 Field)); 1852 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) { 1853 // C++11 [temp.inst]p1: The implicit instantiation of a class template 1854 // specialization causes the implicit instantiation of the definitions 1855 // of unscoped member enumerations. 1856 // Record a point of instantiation for this implicit instantiation. 1857 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() && 1858 Enum->isCompleteDefinition()) { 1859 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo(); 1860 assert(MSInfo && "no spec info for member enum specialization"); 1861 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation); 1862 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1863 } 1864 } 1865 1866 if (NewMember->isInvalidDecl()) 1867 Invalid = true; 1868 } else { 1869 // FIXME: Eventually, a NULL return will mean that one of the 1870 // instantiations was a semantic disaster, and we'll want to set Invalid = 1871 // true. For now, we expect to skip some members that we can't yet handle. 1872 } 1873 } 1874 1875 // Finish checking fields. 1876 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields, 1877 SourceLocation(), SourceLocation(), 0); 1878 CheckCompletedCXXClass(Instantiation); 1879 1880 // Attach any in-class member initializers now the class is complete. 1881 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) { 1882 FieldDecl *OldField = FieldsWithMemberInitializers[I].first; 1883 FieldDecl *NewField = FieldsWithMemberInitializers[I].second; 1884 Expr *OldInit = OldField->getInClassInitializer(); 1885 1886 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs, 1887 /*CXXDirectInit=*/false); 1888 if (NewInit.isInvalid()) 1889 NewField->setInvalidDecl(); 1890 else { 1891 Expr *Init = NewInit.take(); 1892 assert(Init && "no-argument initializer in class"); 1893 assert(!isa<ParenListExpr>(Init) && "call-style init in class"); 1894 ActOnCXXInClassMemberInitializer(NewField, 1895 Init->getSourceRange().getBegin(), Init); 1896 } 1897 } 1898 1899 // Instantiate late parsed attributes, and attach them to their decls. 1900 // See Sema::InstantiateAttrs 1901 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(), 1902 E = LateAttrs.end(); I != E; ++I) { 1903 assert(CurrentInstantiationScope == Instantiator.getStartingScope()); 1904 CurrentInstantiationScope = I->Scope; 1905 Attr *NewAttr = 1906 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs); 1907 I->NewDecl->addAttr(NewAttr); 1908 LocalInstantiationScope::deleteScopes(I->Scope, 1909 Instantiator.getStartingScope()); 1910 } 1911 Instantiator.disableLateAttributeInstantiation(); 1912 LateAttrs.clear(); 1913 1914 if (!FieldsWithMemberInitializers.empty()) 1915 ActOnFinishDelayedMemberInitializers(Instantiation); 1916 1917 if (TSK == TSK_ImplicitInstantiation) { 1918 Instantiation->setLocation(Pattern->getLocation()); 1919 Instantiation->setLocStart(Pattern->getInnerLocStart()); 1920 Instantiation->setRBraceLoc(Pattern->getRBraceLoc()); 1921 } 1922 1923 if (Instantiation->isInvalidDecl()) 1924 Invalid = true; 1925 else { 1926 // Instantiate any out-of-line class template partial 1927 // specializations now. 1928 for (TemplateDeclInstantiator::delayed_partial_spec_iterator 1929 P = Instantiator.delayed_partial_spec_begin(), 1930 PEnd = Instantiator.delayed_partial_spec_end(); 1931 P != PEnd; ++P) { 1932 if (!Instantiator.InstantiateClassTemplatePartialSpecialization( 1933 P->first, 1934 P->second)) { 1935 Invalid = true; 1936 break; 1937 } 1938 } 1939 } 1940 1941 // Exit the scope of this instantiation. 1942 SavedContext.pop(); 1943 1944 if (!Invalid) { 1945 Consumer.HandleTagDeclDefinition(Instantiation); 1946 1947 // Always emit the vtable for an explicit instantiation definition 1948 // of a polymorphic class template specialization. 1949 if (TSK == TSK_ExplicitInstantiationDefinition) 1950 MarkVTableUsed(PointOfInstantiation, Instantiation, true); 1951 } 1952 1953 return Invalid; 1954} 1955 1956/// \brief Instantiate the definition of an enum from a given pattern. 1957/// 1958/// \param PointOfInstantiation The point of instantiation within the 1959/// source code. 1960/// \param Instantiation is the declaration whose definition is being 1961/// instantiated. This will be a member enumeration of a class 1962/// temploid specialization, or a local enumeration within a 1963/// function temploid specialization. 1964/// \param Pattern The templated declaration from which the instantiation 1965/// occurs. 1966/// \param TemplateArgs The template arguments to be substituted into 1967/// the pattern. 1968/// \param TSK The kind of implicit or explicit instantiation to perform. 1969/// 1970/// \return \c true if an error occurred, \c false otherwise. 1971bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation, 1972 EnumDecl *Instantiation, EnumDecl *Pattern, 1973 const MultiLevelTemplateArgumentList &TemplateArgs, 1974 TemplateSpecializationKind TSK) { 1975 EnumDecl *PatternDef = Pattern->getDefinition(); 1976 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation, 1977 Instantiation->getInstantiatedFromMemberEnum(), 1978 Pattern, PatternDef, TSK,/*Complain*/true)) 1979 return true; 1980 Pattern = PatternDef; 1981 1982 // Record the point of instantiation. 1983 if (MemberSpecializationInfo *MSInfo 1984 = Instantiation->getMemberSpecializationInfo()) { 1985 MSInfo->setTemplateSpecializationKind(TSK); 1986 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1987 } 1988 1989 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 1990 if (Inst) 1991 return true; 1992 1993 // Enter the scope of this instantiation. We don't use 1994 // PushDeclContext because we don't have a scope. 1995 ContextRAII SavedContext(*this, Instantiation); 1996 EnterExpressionEvaluationContext EvalContext(*this, 1997 Sema::PotentiallyEvaluated); 1998 1999 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true); 2000 2001 // Pull attributes from the pattern onto the instantiation. 2002 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 2003 2004 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 2005 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern); 2006 2007 // Exit the scope of this instantiation. 2008 SavedContext.pop(); 2009 2010 return Instantiation->isInvalidDecl(); 2011} 2012 2013namespace { 2014 /// \brief A partial specialization whose template arguments have matched 2015 /// a given template-id. 2016 struct PartialSpecMatchResult { 2017 ClassTemplatePartialSpecializationDecl *Partial; 2018 TemplateArgumentList *Args; 2019 }; 2020} 2021 2022bool 2023Sema::InstantiateClassTemplateSpecialization( 2024 SourceLocation PointOfInstantiation, 2025 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2026 TemplateSpecializationKind TSK, 2027 bool Complain) { 2028 // Perform the actual instantiation on the canonical declaration. 2029 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 2030 ClassTemplateSpec->getCanonicalDecl()); 2031 2032 // Check whether we have already instantiated or specialized this class 2033 // template specialization. 2034 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) { 2035 if (ClassTemplateSpec->getSpecializationKind() == 2036 TSK_ExplicitInstantiationDeclaration && 2037 TSK == TSK_ExplicitInstantiationDefinition) { 2038 // An explicit instantiation definition follows an explicit instantiation 2039 // declaration (C++0x [temp.explicit]p10); go ahead and perform the 2040 // explicit instantiation. 2041 ClassTemplateSpec->setSpecializationKind(TSK); 2042 2043 // If this is an explicit instantiation definition, mark the 2044 // vtable as used. 2045 if (TSK == TSK_ExplicitInstantiationDefinition && 2046 !ClassTemplateSpec->isInvalidDecl()) 2047 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true); 2048 2049 return false; 2050 } 2051 2052 // We can only instantiate something that hasn't already been 2053 // instantiated or specialized. Fail without any diagnostics: our 2054 // caller will provide an error message. 2055 return true; 2056 } 2057 2058 if (ClassTemplateSpec->isInvalidDecl()) 2059 return true; 2060 2061 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 2062 CXXRecordDecl *Pattern = 0; 2063 2064 // C++ [temp.class.spec.match]p1: 2065 // When a class template is used in a context that requires an 2066 // instantiation of the class, it is necessary to determine 2067 // whether the instantiation is to be generated using the primary 2068 // template or one of the partial specializations. This is done by 2069 // matching the template arguments of the class template 2070 // specialization with the template argument lists of the partial 2071 // specializations. 2072 typedef PartialSpecMatchResult MatchResult; 2073 SmallVector<MatchResult, 4> Matched; 2074 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 2075 Template->getPartialSpecializations(PartialSpecs); 2076 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 2077 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; 2078 TemplateDeductionInfo Info(Context, PointOfInstantiation); 2079 if (TemplateDeductionResult Result 2080 = DeduceTemplateArguments(Partial, 2081 ClassTemplateSpec->getTemplateArgs(), 2082 Info)) { 2083 // FIXME: Store the failed-deduction information for use in 2084 // diagnostics, later. 2085 (void)Result; 2086 } else { 2087 Matched.push_back(PartialSpecMatchResult()); 2088 Matched.back().Partial = Partial; 2089 Matched.back().Args = Info.take(); 2090 } 2091 } 2092 2093 // If we're dealing with a member template where the template parameters 2094 // have been instantiated, this provides the original template parameters 2095 // from which the member template's parameters were instantiated. 2096 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters; 2097 2098 if (Matched.size() >= 1) { 2099 SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); 2100 if (Matched.size() == 1) { 2101 // -- If exactly one matching specialization is found, the 2102 // instantiation is generated from that specialization. 2103 // We don't need to do anything for this. 2104 } else { 2105 // -- If more than one matching specialization is found, the 2106 // partial order rules (14.5.4.2) are used to determine 2107 // whether one of the specializations is more specialized 2108 // than the others. If none of the specializations is more 2109 // specialized than all of the other matching 2110 // specializations, then the use of the class template is 2111 // ambiguous and the program is ill-formed. 2112 for (SmallVector<MatchResult, 4>::iterator P = Best + 1, 2113 PEnd = Matched.end(); 2114 P != PEnd; ++P) { 2115 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, 2116 PointOfInstantiation) 2117 == P->Partial) 2118 Best = P; 2119 } 2120 2121 // Determine if the best partial specialization is more specialized than 2122 // the others. 2123 bool Ambiguous = false; 2124 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 2125 PEnd = Matched.end(); 2126 P != PEnd; ++P) { 2127 if (P != Best && 2128 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, 2129 PointOfInstantiation) 2130 != Best->Partial) { 2131 Ambiguous = true; 2132 break; 2133 } 2134 } 2135 2136 if (Ambiguous) { 2137 // Partial ordering did not produce a clear winner. Complain. 2138 ClassTemplateSpec->setInvalidDecl(); 2139 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) 2140 << ClassTemplateSpec; 2141 2142 // Print the matching partial specializations. 2143 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 2144 PEnd = Matched.end(); 2145 P != PEnd; ++P) 2146 Diag(P->Partial->getLocation(), diag::note_partial_spec_match) 2147 << getTemplateArgumentBindingsText( 2148 P->Partial->getTemplateParameters(), 2149 *P->Args); 2150 2151 return true; 2152 } 2153 } 2154 2155 // Instantiate using the best class template partial specialization. 2156 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial; 2157 while (OrigPartialSpec->getInstantiatedFromMember()) { 2158 // If we've found an explicit specialization of this class template, 2159 // stop here and use that as the pattern. 2160 if (OrigPartialSpec->isMemberSpecialization()) 2161 break; 2162 2163 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember(); 2164 } 2165 2166 Pattern = OrigPartialSpec; 2167 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args); 2168 } else { 2169 // -- If no matches are found, the instantiation is generated 2170 // from the primary template. 2171 ClassTemplateDecl *OrigTemplate = Template; 2172 while (OrigTemplate->getInstantiatedFromMemberTemplate()) { 2173 // If we've found an explicit specialization of this class template, 2174 // stop here and use that as the pattern. 2175 if (OrigTemplate->isMemberSpecialization()) 2176 break; 2177 2178 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate(); 2179 } 2180 2181 Pattern = OrigTemplate->getTemplatedDecl(); 2182 } 2183 2184 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec, 2185 Pattern, 2186 getTemplateInstantiationArgs(ClassTemplateSpec), 2187 TSK, 2188 Complain); 2189 2190 return Result; 2191} 2192 2193/// \brief Instantiates the definitions of all of the member 2194/// of the given class, which is an instantiation of a class template 2195/// or a member class of a template. 2196void 2197Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 2198 CXXRecordDecl *Instantiation, 2199 const MultiLevelTemplateArgumentList &TemplateArgs, 2200 TemplateSpecializationKind TSK) { 2201 for (DeclContext::decl_iterator D = Instantiation->decls_begin(), 2202 DEnd = Instantiation->decls_end(); 2203 D != DEnd; ++D) { 2204 bool SuppressNew = false; 2205 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) { 2206 if (FunctionDecl *Pattern 2207 = Function->getInstantiatedFromMemberFunction()) { 2208 MemberSpecializationInfo *MSInfo 2209 = Function->getMemberSpecializationInfo(); 2210 assert(MSInfo && "No member specialization information?"); 2211 if (MSInfo->getTemplateSpecializationKind() 2212 == TSK_ExplicitSpecialization) 2213 continue; 2214 2215 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2216 Function, 2217 MSInfo->getTemplateSpecializationKind(), 2218 MSInfo->getPointOfInstantiation(), 2219 SuppressNew) || 2220 SuppressNew) 2221 continue; 2222 2223 if (Function->isDefined()) 2224 continue; 2225 2226 if (TSK == TSK_ExplicitInstantiationDefinition) { 2227 // C++0x [temp.explicit]p8: 2228 // An explicit instantiation definition that names a class template 2229 // specialization explicitly instantiates the class template 2230 // specialization and is only an explicit instantiation definition 2231 // of members whose definition is visible at the point of 2232 // instantiation. 2233 if (!Pattern->isDefined()) 2234 continue; 2235 2236 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2237 2238 InstantiateFunctionDefinition(PointOfInstantiation, Function); 2239 } else { 2240 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2241 } 2242 } 2243 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) { 2244 if (Var->isStaticDataMember()) { 2245 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 2246 assert(MSInfo && "No member specialization information?"); 2247 if (MSInfo->getTemplateSpecializationKind() 2248 == TSK_ExplicitSpecialization) 2249 continue; 2250 2251 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2252 Var, 2253 MSInfo->getTemplateSpecializationKind(), 2254 MSInfo->getPointOfInstantiation(), 2255 SuppressNew) || 2256 SuppressNew) 2257 continue; 2258 2259 if (TSK == TSK_ExplicitInstantiationDefinition) { 2260 // C++0x [temp.explicit]p8: 2261 // An explicit instantiation definition that names a class template 2262 // specialization explicitly instantiates the class template 2263 // specialization and is only an explicit instantiation definition 2264 // of members whose definition is visible at the point of 2265 // instantiation. 2266 if (!Var->getInstantiatedFromStaticDataMember() 2267 ->getOutOfLineDefinition()) 2268 continue; 2269 2270 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2271 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var); 2272 } else { 2273 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 2274 } 2275 } 2276 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) { 2277 // Always skip the injected-class-name, along with any 2278 // redeclarations of nested classes, since both would cause us 2279 // to try to instantiate the members of a class twice. 2280 if (Record->isInjectedClassName() || Record->getPreviousDecl()) 2281 continue; 2282 2283 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); 2284 assert(MSInfo && "No member specialization information?"); 2285 2286 if (MSInfo->getTemplateSpecializationKind() 2287 == TSK_ExplicitSpecialization) 2288 continue; 2289 2290 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 2291 Record, 2292 MSInfo->getTemplateSpecializationKind(), 2293 MSInfo->getPointOfInstantiation(), 2294 SuppressNew) || 2295 SuppressNew) 2296 continue; 2297 2298 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 2299 assert(Pattern && "Missing instantiated-from-template information"); 2300 2301 if (!Record->getDefinition()) { 2302 if (!Pattern->getDefinition()) { 2303 // C++0x [temp.explicit]p8: 2304 // An explicit instantiation definition that names a class template 2305 // specialization explicitly instantiates the class template 2306 // specialization and is only an explicit instantiation definition 2307 // of members whose definition is visible at the point of 2308 // instantiation. 2309 if (TSK == TSK_ExplicitInstantiationDeclaration) { 2310 MSInfo->setTemplateSpecializationKind(TSK); 2311 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2312 } 2313 2314 continue; 2315 } 2316 2317 InstantiateClass(PointOfInstantiation, Record, Pattern, 2318 TemplateArgs, 2319 TSK); 2320 } else { 2321 if (TSK == TSK_ExplicitInstantiationDefinition && 2322 Record->getTemplateSpecializationKind() == 2323 TSK_ExplicitInstantiationDeclaration) { 2324 Record->setTemplateSpecializationKind(TSK); 2325 MarkVTableUsed(PointOfInstantiation, Record, true); 2326 } 2327 } 2328 2329 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 2330 if (Pattern) 2331 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, 2332 TSK); 2333 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) { 2334 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); 2335 assert(MSInfo && "No member specialization information?"); 2336 2337 if (MSInfo->getTemplateSpecializationKind() 2338 == TSK_ExplicitSpecialization) 2339 continue; 2340 2341 if (CheckSpecializationInstantiationRedecl( 2342 PointOfInstantiation, TSK, Enum, 2343 MSInfo->getTemplateSpecializationKind(), 2344 MSInfo->getPointOfInstantiation(), SuppressNew) || 2345 SuppressNew) 2346 continue; 2347 2348 if (Enum->getDefinition()) 2349 continue; 2350 2351 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum(); 2352 assert(Pattern && "Missing instantiated-from-template information"); 2353 2354 if (TSK == TSK_ExplicitInstantiationDefinition) { 2355 if (!Pattern->getDefinition()) 2356 continue; 2357 2358 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK); 2359 } else { 2360 MSInfo->setTemplateSpecializationKind(TSK); 2361 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2362 } 2363 } 2364 } 2365} 2366 2367/// \brief Instantiate the definitions of all of the members of the 2368/// given class template specialization, which was named as part of an 2369/// explicit instantiation. 2370void 2371Sema::InstantiateClassTemplateSpecializationMembers( 2372 SourceLocation PointOfInstantiation, 2373 ClassTemplateSpecializationDecl *ClassTemplateSpec, 2374 TemplateSpecializationKind TSK) { 2375 // C++0x [temp.explicit]p7: 2376 // An explicit instantiation that names a class template 2377 // specialization is an explicit instantion of the same kind 2378 // (declaration or definition) of each of its members (not 2379 // including members inherited from base classes) that has not 2380 // been previously explicitly specialized in the translation unit 2381 // containing the explicit instantiation, except as described 2382 // below. 2383 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 2384 getTemplateInstantiationArgs(ClassTemplateSpec), 2385 TSK); 2386} 2387 2388StmtResult 2389Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { 2390 if (!S) 2391 return Owned(S); 2392 2393 TemplateInstantiator Instantiator(*this, TemplateArgs, 2394 SourceLocation(), 2395 DeclarationName()); 2396 return Instantiator.TransformStmt(S); 2397} 2398 2399ExprResult 2400Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 2401 if (!E) 2402 return Owned(E); 2403 2404 TemplateInstantiator Instantiator(*this, TemplateArgs, 2405 SourceLocation(), 2406 DeclarationName()); 2407 return Instantiator.TransformExpr(E); 2408} 2409 2410bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 2411 const MultiLevelTemplateArgumentList &TemplateArgs, 2412 SmallVectorImpl<Expr *> &Outputs) { 2413 if (NumExprs == 0) 2414 return false; 2415 2416 TemplateInstantiator Instantiator(*this, TemplateArgs, 2417 SourceLocation(), 2418 DeclarationName()); 2419 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs); 2420} 2421 2422NestedNameSpecifierLoc 2423Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 2424 const MultiLevelTemplateArgumentList &TemplateArgs) { 2425 if (!NNS) 2426 return NestedNameSpecifierLoc(); 2427 2428 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), 2429 DeclarationName()); 2430 return Instantiator.TransformNestedNameSpecifierLoc(NNS); 2431} 2432 2433/// \brief Do template substitution on declaration name info. 2434DeclarationNameInfo 2435Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 2436 const MultiLevelTemplateArgumentList &TemplateArgs) { 2437 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(), 2438 NameInfo.getName()); 2439 return Instantiator.TransformDeclarationNameInfo(NameInfo); 2440} 2441 2442TemplateName 2443Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, 2444 TemplateName Name, SourceLocation Loc, 2445 const MultiLevelTemplateArgumentList &TemplateArgs) { 2446 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 2447 DeclarationName()); 2448 CXXScopeSpec SS; 2449 SS.Adopt(QualifierLoc); 2450 return Instantiator.TransformTemplateName(SS, Name, Loc); 2451} 2452 2453bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 2454 TemplateArgumentListInfo &Result, 2455 const MultiLevelTemplateArgumentList &TemplateArgs) { 2456 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 2457 DeclarationName()); 2458 2459 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result); 2460} 2461 2462llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * 2463LocalInstantiationScope::findInstantiationOf(const Decl *D) { 2464 for (LocalInstantiationScope *Current = this; Current; 2465 Current = Current->Outer) { 2466 2467 // Check if we found something within this scope. 2468 const Decl *CheckD = D; 2469 do { 2470 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD); 2471 if (Found != Current->LocalDecls.end()) 2472 return &Found->second; 2473 2474 // If this is a tag declaration, it's possible that we need to look for 2475 // a previous declaration. 2476 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD)) 2477 CheckD = Tag->getPreviousDecl(); 2478 else 2479 CheckD = 0; 2480 } while (CheckD); 2481 2482 // If we aren't combined with our outer scope, we're done. 2483 if (!Current->CombineWithOuterScope) 2484 break; 2485 } 2486 2487 // If we didn't find the decl, then we either have a sema bug, or we have a 2488 // forward reference to a label declaration. Return null to indicate that 2489 // we have an uninstantiated label. 2490 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope"); 2491 return 0; 2492} 2493 2494void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) { 2495 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 2496 if (Stored.isNull()) 2497 Stored = Inst; 2498 else if (Stored.is<Decl *>()) { 2499 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local"); 2500 Stored = Inst; 2501 } else 2502 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst); 2503} 2504 2505void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, 2506 Decl *Inst) { 2507 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>(); 2508 Pack->push_back(Inst); 2509} 2510 2511void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { 2512 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 2513 assert(Stored.isNull() && "Already instantiated this local"); 2514 DeclArgumentPack *Pack = new DeclArgumentPack; 2515 Stored = Pack; 2516 ArgumentPacks.push_back(Pack); 2517} 2518 2519void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, 2520 const TemplateArgument *ExplicitArgs, 2521 unsigned NumExplicitArgs) { 2522 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && 2523 "Already have a partially-substituted pack"); 2524 assert((!PartiallySubstitutedPack 2525 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && 2526 "Wrong number of arguments in partially-substituted pack"); 2527 PartiallySubstitutedPack = Pack; 2528 ArgsInPartiallySubstitutedPack = ExplicitArgs; 2529 NumArgsInPartiallySubstitutedPack = NumExplicitArgs; 2530} 2531 2532NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( 2533 const TemplateArgument **ExplicitArgs, 2534 unsigned *NumExplicitArgs) const { 2535 if (ExplicitArgs) 2536 *ExplicitArgs = 0; 2537 if (NumExplicitArgs) 2538 *NumExplicitArgs = 0; 2539 2540 for (const LocalInstantiationScope *Current = this; Current; 2541 Current = Current->Outer) { 2542 if (Current->PartiallySubstitutedPack) { 2543 if (ExplicitArgs) 2544 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; 2545 if (NumExplicitArgs) 2546 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; 2547 2548 return Current->PartiallySubstitutedPack; 2549 } 2550 2551 if (!Current->CombineWithOuterScope) 2552 break; 2553 } 2554 2555 return 0; 2556} 2557