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