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