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