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