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