1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/ 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 //===----------------------------------------------------------------------===/ 7 // 8 // This file implements C++ template instantiation. 9 // 10 //===----------------------------------------------------------------------===/ 11 12 #include "TreeTransform.h" 13 #include "clang/AST/ASTConcept.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/DeclBase.h" 19 #include "clang/AST/DeclTemplate.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprConcepts.h" 22 #include "clang/AST/PrettyDeclStackTrace.h" 23 #include "clang/AST/Type.h" 24 #include "clang/AST/TypeVisitor.h" 25 #include "clang/Basic/LangOptions.h" 26 #include "clang/Basic/Stack.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Sema/DeclSpec.h" 29 #include "clang/Sema/EnterExpressionEvaluationContext.h" 30 #include "clang/Sema/Initialization.h" 31 #include "clang/Sema/Lookup.h" 32 #include "clang/Sema/Sema.h" 33 #include "clang/Sema/SemaConcept.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "clang/Sema/Template.h" 36 #include "clang/Sema/TemplateDeduction.h" 37 #include "clang/Sema/TemplateInstCallback.h" 38 #include "llvm/ADT/StringExtras.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/TimeProfiler.h" 41 #include <optional> 42 43 using namespace clang; 44 using namespace sema; 45 46 //===----------------------------------------------------------------------===/ 47 // Template Instantiation Support 48 //===----------------------------------------------------------------------===/ 49 50 namespace { 51 namespace TemplateInstArgsHelpers { 52 struct Response { 53 const Decl *NextDecl = nullptr; 54 bool IsDone = false; 55 bool ClearRelativeToPrimary = true; 56 static Response Done() { 57 Response R; 58 R.IsDone = true; 59 return R; 60 } 61 static Response ChangeDecl(const Decl *ND) { 62 Response R; 63 R.NextDecl = ND; 64 return R; 65 } 66 static Response ChangeDecl(const DeclContext *Ctx) { 67 Response R; 68 R.NextDecl = Decl::castFromDeclContext(Ctx); 69 return R; 70 } 71 72 static Response UseNextDecl(const Decl *CurDecl) { 73 return ChangeDecl(CurDecl->getDeclContext()); 74 } 75 76 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) { 77 Response R = Response::UseNextDecl(CurDecl); 78 R.ClearRelativeToPrimary = false; 79 return R; 80 } 81 }; 82 // Add template arguments from a variable template instantiation. 83 Response 84 HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec, 85 MultiLevelTemplateArgumentList &Result, 86 bool SkipForSpecialization) { 87 // For a class-scope explicit specialization, there are no template arguments 88 // at this level, but there may be enclosing template arguments. 89 if (VarTemplSpec->isClassScopeExplicitSpecialization()) 90 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec); 91 92 // We're done when we hit an explicit specialization. 93 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization && 94 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec)) 95 return Response::Done(); 96 97 // If this variable template specialization was instantiated from a 98 // specialized member that is a variable template, we're done. 99 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?"); 100 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *> 101 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial(); 102 if (VarTemplatePartialSpecializationDecl *Partial = 103 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 104 if (!SkipForSpecialization) 105 Result.addOuterTemplateArguments( 106 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(), 107 /*Final=*/false); 108 if (Partial->isMemberSpecialization()) 109 return Response::Done(); 110 } else { 111 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>(); 112 if (!SkipForSpecialization) 113 Result.addOuterTemplateArguments( 114 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(), 115 /*Final=*/false); 116 if (Tmpl->isMemberSpecialization()) 117 return Response::Done(); 118 } 119 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec); 120 } 121 122 // If we have a template template parameter with translation unit context, 123 // then we're performing substitution into a default template argument of 124 // this template template parameter before we've constructed the template 125 // that will own this template template parameter. In this case, we 126 // use empty template parameter lists for all of the outer templates 127 // to avoid performing any substitutions. 128 Response 129 HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP, 130 MultiLevelTemplateArgumentList &Result) { 131 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I) 132 Result.addOuterTemplateArguments(std::nullopt); 133 return Response::Done(); 134 } 135 136 Response HandlePartialClassTemplateSpec( 137 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec, 138 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) { 139 if (!SkipForSpecialization) 140 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth()); 141 return Response::Done(); 142 } 143 144 // Add template arguments from a class template instantiation. 145 Response 146 HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec, 147 MultiLevelTemplateArgumentList &Result, 148 bool SkipForSpecialization) { 149 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) { 150 // We're done when we hit an explicit specialization. 151 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization && 152 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec)) 153 return Response::Done(); 154 155 if (!SkipForSpecialization) 156 Result.addOuterTemplateArguments( 157 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec), 158 ClassTemplSpec->getTemplateInstantiationArgs().asArray(), 159 /*Final=*/false); 160 161 // If this class template specialization was instantiated from a 162 // specialized member that is a class template, we're done. 163 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?"); 164 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization()) 165 return Response::Done(); 166 167 // If this was instantiated from a partial template specialization, we need 168 // to get the next level of declaration context from the partial 169 // specialization, as the ClassTemplateSpecializationDecl's 170 // DeclContext/LexicalDeclContext will be for the primary template. 171 if (auto *InstFromPartialTempl = ClassTemplSpec->getSpecializedTemplateOrPartial() 172 .dyn_cast<ClassTemplatePartialSpecializationDecl *>()) 173 return Response::ChangeDecl(InstFromPartialTempl->getLexicalDeclContext()); 174 } 175 return Response::UseNextDecl(ClassTemplSpec); 176 } 177 178 Response HandleFunction(const FunctionDecl *Function, 179 MultiLevelTemplateArgumentList &Result, 180 const FunctionDecl *Pattern, bool RelativeToPrimary, 181 bool ForConstraintInstantiation) { 182 // Add template arguments from a function template specialization. 183 if (!RelativeToPrimary && 184 Function->getTemplateSpecializationKindForInstantiation() == 185 TSK_ExplicitSpecialization) 186 return Response::Done(); 187 188 if (!RelativeToPrimary && 189 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { 190 // This is an implicit instantiation of an explicit specialization. We 191 // don't get any template arguments from this function but might get 192 // some from an enclosing template. 193 return Response::UseNextDecl(Function); 194 } else if (const TemplateArgumentList *TemplateArgs = 195 Function->getTemplateSpecializationArgs()) { 196 // Add the template arguments for this specialization. 197 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function), 198 TemplateArgs->asArray(), 199 /*Final=*/false); 200 201 // If this function was instantiated from a specialized member that is 202 // a function template, we're done. 203 assert(Function->getPrimaryTemplate() && "No function template?"); 204 if (Function->getPrimaryTemplate()->isMemberSpecialization()) 205 return Response::Done(); 206 207 // If this function is a generic lambda specialization, we are done. 208 if (!ForConstraintInstantiation && 209 isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function)) 210 return Response::Done(); 211 212 } else if (Function->getDescribedFunctionTemplate()) { 213 assert( 214 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && 215 "Outer template not instantiated?"); 216 } 217 // If this is a friend or local declaration and it declares an entity at 218 // namespace scope, take arguments from its lexical parent 219 // instead of its semantic parent, unless of course the pattern we're 220 // instantiating actually comes from the file's context! 221 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) && 222 Function->getNonTransparentDeclContext()->isFileContext() && 223 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) { 224 return Response::ChangeDecl(Function->getLexicalDeclContext()); 225 } 226 return Response::UseNextDecl(Function); 227 } 228 229 Response HandleFunctionTemplateDecl(const FunctionTemplateDecl *FTD, 230 MultiLevelTemplateArgumentList &Result) { 231 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) { 232 Result.addOuterTemplateArguments( 233 const_cast<FunctionTemplateDecl *>(FTD), 234 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(), 235 /*Final=*/false); 236 237 NestedNameSpecifier *NNS = FTD->getTemplatedDecl()->getQualifier(); 238 239 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) { 240 if (NNS->isInstantiationDependent()) { 241 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) 242 Result.addOuterTemplateArguments( 243 const_cast<FunctionTemplateDecl *>(FTD), TSTy->template_arguments(), 244 /*Final=*/false); 245 } 246 247 NNS = NNS->getPrefix(); 248 } 249 } 250 251 return Response::ChangeDecl(FTD->getLexicalDeclContext()); 252 } 253 254 Response HandleRecordDecl(const CXXRecordDecl *Rec, 255 MultiLevelTemplateArgumentList &Result, 256 ASTContext &Context, 257 bool ForConstraintInstantiation) { 258 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) { 259 assert( 260 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && 261 "Outer template not instantiated?"); 262 if (ClassTemplate->isMemberSpecialization()) 263 return Response::Done(); 264 if (ForConstraintInstantiation) 265 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec), 266 ClassTemplate->getInjectedTemplateArgs(), 267 /*Final=*/false); 268 } 269 270 if (const MemberSpecializationInfo *MSInfo = 271 Rec->getMemberSpecializationInfo()) 272 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 273 return Response::Done(); 274 275 bool IsFriend = Rec->getFriendObjectKind() || 276 (Rec->getDescribedClassTemplate() && 277 Rec->getDescribedClassTemplate()->getFriendObjectKind()); 278 if (ForConstraintInstantiation && IsFriend && 279 Rec->getNonTransparentDeclContext()->isFileContext()) { 280 return Response::ChangeDecl(Rec->getLexicalDeclContext()); 281 } 282 283 // This is to make sure we pick up the VarTemplateSpecializationDecl that this 284 // lambda is defined inside of. 285 if (Rec->isLambda()) 286 if (const Decl *LCD = Rec->getLambdaContextDecl()) 287 return Response::ChangeDecl(LCD); 288 289 return Response::UseNextDecl(Rec); 290 } 291 292 Response HandleImplicitConceptSpecializationDecl( 293 const ImplicitConceptSpecializationDecl *CSD, 294 MultiLevelTemplateArgumentList &Result) { 295 Result.addOuterTemplateArguments( 296 const_cast<ImplicitConceptSpecializationDecl *>(CSD), 297 CSD->getTemplateArguments(), 298 /*Final=*/false); 299 return Response::UseNextDecl(CSD); 300 } 301 302 Response HandleGenericDeclContext(const Decl *CurDecl) { 303 return Response::UseNextDecl(CurDecl); 304 } 305 } // namespace TemplateInstArgsHelpers 306 } // namespace 307 308 /// Retrieve the template argument list(s) that should be used to 309 /// instantiate the definition of the given declaration. 310 /// 311 /// \param ND the declaration for which we are computing template instantiation 312 /// arguments. 313 /// 314 /// \param DC In the event we don't HAVE a declaration yet, we instead provide 315 /// the decl context where it will be created. In this case, the `Innermost` 316 /// should likely be provided. If ND is non-null, this is ignored. 317 /// 318 /// \param Innermost if non-NULL, specifies a template argument list for the 319 /// template declaration passed as ND. 320 /// 321 /// \param RelativeToPrimary true if we should get the template 322 /// arguments relative to the primary template, even when we're 323 /// dealing with a specialization. This is only relevant for function 324 /// template specializations. 325 /// 326 /// \param Pattern If non-NULL, indicates the pattern from which we will be 327 /// instantiating the definition of the given declaration, \p ND. This is 328 /// used to determine the proper set of template instantiation arguments for 329 /// friend function template specializations. 330 /// 331 /// \param ForConstraintInstantiation when collecting arguments, 332 /// ForConstraintInstantiation indicates we should continue looking when 333 /// encountering a lambda generic call operator, and continue looking for 334 /// arguments on an enclosing class template. 335 336 MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs( 337 const NamedDecl *ND, const DeclContext *DC, bool Final, 338 const TemplateArgumentList *Innermost, bool RelativeToPrimary, 339 const FunctionDecl *Pattern, bool ForConstraintInstantiation, 340 bool SkipForSpecialization) { 341 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided"); 342 // Accumulate the set of template argument lists in this structure. 343 MultiLevelTemplateArgumentList Result; 344 345 using namespace TemplateInstArgsHelpers; 346 const Decl *CurDecl = ND; 347 348 if (!CurDecl) 349 CurDecl = Decl::castFromDeclContext(DC); 350 351 if (Innermost) { 352 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), 353 Innermost->asArray(), Final); 354 // Populate placeholder template arguments for TemplateTemplateParmDecls. 355 // This is essential for the case e.g. 356 // 357 // template <class> concept Concept = false; 358 // template <template <Concept C> class T> void foo(T<int>) 359 // 360 // where parameter C has a depth of 1 but the substituting argument `int` 361 // has a depth of 0. 362 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) 363 HandleDefaultTempArgIntoTempTempParam(TTP, Result); 364 CurDecl = Response::UseNextDecl(CurDecl).NextDecl; 365 } 366 367 while (!CurDecl->isFileContextDecl()) { 368 Response R; 369 if (const auto *VarTemplSpec = 370 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) { 371 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization); 372 } else if (const auto *PartialClassTemplSpec = 373 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) { 374 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result, 375 SkipForSpecialization); 376 } else if (const auto *ClassTemplSpec = 377 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) { 378 R = HandleClassTemplateSpec(ClassTemplSpec, Result, 379 SkipForSpecialization); 380 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) { 381 R = HandleFunction(Function, Result, Pattern, RelativeToPrimary, 382 ForConstraintInstantiation); 383 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) { 384 R = HandleRecordDecl(Rec, Result, Context, ForConstraintInstantiation); 385 } else if (const auto *CSD = 386 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) { 387 R = HandleImplicitConceptSpecializationDecl(CSD, Result); 388 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) { 389 R = HandleFunctionTemplateDecl(FTD, Result); 390 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) { 391 R = Response::ChangeDecl(CTD->getLexicalDeclContext()); 392 } else if (!isa<DeclContext>(CurDecl)) { 393 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl); 394 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) { 395 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result); 396 } 397 } else { 398 R = HandleGenericDeclContext(CurDecl); 399 } 400 401 if (R.IsDone) 402 return Result; 403 if (R.ClearRelativeToPrimary) 404 RelativeToPrimary = false; 405 assert(R.NextDecl); 406 CurDecl = R.NextDecl; 407 } 408 409 return Result; 410 } 411 412 bool Sema::CodeSynthesisContext::isInstantiationRecord() const { 413 switch (Kind) { 414 case TemplateInstantiation: 415 case ExceptionSpecInstantiation: 416 case DefaultTemplateArgumentInstantiation: 417 case DefaultFunctionArgumentInstantiation: 418 case ExplicitTemplateArgumentSubstitution: 419 case DeducedTemplateArgumentSubstitution: 420 case PriorTemplateArgumentSubstitution: 421 case ConstraintsCheck: 422 case NestedRequirementConstraintsCheck: 423 return true; 424 425 case RequirementInstantiation: 426 case RequirementParameterInstantiation: 427 case DefaultTemplateArgumentChecking: 428 case DeclaringSpecialMember: 429 case DeclaringImplicitEqualityComparison: 430 case DefiningSynthesizedFunction: 431 case ExceptionSpecEvaluation: 432 case ConstraintSubstitution: 433 case ParameterMappingSubstitution: 434 case ConstraintNormalization: 435 case RewritingOperatorAsSpaceship: 436 case InitializingStructuredBinding: 437 case MarkingClassDllexported: 438 case BuildingBuiltinDumpStructCall: 439 case LambdaExpressionSubstitution: 440 case BuildingDeductionGuides: 441 return false; 442 443 // This function should never be called when Kind's value is Memoization. 444 case Memoization: 445 break; 446 } 447 448 llvm_unreachable("Invalid SynthesisKind!"); 449 } 450 451 Sema::InstantiatingTemplate::InstantiatingTemplate( 452 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, 453 SourceLocation PointOfInstantiation, SourceRange InstantiationRange, 454 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, 455 sema::TemplateDeductionInfo *DeductionInfo) 456 : SemaRef(SemaRef) { 457 // Don't allow further instantiation if a fatal error and an uncompilable 458 // error have occurred. Any diagnostics we might have raised will not be 459 // visible, and we do not need to construct a correct AST. 460 if (SemaRef.Diags.hasFatalErrorOccurred() && 461 SemaRef.hasUncompilableErrorOccurred()) { 462 Invalid = true; 463 return; 464 } 465 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange); 466 if (!Invalid) { 467 CodeSynthesisContext Inst; 468 Inst.Kind = Kind; 469 Inst.PointOfInstantiation = PointOfInstantiation; 470 Inst.Entity = Entity; 471 Inst.Template = Template; 472 Inst.TemplateArgs = TemplateArgs.data(); 473 Inst.NumTemplateArgs = TemplateArgs.size(); 474 Inst.DeductionInfo = DeductionInfo; 475 Inst.InstantiationRange = InstantiationRange; 476 SemaRef.pushCodeSynthesisContext(Inst); 477 478 AlreadyInstantiating = !Inst.Entity ? false : 479 !SemaRef.InstantiatingSpecializations 480 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind}) 481 .second; 482 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst); 483 } 484 } 485 486 Sema::InstantiatingTemplate::InstantiatingTemplate( 487 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, 488 SourceRange InstantiationRange) 489 : InstantiatingTemplate(SemaRef, 490 CodeSynthesisContext::TemplateInstantiation, 491 PointOfInstantiation, InstantiationRange, Entity) {} 492 493 Sema::InstantiatingTemplate::InstantiatingTemplate( 494 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, 495 ExceptionSpecification, SourceRange InstantiationRange) 496 : InstantiatingTemplate( 497 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation, 498 PointOfInstantiation, InstantiationRange, Entity) {} 499 500 Sema::InstantiatingTemplate::InstantiatingTemplate( 501 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, 502 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, 503 SourceRange InstantiationRange) 504 : InstantiatingTemplate( 505 SemaRef, 506 CodeSynthesisContext::DefaultTemplateArgumentInstantiation, 507 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param), 508 Template, TemplateArgs) {} 509 510 Sema::InstantiatingTemplate::InstantiatingTemplate( 511 Sema &SemaRef, SourceLocation PointOfInstantiation, 512 FunctionTemplateDecl *FunctionTemplate, 513 ArrayRef<TemplateArgument> TemplateArgs, 514 CodeSynthesisContext::SynthesisKind Kind, 515 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) 516 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation, 517 InstantiationRange, FunctionTemplate, nullptr, 518 TemplateArgs, &DeductionInfo) { 519 assert( 520 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || 521 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution); 522 } 523 524 Sema::InstantiatingTemplate::InstantiatingTemplate( 525 Sema &SemaRef, SourceLocation PointOfInstantiation, 526 TemplateDecl *Template, 527 ArrayRef<TemplateArgument> TemplateArgs, 528 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) 529 : InstantiatingTemplate( 530 SemaRef, 531 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, 532 PointOfInstantiation, InstantiationRange, Template, nullptr, 533 TemplateArgs, &DeductionInfo) {} 534 535 Sema::InstantiatingTemplate::InstantiatingTemplate( 536 Sema &SemaRef, SourceLocation PointOfInstantiation, 537 ClassTemplatePartialSpecializationDecl *PartialSpec, 538 ArrayRef<TemplateArgument> TemplateArgs, 539 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) 540 : InstantiatingTemplate( 541 SemaRef, 542 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, 543 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, 544 TemplateArgs, &DeductionInfo) {} 545 546 Sema::InstantiatingTemplate::InstantiatingTemplate( 547 Sema &SemaRef, SourceLocation PointOfInstantiation, 548 VarTemplatePartialSpecializationDecl *PartialSpec, 549 ArrayRef<TemplateArgument> TemplateArgs, 550 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) 551 : InstantiatingTemplate( 552 SemaRef, 553 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, 554 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, 555 TemplateArgs, &DeductionInfo) {} 556 557 Sema::InstantiatingTemplate::InstantiatingTemplate( 558 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, 559 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) 560 : InstantiatingTemplate( 561 SemaRef, 562 CodeSynthesisContext::DefaultFunctionArgumentInstantiation, 563 PointOfInstantiation, InstantiationRange, Param, nullptr, 564 TemplateArgs) {} 565 566 Sema::InstantiatingTemplate::InstantiatingTemplate( 567 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, 568 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, 569 SourceRange InstantiationRange) 570 : InstantiatingTemplate( 571 SemaRef, 572 CodeSynthesisContext::PriorTemplateArgumentSubstitution, 573 PointOfInstantiation, InstantiationRange, Param, Template, 574 TemplateArgs) {} 575 576 Sema::InstantiatingTemplate::InstantiatingTemplate( 577 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, 578 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, 579 SourceRange InstantiationRange) 580 : InstantiatingTemplate( 581 SemaRef, 582 CodeSynthesisContext::PriorTemplateArgumentSubstitution, 583 PointOfInstantiation, InstantiationRange, Param, Template, 584 TemplateArgs) {} 585 586 Sema::InstantiatingTemplate::InstantiatingTemplate( 587 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, 588 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, 589 SourceRange InstantiationRange) 590 : InstantiatingTemplate( 591 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking, 592 PointOfInstantiation, InstantiationRange, Param, Template, 593 TemplateArgs) {} 594 595 Sema::InstantiatingTemplate::InstantiatingTemplate( 596 Sema &SemaRef, SourceLocation PointOfInstantiation, 597 concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, 598 SourceRange InstantiationRange) 599 : InstantiatingTemplate( 600 SemaRef, CodeSynthesisContext::RequirementInstantiation, 601 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, 602 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) { 603 } 604 605 Sema::InstantiatingTemplate::InstantiatingTemplate( 606 Sema &SemaRef, SourceLocation PointOfInstantiation, 607 concepts::NestedRequirement *Req, ConstraintsCheck, 608 SourceRange InstantiationRange) 609 : InstantiatingTemplate( 610 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck, 611 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, 612 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {} 613 614 Sema::InstantiatingTemplate::InstantiatingTemplate( 615 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE, 616 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) 617 : InstantiatingTemplate( 618 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation, 619 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, 620 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) { 621 } 622 623 Sema::InstantiatingTemplate::InstantiatingTemplate( 624 Sema &SemaRef, SourceLocation PointOfInstantiation, 625 ConstraintsCheck, NamedDecl *Template, 626 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) 627 : InstantiatingTemplate( 628 SemaRef, CodeSynthesisContext::ConstraintsCheck, 629 PointOfInstantiation, InstantiationRange, Template, nullptr, 630 TemplateArgs) {} 631 632 Sema::InstantiatingTemplate::InstantiatingTemplate( 633 Sema &SemaRef, SourceLocation PointOfInstantiation, 634 ConstraintSubstitution, NamedDecl *Template, 635 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) 636 : InstantiatingTemplate( 637 SemaRef, CodeSynthesisContext::ConstraintSubstitution, 638 PointOfInstantiation, InstantiationRange, Template, nullptr, 639 {}, &DeductionInfo) {} 640 641 Sema::InstantiatingTemplate::InstantiatingTemplate( 642 Sema &SemaRef, SourceLocation PointOfInstantiation, 643 ConstraintNormalization, NamedDecl *Template, 644 SourceRange InstantiationRange) 645 : InstantiatingTemplate( 646 SemaRef, CodeSynthesisContext::ConstraintNormalization, 647 PointOfInstantiation, InstantiationRange, Template) {} 648 649 Sema::InstantiatingTemplate::InstantiatingTemplate( 650 Sema &SemaRef, SourceLocation PointOfInstantiation, 651 ParameterMappingSubstitution, NamedDecl *Template, 652 SourceRange InstantiationRange) 653 : InstantiatingTemplate( 654 SemaRef, CodeSynthesisContext::ParameterMappingSubstitution, 655 PointOfInstantiation, InstantiationRange, Template) {} 656 657 Sema::InstantiatingTemplate::InstantiatingTemplate( 658 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity, 659 BuildingDeductionGuidesTag, SourceRange InstantiationRange) 660 : InstantiatingTemplate( 661 SemaRef, CodeSynthesisContext::BuildingDeductionGuides, 662 PointOfInstantiation, InstantiationRange, Entity) {} 663 664 665 void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) { 666 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext; 667 InNonInstantiationSFINAEContext = false; 668 669 CodeSynthesisContexts.push_back(Ctx); 670 671 if (!Ctx.isInstantiationRecord()) 672 ++NonInstantiationEntries; 673 674 // Check to see if we're low on stack space. We can't do anything about this 675 // from here, but we can at least warn the user. 676 if (isStackNearlyExhausted()) 677 warnStackExhausted(Ctx.PointOfInstantiation); 678 } 679 680 void Sema::popCodeSynthesisContext() { 681 auto &Active = CodeSynthesisContexts.back(); 682 if (!Active.isInstantiationRecord()) { 683 assert(NonInstantiationEntries > 0); 684 --NonInstantiationEntries; 685 } 686 687 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext; 688 689 // Name lookup no longer looks in this template's defining module. 690 assert(CodeSynthesisContexts.size() >= 691 CodeSynthesisContextLookupModules.size() && 692 "forgot to remove a lookup module for a template instantiation"); 693 if (CodeSynthesisContexts.size() == 694 CodeSynthesisContextLookupModules.size()) { 695 if (Module *M = CodeSynthesisContextLookupModules.back()) 696 LookupModulesCache.erase(M); 697 CodeSynthesisContextLookupModules.pop_back(); 698 } 699 700 // If we've left the code synthesis context for the current context stack, 701 // stop remembering that we've emitted that stack. 702 if (CodeSynthesisContexts.size() == 703 LastEmittedCodeSynthesisContextDepth) 704 LastEmittedCodeSynthesisContextDepth = 0; 705 706 CodeSynthesisContexts.pop_back(); 707 } 708 709 void Sema::InstantiatingTemplate::Clear() { 710 if (!Invalid) { 711 if (!AlreadyInstantiating) { 712 auto &Active = SemaRef.CodeSynthesisContexts.back(); 713 if (Active.Entity) 714 SemaRef.InstantiatingSpecializations.erase( 715 {Active.Entity->getCanonicalDecl(), Active.Kind}); 716 } 717 718 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, 719 SemaRef.CodeSynthesisContexts.back()); 720 721 SemaRef.popCodeSynthesisContext(); 722 Invalid = true; 723 } 724 } 725 726 static std::string convertCallArgsToString(Sema &S, 727 llvm::ArrayRef<const Expr *> Args) { 728 std::string Result; 729 llvm::raw_string_ostream OS(Result); 730 llvm::ListSeparator Comma; 731 for (const Expr *Arg : Args) { 732 OS << Comma; 733 Arg->IgnoreParens()->printPretty(OS, nullptr, 734 S.Context.getPrintingPolicy()); 735 } 736 return Result; 737 } 738 739 bool Sema::InstantiatingTemplate::CheckInstantiationDepth( 740 SourceLocation PointOfInstantiation, 741 SourceRange InstantiationRange) { 742 assert(SemaRef.NonInstantiationEntries <= 743 SemaRef.CodeSynthesisContexts.size()); 744 if ((SemaRef.CodeSynthesisContexts.size() - 745 SemaRef.NonInstantiationEntries) 746 <= SemaRef.getLangOpts().InstantiationDepth) 747 return false; 748 749 SemaRef.Diag(PointOfInstantiation, 750 diag::err_template_recursion_depth_exceeded) 751 << SemaRef.getLangOpts().InstantiationDepth 752 << InstantiationRange; 753 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) 754 << SemaRef.getLangOpts().InstantiationDepth; 755 return true; 756 } 757 758 /// Prints the current instantiation stack through a series of 759 /// notes. 760 void Sema::PrintInstantiationStack() { 761 // Determine which template instantiations to skip, if any. 762 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart; 763 unsigned Limit = Diags.getTemplateBacktraceLimit(); 764 if (Limit && Limit < CodeSynthesisContexts.size()) { 765 SkipStart = Limit / 2 + Limit % 2; 766 SkipEnd = CodeSynthesisContexts.size() - Limit / 2; 767 } 768 769 // FIXME: In all of these cases, we need to show the template arguments 770 unsigned InstantiationIdx = 0; 771 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator 772 Active = CodeSynthesisContexts.rbegin(), 773 ActiveEnd = CodeSynthesisContexts.rend(); 774 Active != ActiveEnd; 775 ++Active, ++InstantiationIdx) { 776 // Skip this instantiation? 777 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) { 778 if (InstantiationIdx == SkipStart) { 779 // Note that we're skipping instantiations. 780 Diags.Report(Active->PointOfInstantiation, 781 diag::note_instantiation_contexts_suppressed) 782 << unsigned(CodeSynthesisContexts.size() - Limit); 783 } 784 continue; 785 } 786 787 switch (Active->Kind) { 788 case CodeSynthesisContext::TemplateInstantiation: { 789 Decl *D = Active->Entity; 790 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 791 unsigned DiagID = diag::note_template_member_class_here; 792 if (isa<ClassTemplateSpecializationDecl>(Record)) 793 DiagID = diag::note_template_class_instantiation_here; 794 Diags.Report(Active->PointOfInstantiation, DiagID) 795 << Record << Active->InstantiationRange; 796 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 797 unsigned DiagID; 798 if (Function->getPrimaryTemplate()) 799 DiagID = diag::note_function_template_spec_here; 800 else 801 DiagID = diag::note_template_member_function_here; 802 Diags.Report(Active->PointOfInstantiation, DiagID) 803 << Function 804 << Active->InstantiationRange; 805 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 806 Diags.Report(Active->PointOfInstantiation, 807 VD->isStaticDataMember()? 808 diag::note_template_static_data_member_def_here 809 : diag::note_template_variable_def_here) 810 << VD 811 << Active->InstantiationRange; 812 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 813 Diags.Report(Active->PointOfInstantiation, 814 diag::note_template_enum_def_here) 815 << ED 816 << Active->InstantiationRange; 817 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 818 Diags.Report(Active->PointOfInstantiation, 819 diag::note_template_nsdmi_here) 820 << FD << Active->InstantiationRange; 821 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) { 822 Diags.Report(Active->PointOfInstantiation, 823 diag::note_template_class_instantiation_here) 824 << CTD << Active->InstantiationRange; 825 } else { 826 Diags.Report(Active->PointOfInstantiation, 827 diag::note_template_type_alias_instantiation_here) 828 << cast<TypeAliasTemplateDecl>(D) 829 << Active->InstantiationRange; 830 } 831 break; 832 } 833 834 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: { 835 TemplateDecl *Template = cast<TemplateDecl>(Active->Template); 836 SmallString<128> TemplateArgsStr; 837 llvm::raw_svector_ostream OS(TemplateArgsStr); 838 Template->printName(OS, getPrintingPolicy()); 839 printTemplateArgumentList(OS, Active->template_arguments(), 840 getPrintingPolicy()); 841 Diags.Report(Active->PointOfInstantiation, 842 diag::note_default_arg_instantiation_here) 843 << OS.str() 844 << Active->InstantiationRange; 845 break; 846 } 847 848 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: { 849 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity); 850 Diags.Report(Active->PointOfInstantiation, 851 diag::note_explicit_template_arg_substitution_here) 852 << FnTmpl 853 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 854 Active->TemplateArgs, 855 Active->NumTemplateArgs) 856 << Active->InstantiationRange; 857 break; 858 } 859 860 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: { 861 if (FunctionTemplateDecl *FnTmpl = 862 dyn_cast<FunctionTemplateDecl>(Active->Entity)) { 863 Diags.Report(Active->PointOfInstantiation, 864 diag::note_function_template_deduction_instantiation_here) 865 << FnTmpl 866 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), 867 Active->TemplateArgs, 868 Active->NumTemplateArgs) 869 << Active->InstantiationRange; 870 } else { 871 bool IsVar = isa<VarTemplateDecl>(Active->Entity) || 872 isa<VarTemplateSpecializationDecl>(Active->Entity); 873 bool IsTemplate = false; 874 TemplateParameterList *Params; 875 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) { 876 IsTemplate = true; 877 Params = D->getTemplateParameters(); 878 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>( 879 Active->Entity)) { 880 Params = D->getTemplateParameters(); 881 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>( 882 Active->Entity)) { 883 Params = D->getTemplateParameters(); 884 } else { 885 llvm_unreachable("unexpected template kind"); 886 } 887 888 Diags.Report(Active->PointOfInstantiation, 889 diag::note_deduced_template_arg_substitution_here) 890 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity) 891 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs, 892 Active->NumTemplateArgs) 893 << Active->InstantiationRange; 894 } 895 break; 896 } 897 898 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: { 899 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity); 900 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); 901 902 SmallString<128> TemplateArgsStr; 903 llvm::raw_svector_ostream OS(TemplateArgsStr); 904 FD->printName(OS, getPrintingPolicy()); 905 printTemplateArgumentList(OS, Active->template_arguments(), 906 getPrintingPolicy()); 907 Diags.Report(Active->PointOfInstantiation, 908 diag::note_default_function_arg_instantiation_here) 909 << OS.str() 910 << Active->InstantiationRange; 911 break; 912 } 913 914 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: { 915 NamedDecl *Parm = cast<NamedDecl>(Active->Entity); 916 std::string Name; 917 if (!Parm->getName().empty()) 918 Name = std::string(" '") + Parm->getName().str() + "'"; 919 920 TemplateParameterList *TemplateParams = nullptr; 921 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template)) 922 TemplateParams = Template->getTemplateParameters(); 923 else 924 TemplateParams = 925 cast<ClassTemplatePartialSpecializationDecl>(Active->Template) 926 ->getTemplateParameters(); 927 Diags.Report(Active->PointOfInstantiation, 928 diag::note_prior_template_arg_substitution) 929 << isa<TemplateTemplateParmDecl>(Parm) 930 << Name 931 << getTemplateArgumentBindingsText(TemplateParams, 932 Active->TemplateArgs, 933 Active->NumTemplateArgs) 934 << Active->InstantiationRange; 935 break; 936 } 937 938 case CodeSynthesisContext::DefaultTemplateArgumentChecking: { 939 TemplateParameterList *TemplateParams = nullptr; 940 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template)) 941 TemplateParams = Template->getTemplateParameters(); 942 else 943 TemplateParams = 944 cast<ClassTemplatePartialSpecializationDecl>(Active->Template) 945 ->getTemplateParameters(); 946 947 Diags.Report(Active->PointOfInstantiation, 948 diag::note_template_default_arg_checking) 949 << getTemplateArgumentBindingsText(TemplateParams, 950 Active->TemplateArgs, 951 Active->NumTemplateArgs) 952 << Active->InstantiationRange; 953 break; 954 } 955 956 case CodeSynthesisContext::ExceptionSpecEvaluation: 957 Diags.Report(Active->PointOfInstantiation, 958 diag::note_evaluating_exception_spec_here) 959 << cast<FunctionDecl>(Active->Entity); 960 break; 961 962 case CodeSynthesisContext::ExceptionSpecInstantiation: 963 Diags.Report(Active->PointOfInstantiation, 964 diag::note_template_exception_spec_instantiation_here) 965 << cast<FunctionDecl>(Active->Entity) 966 << Active->InstantiationRange; 967 break; 968 969 case CodeSynthesisContext::RequirementInstantiation: 970 Diags.Report(Active->PointOfInstantiation, 971 diag::note_template_requirement_instantiation_here) 972 << Active->InstantiationRange; 973 break; 974 case CodeSynthesisContext::RequirementParameterInstantiation: 975 Diags.Report(Active->PointOfInstantiation, 976 diag::note_template_requirement_params_instantiation_here) 977 << Active->InstantiationRange; 978 break; 979 980 case CodeSynthesisContext::NestedRequirementConstraintsCheck: 981 Diags.Report(Active->PointOfInstantiation, 982 diag::note_nested_requirement_here) 983 << Active->InstantiationRange; 984 break; 985 986 case CodeSynthesisContext::DeclaringSpecialMember: 987 Diags.Report(Active->PointOfInstantiation, 988 diag::note_in_declaration_of_implicit_special_member) 989 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember; 990 break; 991 992 case CodeSynthesisContext::DeclaringImplicitEqualityComparison: 993 Diags.Report(Active->Entity->getLocation(), 994 diag::note_in_declaration_of_implicit_equality_comparison); 995 break; 996 997 case CodeSynthesisContext::DefiningSynthesizedFunction: { 998 // FIXME: For synthesized functions that are not defaulted, 999 // produce a note. 1000 auto *FD = dyn_cast<FunctionDecl>(Active->Entity); 1001 DefaultedFunctionKind DFK = 1002 FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind(); 1003 if (DFK.isSpecialMember()) { 1004 auto *MD = cast<CXXMethodDecl>(FD); 1005 Diags.Report(Active->PointOfInstantiation, 1006 diag::note_member_synthesized_at) 1007 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember() 1008 << Context.getTagDeclType(MD->getParent()); 1009 } else if (DFK.isComparison()) { 1010 QualType RecordType = FD->getParamDecl(0) 1011 ->getType() 1012 .getNonReferenceType() 1013 .getUnqualifiedType(); 1014 Diags.Report(Active->PointOfInstantiation, 1015 diag::note_comparison_synthesized_at) 1016 << (int)DFK.asComparison() << RecordType; 1017 } 1018 break; 1019 } 1020 1021 case CodeSynthesisContext::RewritingOperatorAsSpaceship: 1022 Diags.Report(Active->Entity->getLocation(), 1023 diag::note_rewriting_operator_as_spaceship); 1024 break; 1025 1026 case CodeSynthesisContext::InitializingStructuredBinding: 1027 Diags.Report(Active->PointOfInstantiation, 1028 diag::note_in_binding_decl_init) 1029 << cast<BindingDecl>(Active->Entity); 1030 break; 1031 1032 case CodeSynthesisContext::MarkingClassDllexported: 1033 Diags.Report(Active->PointOfInstantiation, 1034 diag::note_due_to_dllexported_class) 1035 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11; 1036 break; 1037 1038 case CodeSynthesisContext::BuildingBuiltinDumpStructCall: 1039 Diags.Report(Active->PointOfInstantiation, 1040 diag::note_building_builtin_dump_struct_call) 1041 << convertCallArgsToString( 1042 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs)); 1043 break; 1044 1045 case CodeSynthesisContext::Memoization: 1046 break; 1047 1048 case CodeSynthesisContext::LambdaExpressionSubstitution: 1049 Diags.Report(Active->PointOfInstantiation, 1050 diag::note_lambda_substitution_here); 1051 break; 1052 case CodeSynthesisContext::ConstraintsCheck: { 1053 unsigned DiagID = 0; 1054 if (!Active->Entity) { 1055 Diags.Report(Active->PointOfInstantiation, 1056 diag::note_nested_requirement_here) 1057 << Active->InstantiationRange; 1058 break; 1059 } 1060 if (isa<ConceptDecl>(Active->Entity)) 1061 DiagID = diag::note_concept_specialization_here; 1062 else if (isa<TemplateDecl>(Active->Entity)) 1063 DiagID = diag::note_checking_constraints_for_template_id_here; 1064 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity)) 1065 DiagID = diag::note_checking_constraints_for_var_spec_id_here; 1066 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity)) 1067 DiagID = diag::note_checking_constraints_for_class_spec_id_here; 1068 else { 1069 assert(isa<FunctionDecl>(Active->Entity)); 1070 DiagID = diag::note_checking_constraints_for_function_here; 1071 } 1072 SmallString<128> TemplateArgsStr; 1073 llvm::raw_svector_ostream OS(TemplateArgsStr); 1074 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy()); 1075 if (!isa<FunctionDecl>(Active->Entity)) { 1076 printTemplateArgumentList(OS, Active->template_arguments(), 1077 getPrintingPolicy()); 1078 } 1079 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str() 1080 << Active->InstantiationRange; 1081 break; 1082 } 1083 case CodeSynthesisContext::ConstraintSubstitution: 1084 Diags.Report(Active->PointOfInstantiation, 1085 diag::note_constraint_substitution_here) 1086 << Active->InstantiationRange; 1087 break; 1088 case CodeSynthesisContext::ConstraintNormalization: 1089 Diags.Report(Active->PointOfInstantiation, 1090 diag::note_constraint_normalization_here) 1091 << cast<NamedDecl>(Active->Entity)->getName() 1092 << Active->InstantiationRange; 1093 break; 1094 case CodeSynthesisContext::ParameterMappingSubstitution: 1095 Diags.Report(Active->PointOfInstantiation, 1096 diag::note_parameter_mapping_substitution_here) 1097 << Active->InstantiationRange; 1098 break; 1099 case CodeSynthesisContext::BuildingDeductionGuides: 1100 Diags.Report(Active->PointOfInstantiation, 1101 diag::note_building_deduction_guide_here); 1102 break; 1103 } 1104 } 1105 } 1106 1107 std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { 1108 if (InNonInstantiationSFINAEContext) 1109 return std::optional<TemplateDeductionInfo *>(nullptr); 1110 1111 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator 1112 Active = CodeSynthesisContexts.rbegin(), 1113 ActiveEnd = CodeSynthesisContexts.rend(); 1114 Active != ActiveEnd; 1115 ++Active) 1116 { 1117 switch (Active->Kind) { 1118 case CodeSynthesisContext::TemplateInstantiation: 1119 // An instantiation of an alias template may or may not be a SFINAE 1120 // context, depending on what else is on the stack. 1121 if (isa<TypeAliasTemplateDecl>(Active->Entity)) 1122 break; 1123 [[fallthrough]]; 1124 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: 1125 case CodeSynthesisContext::ExceptionSpecInstantiation: 1126 case CodeSynthesisContext::ConstraintsCheck: 1127 case CodeSynthesisContext::ParameterMappingSubstitution: 1128 case CodeSynthesisContext::ConstraintNormalization: 1129 case CodeSynthesisContext::NestedRequirementConstraintsCheck: 1130 // This is a template instantiation, so there is no SFINAE. 1131 return std::nullopt; 1132 case CodeSynthesisContext::LambdaExpressionSubstitution: 1133 // [temp.deduct]p9 1134 // A lambda-expression appearing in a function type or a template 1135 // parameter is not considered part of the immediate context for the 1136 // purposes of template argument deduction. 1137 // CWG2672: A lambda-expression body is never in the immediate context. 1138 return std::nullopt; 1139 1140 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: 1141 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: 1142 case CodeSynthesisContext::DefaultTemplateArgumentChecking: 1143 case CodeSynthesisContext::RewritingOperatorAsSpaceship: 1144 // A default template argument instantiation and substitution into 1145 // template parameters with arguments for prior parameters may or may 1146 // not be a SFINAE context; look further up the stack. 1147 break; 1148 1149 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: 1150 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: 1151 // We're either substituting explicitly-specified template arguments, 1152 // deduced template arguments. SFINAE applies unless we are in a lambda 1153 // body, see [temp.deduct]p9. 1154 case CodeSynthesisContext::ConstraintSubstitution: 1155 case CodeSynthesisContext::RequirementInstantiation: 1156 case CodeSynthesisContext::RequirementParameterInstantiation: 1157 // SFINAE always applies in a constraint expression or a requirement 1158 // in a requires expression. 1159 assert(Active->DeductionInfo && "Missing deduction info pointer"); 1160 return Active->DeductionInfo; 1161 1162 case CodeSynthesisContext::DeclaringSpecialMember: 1163 case CodeSynthesisContext::DeclaringImplicitEqualityComparison: 1164 case CodeSynthesisContext::DefiningSynthesizedFunction: 1165 case CodeSynthesisContext::InitializingStructuredBinding: 1166 case CodeSynthesisContext::MarkingClassDllexported: 1167 case CodeSynthesisContext::BuildingBuiltinDumpStructCall: 1168 case CodeSynthesisContext::BuildingDeductionGuides: 1169 // This happens in a context unrelated to template instantiation, so 1170 // there is no SFINAE. 1171 return std::nullopt; 1172 1173 case CodeSynthesisContext::ExceptionSpecEvaluation: 1174 // FIXME: This should not be treated as a SFINAE context, because 1175 // we will cache an incorrect exception specification. However, clang 1176 // bootstrap relies this! See PR31692. 1177 break; 1178 1179 case CodeSynthesisContext::Memoization: 1180 break; 1181 } 1182 1183 // The inner context was transparent for SFINAE. If it occurred within a 1184 // non-instantiation SFINAE context, then SFINAE applies. 1185 if (Active->SavedInNonInstantiationSFINAEContext) 1186 return std::optional<TemplateDeductionInfo *>(nullptr); 1187 } 1188 1189 return std::nullopt; 1190 } 1191 1192 //===----------------------------------------------------------------------===/ 1193 // Template Instantiation for Types 1194 //===----------------------------------------------------------------------===/ 1195 namespace { 1196 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> { 1197 const MultiLevelTemplateArgumentList &TemplateArgs; 1198 SourceLocation Loc; 1199 DeclarationName Entity; 1200 // Whether to evaluate the C++20 constraints or simply substitute into them. 1201 bool EvaluateConstraints = true; 1202 1203 public: 1204 typedef TreeTransform<TemplateInstantiator> inherited; 1205 1206 TemplateInstantiator(Sema &SemaRef, 1207 const MultiLevelTemplateArgumentList &TemplateArgs, 1208 SourceLocation Loc, DeclarationName Entity) 1209 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), 1210 Entity(Entity) {} 1211 1212 void setEvaluateConstraints(bool B) { 1213 EvaluateConstraints = B; 1214 } 1215 bool getEvaluateConstraints() { 1216 return EvaluateConstraints; 1217 } 1218 1219 /// Determine whether the given type \p T has already been 1220 /// transformed. 1221 /// 1222 /// For the purposes of template instantiation, a type has already been 1223 /// transformed if it is NULL or if it is not dependent. 1224 bool AlreadyTransformed(QualType T); 1225 1226 /// Returns the location of the entity being instantiated, if known. 1227 SourceLocation getBaseLocation() { return Loc; } 1228 1229 /// Returns the name of the entity being instantiated, if any. 1230 DeclarationName getBaseEntity() { return Entity; } 1231 1232 /// Sets the "base" location and entity when that 1233 /// information is known based on another transformation. 1234 void setBase(SourceLocation Loc, DeclarationName Entity) { 1235 this->Loc = Loc; 1236 this->Entity = Entity; 1237 } 1238 1239 unsigned TransformTemplateDepth(unsigned Depth) { 1240 return TemplateArgs.getNewDepth(Depth); 1241 } 1242 1243 std::optional<unsigned> getPackIndex(TemplateArgument Pack) { 1244 int Index = getSema().ArgumentPackSubstitutionIndex; 1245 if (Index == -1) 1246 return std::nullopt; 1247 return Pack.pack_size() - 1 - Index; 1248 } 1249 1250 bool TryExpandParameterPacks(SourceLocation EllipsisLoc, 1251 SourceRange PatternRange, 1252 ArrayRef<UnexpandedParameterPack> Unexpanded, 1253 bool &ShouldExpand, bool &RetainExpansion, 1254 std::optional<unsigned> &NumExpansions) { 1255 return getSema().CheckParameterPacksForExpansion(EllipsisLoc, 1256 PatternRange, Unexpanded, 1257 TemplateArgs, 1258 ShouldExpand, 1259 RetainExpansion, 1260 NumExpansions); 1261 } 1262 1263 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { 1264 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack); 1265 } 1266 1267 TemplateArgument ForgetPartiallySubstitutedPack() { 1268 TemplateArgument Result; 1269 if (NamedDecl *PartialPack 1270 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ 1271 MultiLevelTemplateArgumentList &TemplateArgs 1272 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); 1273 unsigned Depth, Index; 1274 std::tie(Depth, Index) = getDepthAndIndex(PartialPack); 1275 if (TemplateArgs.hasTemplateArgument(Depth, Index)) { 1276 Result = TemplateArgs(Depth, Index); 1277 TemplateArgs.setArgument(Depth, Index, TemplateArgument()); 1278 } 1279 } 1280 1281 return Result; 1282 } 1283 1284 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { 1285 if (Arg.isNull()) 1286 return; 1287 1288 if (NamedDecl *PartialPack 1289 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ 1290 MultiLevelTemplateArgumentList &TemplateArgs 1291 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); 1292 unsigned Depth, Index; 1293 std::tie(Depth, Index) = getDepthAndIndex(PartialPack); 1294 TemplateArgs.setArgument(Depth, Index, Arg); 1295 } 1296 } 1297 1298 /// Transform the given declaration by instantiating a reference to 1299 /// this declaration. 1300 Decl *TransformDecl(SourceLocation Loc, Decl *D); 1301 1302 void transformAttrs(Decl *Old, Decl *New) { 1303 SemaRef.InstantiateAttrs(TemplateArgs, Old, New); 1304 } 1305 1306 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) { 1307 if (Old->isParameterPack()) { 1308 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old); 1309 for (auto *New : NewDecls) 1310 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg( 1311 Old, cast<VarDecl>(New)); 1312 return; 1313 } 1314 1315 assert(NewDecls.size() == 1 && 1316 "should only have multiple expansions for a pack"); 1317 Decl *New = NewDecls.front(); 1318 1319 // If we've instantiated the call operator of a lambda or the call 1320 // operator template of a generic lambda, update the "instantiation of" 1321 // information. 1322 auto *NewMD = dyn_cast<CXXMethodDecl>(New); 1323 if (NewMD && isLambdaCallOperator(NewMD)) { 1324 auto *OldMD = dyn_cast<CXXMethodDecl>(Old); 1325 if (auto *NewTD = NewMD->getDescribedFunctionTemplate()) 1326 NewTD->setInstantiatedFromMemberTemplate( 1327 OldMD->getDescribedFunctionTemplate()); 1328 else 1329 NewMD->setInstantiationOfMemberFunction(OldMD, 1330 TSK_ImplicitInstantiation); 1331 } 1332 1333 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New); 1334 1335 // We recreated a local declaration, but not by instantiating it. There 1336 // may be pending dependent diagnostics to produce. 1337 if (auto *DC = dyn_cast<DeclContext>(Old); 1338 DC && DC->isDependentContext() && DC->isFunctionOrMethod()) 1339 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs); 1340 } 1341 1342 /// Transform the definition of the given declaration by 1343 /// instantiating it. 1344 Decl *TransformDefinition(SourceLocation Loc, Decl *D); 1345 1346 /// Transform the first qualifier within a scope by instantiating the 1347 /// declaration. 1348 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); 1349 1350 bool TransformExceptionSpec(SourceLocation Loc, 1351 FunctionProtoType::ExceptionSpecInfo &ESI, 1352 SmallVectorImpl<QualType> &Exceptions, 1353 bool &Changed); 1354 1355 /// Rebuild the exception declaration and register the declaration 1356 /// as an instantiated local. 1357 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, 1358 TypeSourceInfo *Declarator, 1359 SourceLocation StartLoc, 1360 SourceLocation NameLoc, 1361 IdentifierInfo *Name); 1362 1363 /// Rebuild the Objective-C exception declaration and register the 1364 /// declaration as an instantiated local. 1365 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 1366 TypeSourceInfo *TSInfo, QualType T); 1367 1368 /// Check for tag mismatches when instantiating an 1369 /// elaborated type. 1370 QualType RebuildElaboratedType(SourceLocation KeywordLoc, 1371 ElaboratedTypeKeyword Keyword, 1372 NestedNameSpecifierLoc QualifierLoc, 1373 QualType T); 1374 1375 TemplateName 1376 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name, 1377 SourceLocation NameLoc, 1378 QualType ObjectType = QualType(), 1379 NamedDecl *FirstQualifierInScope = nullptr, 1380 bool AllowInjectedClassName = false); 1381 1382 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH); 1383 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS, 1384 const Stmt *InstS, 1385 const NoInlineAttr *A); 1386 const AlwaysInlineAttr * 1387 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS, 1388 const AlwaysInlineAttr *A); 1389 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA); 1390 ExprResult TransformPredefinedExpr(PredefinedExpr *E); 1391 ExprResult TransformDeclRefExpr(DeclRefExpr *E); 1392 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E); 1393 1394 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E, 1395 NonTypeTemplateParmDecl *D); 1396 ExprResult TransformSubstNonTypeTemplateParmPackExpr( 1397 SubstNonTypeTemplateParmPackExpr *E); 1398 ExprResult TransformSubstNonTypeTemplateParmExpr( 1399 SubstNonTypeTemplateParmExpr *E); 1400 1401 /// Rebuild a DeclRefExpr for a VarDecl reference. 1402 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc); 1403 1404 /// Transform a reference to a function or init-capture parameter pack. 1405 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD); 1406 1407 /// Transform a FunctionParmPackExpr which was built when we couldn't 1408 /// expand a function parameter pack reference which refers to an expanded 1409 /// pack. 1410 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E); 1411 1412 QualType TransformFunctionProtoType(TypeLocBuilder &TLB, 1413 FunctionProtoTypeLoc TL) { 1414 // Call the base version; it will forward to our overridden version below. 1415 return inherited::TransformFunctionProtoType(TLB, TL); 1416 } 1417 1418 template<typename Fn> 1419 QualType TransformFunctionProtoType(TypeLocBuilder &TLB, 1420 FunctionProtoTypeLoc TL, 1421 CXXRecordDecl *ThisContext, 1422 Qualifiers ThisTypeQuals, 1423 Fn TransformExceptionSpec); 1424 1425 ParmVarDecl * 1426 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment, 1427 std::optional<unsigned> NumExpansions, 1428 bool ExpectParameterPack); 1429 1430 using inherited::TransformTemplateTypeParmType; 1431 /// Transforms a template type parameter type by performing 1432 /// substitution of the corresponding template type argument. 1433 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, 1434 TemplateTypeParmTypeLoc TL, 1435 bool SuppressObjCLifetime); 1436 1437 QualType BuildSubstTemplateTypeParmType( 1438 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, 1439 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex, 1440 TemplateArgument Arg, SourceLocation NameLoc); 1441 1442 /// Transforms an already-substituted template type parameter pack 1443 /// into either itself (if we aren't substituting into its pack expansion) 1444 /// or the appropriate substituted argument. 1445 using inherited::TransformSubstTemplateTypeParmPackType; 1446 QualType 1447 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB, 1448 SubstTemplateTypeParmPackTypeLoc TL, 1449 bool SuppressObjCLifetime); 1450 1451 ExprResult TransformLambdaExpr(LambdaExpr *E) { 1452 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); 1453 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this); 1454 1455 ExprResult Result = inherited::TransformLambdaExpr(E); 1456 if (Result.isInvalid()) 1457 return Result; 1458 1459 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator(); 1460 for (ParmVarDecl *PVD : MD->parameters()) { 1461 assert(PVD && "null in a parameter list"); 1462 if (!PVD->hasDefaultArg()) 1463 continue; 1464 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg(); 1465 // FIXME: Obtain the source location for the '=' token. 1466 SourceLocation EqualLoc = UninstExpr->getBeginLoc(); 1467 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) { 1468 // If substitution fails, the default argument is set to a 1469 // RecoveryExpr that wraps the uninstantiated default argument so 1470 // that downstream diagnostics are omitted. 1471 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr( 1472 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), 1473 { UninstExpr }, UninstExpr->getType()); 1474 if (ErrorResult.isUsable()) 1475 PVD->setDefaultArg(ErrorResult.get()); 1476 } 1477 } 1478 1479 return Result; 1480 } 1481 1482 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 1483 // Currently, we instantiate the body when instantiating the lambda 1484 // expression. However, `EvaluateConstraints` is disabled during the 1485 // instantiation of the lambda expression, causing the instantiation 1486 // failure of the return type requirement in the body. If p0588r1 is fully 1487 // implemented, the body will be lazily instantiated, and this problem 1488 // will not occur. Here, `EvaluateConstraints` is temporarily set to 1489 // `true` to temporarily fix this issue. 1490 // FIXME: This temporary fix can be removed after fully implementing 1491 // p0588r1. 1492 bool Prev = EvaluateConstraints; 1493 EvaluateConstraints = true; 1494 StmtResult Stmt = inherited::TransformLambdaBody(E, Body); 1495 EvaluateConstraints = Prev; 1496 return Stmt; 1497 } 1498 1499 ExprResult TransformRequiresExpr(RequiresExpr *E) { 1500 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); 1501 ExprResult TransReq = inherited::TransformRequiresExpr(E); 1502 if (TransReq.isInvalid()) 1503 return TransReq; 1504 assert(TransReq.get() != E && 1505 "Do not change value of isSatisfied for the existing expression. " 1506 "Create a new expression instead."); 1507 if (E->getBody()->isDependentContext()) { 1508 Sema::SFINAETrap Trap(SemaRef); 1509 // We recreate the RequiresExpr body, but not by instantiating it. 1510 // Produce pending diagnostics for dependent access check. 1511 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs); 1512 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis. 1513 if (Trap.hasErrorOccurred()) 1514 TransReq.getAs<RequiresExpr>()->setSatisfied(false); 1515 } 1516 return TransReq; 1517 } 1518 1519 bool TransformRequiresExprRequirements( 1520 ArrayRef<concepts::Requirement *> Reqs, 1521 SmallVectorImpl<concepts::Requirement *> &Transformed) { 1522 bool SatisfactionDetermined = false; 1523 for (concepts::Requirement *Req : Reqs) { 1524 concepts::Requirement *TransReq = nullptr; 1525 if (!SatisfactionDetermined) { 1526 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req)) 1527 TransReq = TransformTypeRequirement(TypeReq); 1528 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req)) 1529 TransReq = TransformExprRequirement(ExprReq); 1530 else 1531 TransReq = TransformNestedRequirement( 1532 cast<concepts::NestedRequirement>(Req)); 1533 if (!TransReq) 1534 return true; 1535 if (!TransReq->isDependent() && !TransReq->isSatisfied()) 1536 // [expr.prim.req]p6 1537 // [...] The substitution and semantic constraint checking 1538 // proceeds in lexical order and stops when a condition that 1539 // determines the result of the requires-expression is 1540 // encountered. [..] 1541 SatisfactionDetermined = true; 1542 } else 1543 TransReq = Req; 1544 Transformed.push_back(TransReq); 1545 } 1546 return false; 1547 } 1548 1549 TemplateParameterList *TransformTemplateParameterList( 1550 TemplateParameterList *OrigTPL) { 1551 if (!OrigTPL || !OrigTPL->size()) return OrigTPL; 1552 1553 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext(); 1554 TemplateDeclInstantiator DeclInstantiator(getSema(), 1555 /* DeclContext *Owner */ Owner, TemplateArgs); 1556 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints); 1557 return DeclInstantiator.SubstTemplateParams(OrigTPL); 1558 } 1559 1560 concepts::TypeRequirement * 1561 TransformTypeRequirement(concepts::TypeRequirement *Req); 1562 concepts::ExprRequirement * 1563 TransformExprRequirement(concepts::ExprRequirement *Req); 1564 concepts::NestedRequirement * 1565 TransformNestedRequirement(concepts::NestedRequirement *Req); 1566 ExprResult TransformRequiresTypeParams( 1567 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE, 1568 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params, 1569 SmallVectorImpl<QualType> &PTypes, 1570 SmallVectorImpl<ParmVarDecl *> &TransParams, 1571 Sema::ExtParameterInfoBuilder &PInfos); 1572 1573 private: 1574 ExprResult 1575 transformNonTypeTemplateParmRef(Decl *AssociatedDecl, 1576 const NonTypeTemplateParmDecl *parm, 1577 SourceLocation loc, TemplateArgument arg, 1578 std::optional<unsigned> PackIndex); 1579 }; 1580 } 1581 1582 bool TemplateInstantiator::AlreadyTransformed(QualType T) { 1583 if (T.isNull()) 1584 return true; 1585 1586 if (T->isInstantiationDependentType() || T->isVariablyModifiedType()) 1587 return false; 1588 1589 getSema().MarkDeclarationsReferencedInType(Loc, T); 1590 return true; 1591 } 1592 1593 static TemplateArgument 1594 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) { 1595 assert(S.ArgumentPackSubstitutionIndex >= 0); 1596 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()); 1597 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex]; 1598 if (Arg.isPackExpansion()) 1599 Arg = Arg.getPackExpansionPattern(); 1600 return Arg; 1601 } 1602 1603 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { 1604 if (!D) 1605 return nullptr; 1606 1607 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) { 1608 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 1609 // If the corresponding template argument is NULL or non-existent, it's 1610 // because we are performing instantiation from explicitly-specified 1611 // template arguments in a function template, but there were some 1612 // arguments left unspecified. 1613 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), 1614 TTP->getPosition())) 1615 return D; 1616 1617 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); 1618 1619 if (TTP->isParameterPack()) { 1620 assert(Arg.getKind() == TemplateArgument::Pack && 1621 "Missing argument pack"); 1622 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1623 } 1624 1625 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute(); 1626 assert(!Template.isNull() && Template.getAsTemplateDecl() && 1627 "Wrong kind of template template argument"); 1628 return Template.getAsTemplateDecl(); 1629 } 1630 1631 // Fall through to find the instantiated declaration for this template 1632 // template parameter. 1633 } 1634 1635 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs); 1636 } 1637 1638 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { 1639 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs); 1640 if (!Inst) 1641 return nullptr; 1642 1643 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1644 return Inst; 1645 } 1646 1647 bool TemplateInstantiator::TransformExceptionSpec( 1648 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, 1649 SmallVectorImpl<QualType> &Exceptions, bool &Changed) { 1650 if (ESI.Type == EST_Uninstantiated) { 1651 ESI.instantiate(); 1652 Changed = true; 1653 } 1654 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed); 1655 } 1656 1657 NamedDecl * 1658 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, 1659 SourceLocation Loc) { 1660 // If the first part of the nested-name-specifier was a template type 1661 // parameter, instantiate that type parameter down to a tag type. 1662 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) { 1663 const TemplateTypeParmType *TTP 1664 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD)); 1665 1666 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 1667 // FIXME: This needs testing w/ member access expressions. 1668 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex()); 1669 1670 if (TTP->isParameterPack()) { 1671 assert(Arg.getKind() == TemplateArgument::Pack && 1672 "Missing argument pack"); 1673 1674 if (getSema().ArgumentPackSubstitutionIndex == -1) 1675 return nullptr; 1676 1677 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1678 } 1679 1680 QualType T = Arg.getAsType(); 1681 if (T.isNull()) 1682 return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); 1683 1684 if (const TagType *Tag = T->getAs<TagType>()) 1685 return Tag->getDecl(); 1686 1687 // The resulting type is not a tag; complain. 1688 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T; 1689 return nullptr; 1690 } 1691 } 1692 1693 return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); 1694 } 1695 1696 VarDecl * 1697 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, 1698 TypeSourceInfo *Declarator, 1699 SourceLocation StartLoc, 1700 SourceLocation NameLoc, 1701 IdentifierInfo *Name) { 1702 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator, 1703 StartLoc, NameLoc, Name); 1704 if (Var) 1705 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); 1706 return Var; 1707 } 1708 1709 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, 1710 TypeSourceInfo *TSInfo, 1711 QualType T) { 1712 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T); 1713 if (Var) 1714 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); 1715 return Var; 1716 } 1717 1718 QualType 1719 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc, 1720 ElaboratedTypeKeyword Keyword, 1721 NestedNameSpecifierLoc QualifierLoc, 1722 QualType T) { 1723 if (const TagType *TT = T->getAs<TagType>()) { 1724 TagDecl* TD = TT->getDecl(); 1725 1726 SourceLocation TagLocation = KeywordLoc; 1727 1728 IdentifierInfo *Id = TD->getIdentifier(); 1729 1730 // TODO: should we even warn on struct/class mismatches for this? Seems 1731 // like it's likely to produce a lot of spurious errors. 1732 if (Id && Keyword != ElaboratedTypeKeyword::None && 1733 Keyword != ElaboratedTypeKeyword::Typename) { 1734 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword); 1735 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false, 1736 TagLocation, Id)) { 1737 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag) 1738 << Id 1739 << FixItHint::CreateReplacement(SourceRange(TagLocation), 1740 TD->getKindName()); 1741 SemaRef.Diag(TD->getLocation(), diag::note_previous_use); 1742 } 1743 } 1744 } 1745 1746 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T); 1747 } 1748 1749 TemplateName TemplateInstantiator::TransformTemplateName( 1750 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc, 1751 QualType ObjectType, NamedDecl *FirstQualifierInScope, 1752 bool AllowInjectedClassName) { 1753 if (TemplateTemplateParmDecl *TTP 1754 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) { 1755 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 1756 // If the corresponding template argument is NULL or non-existent, it's 1757 // because we are performing instantiation from explicitly-specified 1758 // template arguments in a function template, but there were some 1759 // arguments left unspecified. 1760 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), 1761 TTP->getPosition())) 1762 return Name; 1763 1764 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); 1765 1766 if (TemplateArgs.isRewrite()) { 1767 // We're rewriting the template parameter as a reference to another 1768 // template parameter. 1769 if (Arg.getKind() == TemplateArgument::Pack) { 1770 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && 1771 "unexpected pack arguments in template rewrite"); 1772 Arg = Arg.pack_begin()->getPackExpansionPattern(); 1773 } 1774 assert(Arg.getKind() == TemplateArgument::Template && 1775 "unexpected nontype template argument kind in template rewrite"); 1776 return Arg.getAsTemplate(); 1777 } 1778 1779 auto [AssociatedDecl, Final] = 1780 TemplateArgs.getAssociatedDecl(TTP->getDepth()); 1781 std::optional<unsigned> PackIndex; 1782 if (TTP->isParameterPack()) { 1783 assert(Arg.getKind() == TemplateArgument::Pack && 1784 "Missing argument pack"); 1785 1786 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1787 // We have the template argument pack to substitute, but we're not 1788 // actually expanding the enclosing pack expansion yet. So, just 1789 // keep the entire argument pack. 1790 return getSema().Context.getSubstTemplateTemplateParmPack( 1791 Arg, AssociatedDecl, TTP->getIndex(), Final); 1792 } 1793 1794 PackIndex = getPackIndex(Arg); 1795 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1796 } 1797 1798 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute(); 1799 assert(!Template.isNull() && "Null template template argument"); 1800 assert(!Template.getAsQualifiedTemplateName() && 1801 "template decl to substitute is qualified?"); 1802 1803 if (Final) 1804 return Template; 1805 return getSema().Context.getSubstTemplateTemplateParm( 1806 Template, AssociatedDecl, TTP->getIndex(), PackIndex); 1807 } 1808 } 1809 1810 if (SubstTemplateTemplateParmPackStorage *SubstPack 1811 = Name.getAsSubstTemplateTemplateParmPack()) { 1812 if (getSema().ArgumentPackSubstitutionIndex == -1) 1813 return Name; 1814 1815 TemplateArgument Pack = SubstPack->getArgumentPack(); 1816 TemplateName Template = 1817 getPackSubstitutedTemplateArgument(getSema(), Pack).getAsTemplate(); 1818 if (SubstPack->getFinal()) 1819 return Template; 1820 return getSema().Context.getSubstTemplateTemplateParm( 1821 Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(), 1822 SubstPack->getIndex(), getPackIndex(Pack)); 1823 } 1824 1825 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType, 1826 FirstQualifierInScope, 1827 AllowInjectedClassName); 1828 } 1829 1830 ExprResult 1831 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { 1832 if (!E->isTypeDependent()) 1833 return E; 1834 1835 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind()); 1836 } 1837 1838 ExprResult 1839 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, 1840 NonTypeTemplateParmDecl *NTTP) { 1841 // If the corresponding template argument is NULL or non-existent, it's 1842 // because we are performing instantiation from explicitly-specified 1843 // template arguments in a function template, but there were some 1844 // arguments left unspecified. 1845 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(), 1846 NTTP->getPosition())) 1847 return E; 1848 1849 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition()); 1850 1851 if (TemplateArgs.isRewrite()) { 1852 // We're rewriting the template parameter as a reference to another 1853 // template parameter. 1854 if (Arg.getKind() == TemplateArgument::Pack) { 1855 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && 1856 "unexpected pack arguments in template rewrite"); 1857 Arg = Arg.pack_begin()->getPackExpansionPattern(); 1858 } 1859 assert(Arg.getKind() == TemplateArgument::Expression && 1860 "unexpected nontype template argument kind in template rewrite"); 1861 // FIXME: This can lead to the same subexpression appearing multiple times 1862 // in a complete expression. 1863 return Arg.getAsExpr(); 1864 } 1865 1866 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth()); 1867 std::optional<unsigned> PackIndex; 1868 if (NTTP->isParameterPack()) { 1869 assert(Arg.getKind() == TemplateArgument::Pack && 1870 "Missing argument pack"); 1871 1872 if (getSema().ArgumentPackSubstitutionIndex == -1) { 1873 // We have an argument pack, but we can't select a particular argument 1874 // out of it yet. Therefore, we'll build an expression to hold on to that 1875 // argument pack. 1876 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs, 1877 E->getLocation(), 1878 NTTP->getDeclName()); 1879 if (TargetType.isNull()) 1880 return ExprError(); 1881 1882 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context); 1883 if (TargetType->isRecordType()) 1884 ExprType.addConst(); 1885 // FIXME: Pass in Final. 1886 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr( 1887 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue, 1888 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition()); 1889 } 1890 PackIndex = getPackIndex(Arg); 1891 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 1892 } 1893 // FIXME: Don't put subst node on Final replacement. 1894 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(), 1895 Arg, PackIndex); 1896 } 1897 1898 const LoopHintAttr * 1899 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) { 1900 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get(); 1901 1902 if (TransformedExpr == LH->getValue()) 1903 return LH; 1904 1905 // Generate error if there is a problem with the value. 1906 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation())) 1907 return LH; 1908 1909 // Create new LoopHintValueAttr with integral expression in place of the 1910 // non-type template parameter. 1911 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(), 1912 LH->getState(), TransformedExpr, *LH); 1913 } 1914 const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr( 1915 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) { 1916 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A)) 1917 return nullptr; 1918 1919 return A; 1920 } 1921 const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr( 1922 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) { 1923 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A)) 1924 return nullptr; 1925 1926 return A; 1927 } 1928 1929 const CodeAlignAttr * 1930 TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) { 1931 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get(); 1932 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr); 1933 } 1934 1935 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( 1936 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm, 1937 SourceLocation loc, TemplateArgument arg, 1938 std::optional<unsigned> PackIndex) { 1939 ExprResult result; 1940 1941 // Determine the substituted parameter type. We can usually infer this from 1942 // the template argument, but not always. 1943 auto SubstParamType = [&] { 1944 QualType T; 1945 if (parm->isExpandedParameterPack()) 1946 T = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex); 1947 else 1948 T = parm->getType(); 1949 if (parm->isParameterPack() && isa<PackExpansionType>(T)) 1950 T = cast<PackExpansionType>(T)->getPattern(); 1951 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName()); 1952 }; 1953 1954 bool refParam = false; 1955 1956 // The template argument itself might be an expression, in which case we just 1957 // return that expression. This happens when substituting into an alias 1958 // template. 1959 if (arg.getKind() == TemplateArgument::Expression) { 1960 Expr *argExpr = arg.getAsExpr(); 1961 result = argExpr; 1962 if (argExpr->isLValue()) { 1963 if (argExpr->getType()->isRecordType()) { 1964 // Check whether the parameter was actually a reference. 1965 QualType paramType = SubstParamType(); 1966 if (paramType.isNull()) 1967 return ExprError(); 1968 refParam = paramType->isReferenceType(); 1969 } else { 1970 refParam = true; 1971 } 1972 } 1973 } else if (arg.getKind() == TemplateArgument::Declaration || 1974 arg.getKind() == TemplateArgument::NullPtr) { 1975 ValueDecl *VD; 1976 if (arg.getKind() == TemplateArgument::Declaration) { 1977 VD = arg.getAsDecl(); 1978 1979 // Find the instantiation of the template argument. This is 1980 // required for nested templates. 1981 VD = cast_or_null<ValueDecl>( 1982 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs)); 1983 if (!VD) 1984 return ExprError(); 1985 } else { 1986 // Propagate NULL template argument. 1987 VD = nullptr; 1988 } 1989 1990 QualType paramType = VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(); 1991 assert(!paramType.isNull() && "type substitution failed for param type"); 1992 assert(!paramType->isDependentType() && "param type still dependent"); 1993 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc); 1994 refParam = paramType->isReferenceType(); 1995 } else { 1996 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc); 1997 assert(result.isInvalid() || 1998 SemaRef.Context.hasSameType(result.get()->getType(), 1999 arg.getIntegralType())); 2000 } 2001 2002 if (result.isInvalid()) 2003 return ExprError(); 2004 2005 Expr *resultExpr = result.get(); 2006 // FIXME: Don't put subst node on final replacement. 2007 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr( 2008 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr, 2009 AssociatedDecl, parm->getIndex(), PackIndex, refParam); 2010 } 2011 2012 ExprResult 2013 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr( 2014 SubstNonTypeTemplateParmPackExpr *E) { 2015 if (getSema().ArgumentPackSubstitutionIndex == -1) { 2016 // We aren't expanding the parameter pack, so just return ourselves. 2017 return E; 2018 } 2019 2020 TemplateArgument Pack = E->getArgumentPack(); 2021 TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack); 2022 // FIXME: Don't put subst node on final replacement. 2023 return transformNonTypeTemplateParmRef( 2024 E->getAssociatedDecl(), E->getParameterPack(), 2025 E->getParameterPackLocation(), Arg, getPackIndex(Pack)); 2026 } 2027 2028 ExprResult 2029 TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr( 2030 SubstNonTypeTemplateParmExpr *E) { 2031 ExprResult SubstReplacement = E->getReplacement(); 2032 if (!isa<ConstantExpr>(SubstReplacement.get())) 2033 SubstReplacement = TransformExpr(E->getReplacement()); 2034 if (SubstReplacement.isInvalid()) 2035 return true; 2036 QualType SubstType = TransformType(E->getParameterType(getSema().Context)); 2037 if (SubstType.isNull()) 2038 return true; 2039 // The type may have been previously dependent and not now, which means we 2040 // might have to implicit cast the argument to the new type, for example: 2041 // template<auto T, decltype(T) U> 2042 // concept C = sizeof(U) == 4; 2043 // void foo() requires C<2, 'a'> { } 2044 // When normalizing foo(), we first form the normalized constraints of C: 2045 // AtomicExpr(sizeof(U) == 4, 2046 // U=SubstNonTypeTemplateParmExpr(Param=U, 2047 // Expr=DeclRef(U), 2048 // Type=decltype(T))) 2049 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to 2050 // produce: 2051 // AtomicExpr(sizeof(U) == 4, 2052 // U=SubstNonTypeTemplateParmExpr(Param=U, 2053 // Expr=ImpCast( 2054 // decltype(2), 2055 // SubstNTTPE(Param=U, Expr='a', 2056 // Type=char)), 2057 // Type=decltype(2))) 2058 // The call to CheckTemplateArgument here produces the ImpCast. 2059 TemplateArgument SugaredConverted, CanonicalConverted; 2060 if (SemaRef 2061 .CheckTemplateArgument(E->getParameter(), SubstType, 2062 SubstReplacement.get(), SugaredConverted, 2063 CanonicalConverted, Sema::CTAK_Specified) 2064 .isInvalid()) 2065 return true; 2066 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(), 2067 E->getParameter(), E->getExprLoc(), 2068 SugaredConverted, E->getPackIndex()); 2069 } 2070 2071 ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD, 2072 SourceLocation Loc) { 2073 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc); 2074 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD); 2075 } 2076 2077 ExprResult 2078 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) { 2079 if (getSema().ArgumentPackSubstitutionIndex != -1) { 2080 // We can expand this parameter pack now. 2081 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex); 2082 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D)); 2083 if (!VD) 2084 return ExprError(); 2085 return RebuildVarDeclRefExpr(VD, E->getExprLoc()); 2086 } 2087 2088 QualType T = TransformType(E->getType()); 2089 if (T.isNull()) 2090 return ExprError(); 2091 2092 // Transform each of the parameter expansions into the corresponding 2093 // parameters in the instantiation of the function decl. 2094 SmallVector<VarDecl *, 8> Vars; 2095 Vars.reserve(E->getNumExpansions()); 2096 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end(); 2097 I != End; ++I) { 2098 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I)); 2099 if (!D) 2100 return ExprError(); 2101 Vars.push_back(D); 2102 } 2103 2104 auto *PackExpr = 2105 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(), 2106 E->getParameterPackLocation(), Vars); 2107 getSema().MarkFunctionParmPackReferenced(PackExpr); 2108 return PackExpr; 2109 } 2110 2111 ExprResult 2112 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E, 2113 VarDecl *PD) { 2114 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 2115 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found 2116 = getSema().CurrentInstantiationScope->findInstantiationOf(PD); 2117 assert(Found && "no instantiation for parameter pack"); 2118 2119 Decl *TransformedDecl; 2120 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) { 2121 // If this is a reference to a function parameter pack which we can 2122 // substitute but can't yet expand, build a FunctionParmPackExpr for it. 2123 if (getSema().ArgumentPackSubstitutionIndex == -1) { 2124 QualType T = TransformType(E->getType()); 2125 if (T.isNull()) 2126 return ExprError(); 2127 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD, 2128 E->getExprLoc(), *Pack); 2129 getSema().MarkFunctionParmPackReferenced(PackExpr); 2130 return PackExpr; 2131 } 2132 2133 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex]; 2134 } else { 2135 TransformedDecl = Found->get<Decl*>(); 2136 } 2137 2138 // We have either an unexpanded pack or a specific expansion. 2139 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc()); 2140 } 2141 2142 ExprResult 2143 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { 2144 NamedDecl *D = E->getDecl(); 2145 2146 // Handle references to non-type template parameters and non-type template 2147 // parameter packs. 2148 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { 2149 if (NTTP->getDepth() < TemplateArgs.getNumLevels()) 2150 return TransformTemplateParmRefExpr(E, NTTP); 2151 2152 // We have a non-type template parameter that isn't fully substituted; 2153 // FindInstantiatedDecl will find it in the local instantiation scope. 2154 } 2155 2156 // Handle references to function parameter packs. 2157 if (VarDecl *PD = dyn_cast<VarDecl>(D)) 2158 if (PD->isParameterPack()) 2159 return TransformFunctionParmPackRefExpr(E, PD); 2160 2161 return inherited::TransformDeclRefExpr(E); 2162 } 2163 2164 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( 2165 CXXDefaultArgExpr *E) { 2166 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())-> 2167 getDescribedFunctionTemplate() && 2168 "Default arg expressions are never formed in dependent cases."); 2169 return SemaRef.BuildCXXDefaultArgExpr( 2170 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()), 2171 E->getParam()); 2172 } 2173 2174 template<typename Fn> 2175 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB, 2176 FunctionProtoTypeLoc TL, 2177 CXXRecordDecl *ThisContext, 2178 Qualifiers ThisTypeQuals, 2179 Fn TransformExceptionSpec) { 2180 // We need a local instantiation scope for this function prototype. 2181 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); 2182 return inherited::TransformFunctionProtoType( 2183 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec); 2184 } 2185 2186 ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam( 2187 ParmVarDecl *OldParm, int indexAdjustment, 2188 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) { 2189 auto NewParm = SemaRef.SubstParmVarDecl( 2190 OldParm, TemplateArgs, indexAdjustment, NumExpansions, 2191 ExpectParameterPack, EvaluateConstraints); 2192 if (NewParm && SemaRef.getLangOpts().OpenCL) 2193 SemaRef.deduceOpenCLAddressSpace(NewParm); 2194 return NewParm; 2195 } 2196 2197 QualType TemplateInstantiator::BuildSubstTemplateTypeParmType( 2198 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, 2199 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex, 2200 TemplateArgument Arg, SourceLocation NameLoc) { 2201 QualType Replacement = Arg.getAsType(); 2202 2203 // If the template parameter had ObjC lifetime qualifiers, 2204 // then any such qualifiers on the replacement type are ignored. 2205 if (SuppressObjCLifetime) { 2206 Qualifiers RQs; 2207 RQs = Replacement.getQualifiers(); 2208 RQs.removeObjCLifetime(); 2209 Replacement = 2210 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs); 2211 } 2212 2213 if (Final) { 2214 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc); 2215 return Replacement; 2216 } 2217 // TODO: only do this uniquing once, at the start of instantiation. 2218 QualType Result = getSema().Context.getSubstTemplateTypeParmType( 2219 Replacement, AssociatedDecl, Index, PackIndex); 2220 SubstTemplateTypeParmTypeLoc NewTL = 2221 TLB.push<SubstTemplateTypeParmTypeLoc>(Result); 2222 NewTL.setNameLoc(NameLoc); 2223 return Result; 2224 } 2225 2226 QualType 2227 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, 2228 TemplateTypeParmTypeLoc TL, 2229 bool SuppressObjCLifetime) { 2230 const TemplateTypeParmType *T = TL.getTypePtr(); 2231 if (T->getDepth() < TemplateArgs.getNumLevels()) { 2232 // Replace the template type parameter with its corresponding 2233 // template argument. 2234 2235 // If the corresponding template argument is NULL or doesn't exist, it's 2236 // because we are performing instantiation from explicitly-specified 2237 // template arguments in a function template class, but there were some 2238 // arguments left unspecified. 2239 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) { 2240 TemplateTypeParmTypeLoc NewTL 2241 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType()); 2242 NewTL.setNameLoc(TL.getNameLoc()); 2243 return TL.getType(); 2244 } 2245 2246 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex()); 2247 2248 if (TemplateArgs.isRewrite()) { 2249 // We're rewriting the template parameter as a reference to another 2250 // template parameter. 2251 if (Arg.getKind() == TemplateArgument::Pack) { 2252 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && 2253 "unexpected pack arguments in template rewrite"); 2254 Arg = Arg.pack_begin()->getPackExpansionPattern(); 2255 } 2256 assert(Arg.getKind() == TemplateArgument::Type && 2257 "unexpected nontype template argument kind in template rewrite"); 2258 QualType NewT = Arg.getAsType(); 2259 assert(isa<TemplateTypeParmType>(NewT) && 2260 "type parm not rewritten to type parm"); 2261 auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT); 2262 NewTL.setNameLoc(TL.getNameLoc()); 2263 return NewT; 2264 } 2265 2266 auto [AssociatedDecl, Final] = 2267 TemplateArgs.getAssociatedDecl(T->getDepth()); 2268 std::optional<unsigned> PackIndex; 2269 if (T->isParameterPack()) { 2270 assert(Arg.getKind() == TemplateArgument::Pack && 2271 "Missing argument pack"); 2272 2273 if (getSema().ArgumentPackSubstitutionIndex == -1) { 2274 // We have the template argument pack, but we're not expanding the 2275 // enclosing pack expansion yet. Just save the template argument 2276 // pack for later substitution. 2277 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType( 2278 AssociatedDecl, T->getIndex(), Final, Arg); 2279 SubstTemplateTypeParmPackTypeLoc NewTL 2280 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result); 2281 NewTL.setNameLoc(TL.getNameLoc()); 2282 return Result; 2283 } 2284 2285 // PackIndex starts from last element. 2286 PackIndex = getPackIndex(Arg); 2287 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); 2288 } 2289 2290 assert(Arg.getKind() == TemplateArgument::Type && 2291 "Template argument kind mismatch"); 2292 2293 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final, 2294 AssociatedDecl, T->getIndex(), 2295 PackIndex, Arg, TL.getNameLoc()); 2296 } 2297 2298 // The template type parameter comes from an inner template (e.g., 2299 // the template parameter list of a member template inside the 2300 // template we are instantiating). Create a new template type 2301 // parameter with the template "level" reduced by one. 2302 TemplateTypeParmDecl *NewTTPDecl = nullptr; 2303 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl()) 2304 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>( 2305 TransformDecl(TL.getNameLoc(), OldTTPDecl)); 2306 QualType Result = getSema().Context.getTemplateTypeParmType( 2307 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(), 2308 T->isParameterPack(), NewTTPDecl); 2309 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result); 2310 NewTL.setNameLoc(TL.getNameLoc()); 2311 return Result; 2312 } 2313 2314 QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType( 2315 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, 2316 bool SuppressObjCLifetime) { 2317 const SubstTemplateTypeParmPackType *T = TL.getTypePtr(); 2318 2319 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl()); 2320 2321 if (getSema().ArgumentPackSubstitutionIndex == -1) { 2322 // We aren't expanding the parameter pack, so just return ourselves. 2323 QualType Result = TL.getType(); 2324 if (NewReplaced != T->getAssociatedDecl()) 2325 Result = getSema().Context.getSubstTemplateTypeParmPackType( 2326 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack()); 2327 SubstTemplateTypeParmPackTypeLoc NewTL = 2328 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result); 2329 NewTL.setNameLoc(TL.getNameLoc()); 2330 return Result; 2331 } 2332 2333 TemplateArgument Pack = T->getArgumentPack(); 2334 TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack); 2335 return BuildSubstTemplateTypeParmType( 2336 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(), 2337 getPackIndex(Pack), Arg, TL.getNameLoc()); 2338 } 2339 2340 static concepts::Requirement::SubstitutionDiagnostic * 2341 createSubstDiag(Sema &S, TemplateDeductionInfo &Info, 2342 concepts::EntityPrinter Printer) { 2343 SmallString<128> Message; 2344 SourceLocation ErrorLoc; 2345 if (Info.hasSFINAEDiagnostic()) { 2346 PartialDiagnosticAt PDA(SourceLocation(), 2347 PartialDiagnostic::NullDiagnostic{}); 2348 Info.takeSFINAEDiagnostic(PDA); 2349 PDA.second.EmitToString(S.getDiagnostics(), Message); 2350 ErrorLoc = PDA.first; 2351 } else { 2352 ErrorLoc = Info.getLocation(); 2353 } 2354 char *MessageBuf = new (S.Context) char[Message.size()]; 2355 std::copy(Message.begin(), Message.end(), MessageBuf); 2356 SmallString<128> Entity; 2357 llvm::raw_svector_ostream OS(Entity); 2358 Printer(OS); 2359 char *EntityBuf = new (S.Context) char[Entity.size()]; 2360 std::copy(Entity.begin(), Entity.end(), EntityBuf); 2361 return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{ 2362 StringRef(EntityBuf, Entity.size()), ErrorLoc, 2363 StringRef(MessageBuf, Message.size())}; 2364 } 2365 2366 concepts::Requirement::SubstitutionDiagnostic * 2367 concepts::createSubstDiagAt(Sema &S, SourceLocation Location, 2368 EntityPrinter Printer) { 2369 SmallString<128> Entity; 2370 llvm::raw_svector_ostream OS(Entity); 2371 Printer(OS); 2372 char *EntityBuf = new (S.Context) char[Entity.size()]; 2373 llvm::copy(Entity, EntityBuf); 2374 return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{ 2375 /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()), 2376 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()}; 2377 } 2378 2379 ExprResult TemplateInstantiator::TransformRequiresTypeParams( 2380 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE, 2381 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params, 2382 SmallVectorImpl<QualType> &PTypes, 2383 SmallVectorImpl<ParmVarDecl *> &TransParams, 2384 Sema::ExtParameterInfoBuilder &PInfos) { 2385 2386 TemplateDeductionInfo Info(KWLoc); 2387 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, 2388 RE, Info, 2389 SourceRange{KWLoc, RBraceLoc}); 2390 Sema::SFINAETrap Trap(SemaRef); 2391 2392 unsigned ErrorIdx; 2393 if (getDerived().TransformFunctionTypeParams( 2394 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes, 2395 &TransParams, PInfos, &ErrorIdx) || 2396 Trap.hasErrorOccurred()) { 2397 SmallVector<concepts::Requirement *, 4> TransReqs; 2398 ParmVarDecl *FailedDecl = Params[ErrorIdx]; 2399 // Add a 'failed' Requirement to contain the error that caused the failure 2400 // here. 2401 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag( 2402 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; }))); 2403 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(), 2404 TransParams, RE->getRParenLoc(), 2405 TransReqs, RBraceLoc); 2406 } 2407 2408 return ExprResult{}; 2409 } 2410 2411 concepts::TypeRequirement * 2412 TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) { 2413 if (!Req->isDependent() && !AlwaysRebuild()) 2414 return Req; 2415 if (Req->isSubstitutionFailure()) { 2416 if (AlwaysRebuild()) 2417 return RebuildTypeRequirement( 2418 Req->getSubstitutionDiagnostic()); 2419 return Req; 2420 } 2421 2422 Sema::SFINAETrap Trap(SemaRef); 2423 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc()); 2424 Sema::InstantiatingTemplate TypeInst(SemaRef, 2425 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info, 2426 Req->getType()->getTypeLoc().getSourceRange()); 2427 if (TypeInst.isInvalid()) 2428 return nullptr; 2429 TypeSourceInfo *TransType = TransformType(Req->getType()); 2430 if (!TransType || Trap.hasErrorOccurred()) 2431 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info, 2432 [&] (llvm::raw_ostream& OS) { 2433 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy()); 2434 })); 2435 return RebuildTypeRequirement(TransType); 2436 } 2437 2438 concepts::ExprRequirement * 2439 TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) { 2440 if (!Req->isDependent() && !AlwaysRebuild()) 2441 return Req; 2442 2443 Sema::SFINAETrap Trap(SemaRef); 2444 2445 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> 2446 TransExpr; 2447 if (Req->isExprSubstitutionFailure()) 2448 TransExpr = Req->getExprSubstitutionDiagnostic(); 2449 else { 2450 Expr *E = Req->getExpr(); 2451 TemplateDeductionInfo Info(E->getBeginLoc()); 2452 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info, 2453 E->getSourceRange()); 2454 if (ExprInst.isInvalid()) 2455 return nullptr; 2456 ExprResult TransExprRes = TransformExpr(E); 2457 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() && 2458 TransExprRes.get()->hasPlaceholderType()) 2459 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get()); 2460 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred()) 2461 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) { 2462 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy()); 2463 }); 2464 else 2465 TransExpr = TransExprRes.get(); 2466 } 2467 2468 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq; 2469 const auto &RetReq = Req->getReturnTypeRequirement(); 2470 if (RetReq.isEmpty()) 2471 TransRetReq.emplace(); 2472 else if (RetReq.isSubstitutionFailure()) 2473 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic()); 2474 else if (RetReq.isTypeConstraint()) { 2475 TemplateParameterList *OrigTPL = 2476 RetReq.getTypeConstraintTemplateParameterList(); 2477 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc()); 2478 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), 2479 Req, Info, OrigTPL->getSourceRange()); 2480 if (TPLInst.isInvalid()) 2481 return nullptr; 2482 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL); 2483 if (!TPL) 2484 TransRetReq.emplace(createSubstDiag(SemaRef, Info, 2485 [&] (llvm::raw_ostream& OS) { 2486 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint() 2487 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy()); 2488 })); 2489 else { 2490 TPLInst.Clear(); 2491 TransRetReq.emplace(TPL); 2492 } 2493 } 2494 assert(TransRetReq && "All code paths leading here must set TransRetReq"); 2495 if (Expr *E = TransExpr.dyn_cast<Expr *>()) 2496 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(), 2497 std::move(*TransRetReq)); 2498 return RebuildExprRequirement( 2499 TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(), 2500 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq)); 2501 } 2502 2503 concepts::NestedRequirement * 2504 TemplateInstantiator::TransformNestedRequirement( 2505 concepts::NestedRequirement *Req) { 2506 if (!Req->isDependent() && !AlwaysRebuild()) 2507 return Req; 2508 if (Req->hasInvalidConstraint()) { 2509 if (AlwaysRebuild()) 2510 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(), 2511 Req->getConstraintSatisfaction()); 2512 return Req; 2513 } 2514 Sema::InstantiatingTemplate ReqInst(SemaRef, 2515 Req->getConstraintExpr()->getBeginLoc(), Req, 2516 Sema::InstantiatingTemplate::ConstraintsCheck{}, 2517 Req->getConstraintExpr()->getSourceRange()); 2518 if (!getEvaluateConstraints()) { 2519 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr()); 2520 if (TransConstraint.isInvalid() || !TransConstraint.get()) 2521 return nullptr; 2522 if (TransConstraint.get()->isInstantiationDependent()) 2523 return new (SemaRef.Context) 2524 concepts::NestedRequirement(TransConstraint.get()); 2525 ConstraintSatisfaction Satisfaction; 2526 return new (SemaRef.Context) concepts::NestedRequirement( 2527 SemaRef.Context, TransConstraint.get(), Satisfaction); 2528 } 2529 2530 ExprResult TransConstraint; 2531 ConstraintSatisfaction Satisfaction; 2532 TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc()); 2533 { 2534 EnterExpressionEvaluationContext ContextRAII( 2535 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 2536 Sema::SFINAETrap Trap(SemaRef); 2537 Sema::InstantiatingTemplate ConstrInst(SemaRef, 2538 Req->getConstraintExpr()->getBeginLoc(), Req, Info, 2539 Req->getConstraintExpr()->getSourceRange()); 2540 if (ConstrInst.isInvalid()) 2541 return nullptr; 2542 llvm::SmallVector<Expr *> Result; 2543 if (!SemaRef.CheckConstraintSatisfaction( 2544 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs, 2545 Req->getConstraintExpr()->getSourceRange(), Satisfaction) && 2546 !Result.empty()) 2547 TransConstraint = Result[0]; 2548 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled " 2549 "by CheckConstraintSatisfaction."); 2550 } 2551 if (TransConstraint.isUsable() && 2552 TransConstraint.get()->isInstantiationDependent()) 2553 return new (SemaRef.Context) 2554 concepts::NestedRequirement(TransConstraint.get()); 2555 if (TransConstraint.isInvalid() || !TransConstraint.get() || 2556 Satisfaction.HasSubstitutionFailure()) { 2557 SmallString<128> Entity; 2558 llvm::raw_svector_ostream OS(Entity); 2559 Req->getConstraintExpr()->printPretty(OS, nullptr, 2560 SemaRef.getPrintingPolicy()); 2561 char *EntityBuf = new (SemaRef.Context) char[Entity.size()]; 2562 std::copy(Entity.begin(), Entity.end(), EntityBuf); 2563 return new (SemaRef.Context) concepts::NestedRequirement( 2564 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction); 2565 } 2566 return new (SemaRef.Context) concepts::NestedRequirement( 2567 SemaRef.Context, TransConstraint.get(), Satisfaction); 2568 } 2569 2570 2571 /// Perform substitution on the type T with a given set of template 2572 /// arguments. 2573 /// 2574 /// This routine substitutes the given template arguments into the 2575 /// type T and produces the instantiated type. 2576 /// 2577 /// \param T the type into which the template arguments will be 2578 /// substituted. If this type is not dependent, it will be returned 2579 /// immediately. 2580 /// 2581 /// \param Args the template arguments that will be 2582 /// substituted for the top-level template parameters within T. 2583 /// 2584 /// \param Loc the location in the source code where this substitution 2585 /// is being performed. It will typically be the location of the 2586 /// declarator (if we're instantiating the type of some declaration) 2587 /// or the location of the type in the source code (if, e.g., we're 2588 /// instantiating the type of a cast expression). 2589 /// 2590 /// \param Entity the name of the entity associated with a declaration 2591 /// being instantiated (if any). May be empty to indicate that there 2592 /// is no such entity (if, e.g., this is a type that occurs as part of 2593 /// a cast expression) or that the entity has no name (e.g., an 2594 /// unnamed function parameter). 2595 /// 2596 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is 2597 /// acceptable as the top level type of the result. 2598 /// 2599 /// \returns If the instantiation succeeds, the instantiated 2600 /// type. Otherwise, produces diagnostics and returns a NULL type. 2601 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, 2602 const MultiLevelTemplateArgumentList &Args, 2603 SourceLocation Loc, 2604 DeclarationName Entity, 2605 bool AllowDeducedTST) { 2606 assert(!CodeSynthesisContexts.empty() && 2607 "Cannot perform an instantiation without some context on the " 2608 "instantiation stack"); 2609 2610 if (!T->getType()->isInstantiationDependentType() && 2611 !T->getType()->isVariablyModifiedType()) 2612 return T; 2613 2614 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 2615 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T) 2616 : Instantiator.TransformType(T); 2617 } 2618 2619 TypeSourceInfo *Sema::SubstType(TypeLoc TL, 2620 const MultiLevelTemplateArgumentList &Args, 2621 SourceLocation Loc, 2622 DeclarationName Entity) { 2623 assert(!CodeSynthesisContexts.empty() && 2624 "Cannot perform an instantiation without some context on the " 2625 "instantiation stack"); 2626 2627 if (TL.getType().isNull()) 2628 return nullptr; 2629 2630 if (!TL.getType()->isInstantiationDependentType() && 2631 !TL.getType()->isVariablyModifiedType()) { 2632 // FIXME: Make a copy of the TypeLoc data here, so that we can 2633 // return a new TypeSourceInfo. Inefficient! 2634 TypeLocBuilder TLB; 2635 TLB.pushFullCopy(TL); 2636 return TLB.getTypeSourceInfo(Context, TL.getType()); 2637 } 2638 2639 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 2640 TypeLocBuilder TLB; 2641 TLB.reserve(TL.getFullDataSize()); 2642 QualType Result = Instantiator.TransformType(TLB, TL); 2643 if (Result.isNull()) 2644 return nullptr; 2645 2646 return TLB.getTypeSourceInfo(Context, Result); 2647 } 2648 2649 /// Deprecated form of the above. 2650 QualType Sema::SubstType(QualType T, 2651 const MultiLevelTemplateArgumentList &TemplateArgs, 2652 SourceLocation Loc, DeclarationName Entity) { 2653 assert(!CodeSynthesisContexts.empty() && 2654 "Cannot perform an instantiation without some context on the " 2655 "instantiation stack"); 2656 2657 // If T is not a dependent type or a variably-modified type, there 2658 // is nothing to do. 2659 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType()) 2660 return T; 2661 2662 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); 2663 return Instantiator.TransformType(T); 2664 } 2665 2666 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) { 2667 if (T->getType()->isInstantiationDependentType() || 2668 T->getType()->isVariablyModifiedType()) 2669 return true; 2670 2671 TypeLoc TL = T->getTypeLoc().IgnoreParens(); 2672 if (!TL.getAs<FunctionProtoTypeLoc>()) 2673 return false; 2674 2675 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>(); 2676 for (ParmVarDecl *P : FP.getParams()) { 2677 // This must be synthesized from a typedef. 2678 if (!P) continue; 2679 2680 // If there are any parameters, a new TypeSourceInfo that refers to the 2681 // instantiated parameters must be built. 2682 return true; 2683 } 2684 2685 return false; 2686 } 2687 2688 /// A form of SubstType intended specifically for instantiating the 2689 /// type of a FunctionDecl. Its purpose is solely to force the 2690 /// instantiation of default-argument expressions and to avoid 2691 /// instantiating an exception-specification. 2692 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T, 2693 const MultiLevelTemplateArgumentList &Args, 2694 SourceLocation Loc, 2695 DeclarationName Entity, 2696 CXXRecordDecl *ThisContext, 2697 Qualifiers ThisTypeQuals, 2698 bool EvaluateConstraints) { 2699 assert(!CodeSynthesisContexts.empty() && 2700 "Cannot perform an instantiation without some context on the " 2701 "instantiation stack"); 2702 2703 if (!NeedsInstantiationAsFunctionType(T)) 2704 return T; 2705 2706 TemplateInstantiator Instantiator(*this, Args, Loc, Entity); 2707 Instantiator.setEvaluateConstraints(EvaluateConstraints); 2708 2709 TypeLocBuilder TLB; 2710 2711 TypeLoc TL = T->getTypeLoc(); 2712 TLB.reserve(TL.getFullDataSize()); 2713 2714 QualType Result; 2715 2716 if (FunctionProtoTypeLoc Proto = 2717 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) { 2718 // Instantiate the type, other than its exception specification. The 2719 // exception specification is instantiated in InitFunctionInstantiation 2720 // once we've built the FunctionDecl. 2721 // FIXME: Set the exception specification to EST_Uninstantiated here, 2722 // instead of rebuilding the function type again later. 2723 Result = Instantiator.TransformFunctionProtoType( 2724 TLB, Proto, ThisContext, ThisTypeQuals, 2725 [](FunctionProtoType::ExceptionSpecInfo &ESI, 2726 bool &Changed) { return false; }); 2727 } else { 2728 Result = Instantiator.TransformType(TLB, TL); 2729 } 2730 // When there are errors resolving types, clang may use IntTy as a fallback, 2731 // breaking our assumption that function declarations have function types. 2732 if (Result.isNull() || !Result->isFunctionType()) 2733 return nullptr; 2734 2735 return TLB.getTypeSourceInfo(Context, Result); 2736 } 2737 2738 bool Sema::SubstExceptionSpec(SourceLocation Loc, 2739 FunctionProtoType::ExceptionSpecInfo &ESI, 2740 SmallVectorImpl<QualType> &ExceptionStorage, 2741 const MultiLevelTemplateArgumentList &Args) { 2742 bool Changed = false; 2743 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName()); 2744 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage, 2745 Changed); 2746 } 2747 2748 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, 2749 const MultiLevelTemplateArgumentList &Args) { 2750 FunctionProtoType::ExceptionSpecInfo ESI = 2751 Proto->getExtProtoInfo().ExceptionSpec; 2752 2753 SmallVector<QualType, 4> ExceptionStorage; 2754 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(), 2755 ESI, ExceptionStorage, Args)) 2756 // On error, recover by dropping the exception specification. 2757 ESI.Type = EST_None; 2758 2759 UpdateExceptionSpec(New, ESI); 2760 } 2761 2762 namespace { 2763 2764 struct GetContainedInventedTypeParmVisitor : 2765 public TypeVisitor<GetContainedInventedTypeParmVisitor, 2766 TemplateTypeParmDecl *> { 2767 using TypeVisitor<GetContainedInventedTypeParmVisitor, 2768 TemplateTypeParmDecl *>::Visit; 2769 2770 TemplateTypeParmDecl *Visit(QualType T) { 2771 if (T.isNull()) 2772 return nullptr; 2773 return Visit(T.getTypePtr()); 2774 } 2775 // The deduced type itself. 2776 TemplateTypeParmDecl *VisitTemplateTypeParmType( 2777 const TemplateTypeParmType *T) { 2778 if (!T->getDecl() || !T->getDecl()->isImplicit()) 2779 return nullptr; 2780 return T->getDecl(); 2781 } 2782 2783 // Only these types can contain 'auto' types, and subsequently be replaced 2784 // by references to invented parameters. 2785 2786 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) { 2787 return Visit(T->getNamedType()); 2788 } 2789 2790 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) { 2791 return Visit(T->getPointeeType()); 2792 } 2793 2794 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) { 2795 return Visit(T->getPointeeType()); 2796 } 2797 2798 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) { 2799 return Visit(T->getPointeeTypeAsWritten()); 2800 } 2801 2802 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) { 2803 return Visit(T->getPointeeType()); 2804 } 2805 2806 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) { 2807 return Visit(T->getElementType()); 2808 } 2809 2810 TemplateTypeParmDecl *VisitDependentSizedExtVectorType( 2811 const DependentSizedExtVectorType *T) { 2812 return Visit(T->getElementType()); 2813 } 2814 2815 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) { 2816 return Visit(T->getElementType()); 2817 } 2818 2819 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) { 2820 return VisitFunctionType(T); 2821 } 2822 2823 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) { 2824 return Visit(T->getReturnType()); 2825 } 2826 2827 TemplateTypeParmDecl *VisitParenType(const ParenType *T) { 2828 return Visit(T->getInnerType()); 2829 } 2830 2831 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) { 2832 return Visit(T->getModifiedType()); 2833 } 2834 2835 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) { 2836 return Visit(T->getUnderlyingType()); 2837 } 2838 2839 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) { 2840 return Visit(T->getOriginalType()); 2841 } 2842 2843 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) { 2844 return Visit(T->getPattern()); 2845 } 2846 }; 2847 2848 } // namespace 2849 2850 bool Sema::SubstTypeConstraint( 2851 TemplateTypeParmDecl *Inst, const TypeConstraint *TC, 2852 const MultiLevelTemplateArgumentList &TemplateArgs, 2853 bool EvaluateConstraints) { 2854 const ASTTemplateArgumentListInfo *TemplArgInfo = 2855 TC->getTemplateArgsAsWritten(); 2856 2857 if (!EvaluateConstraints) { 2858 Inst->setTypeConstraint(TC->getConceptReference(), 2859 TC->getImmediatelyDeclaredConstraint()); 2860 return false; 2861 } 2862 2863 TemplateArgumentListInfo InstArgs; 2864 2865 if (TemplArgInfo) { 2866 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc); 2867 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc); 2868 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs, 2869 InstArgs)) 2870 return true; 2871 } 2872 return AttachTypeConstraint( 2873 TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(), 2874 TC->getNamedConcept(), &InstArgs, Inst, 2875 Inst->isParameterPack() 2876 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint()) 2877 ->getEllipsisLoc() 2878 : SourceLocation()); 2879 } 2880 2881 ParmVarDecl *Sema::SubstParmVarDecl( 2882 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs, 2883 int indexAdjustment, std::optional<unsigned> NumExpansions, 2884 bool ExpectParameterPack, bool EvaluateConstraint) { 2885 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo(); 2886 TypeSourceInfo *NewDI = nullptr; 2887 2888 TypeLoc OldTL = OldDI->getTypeLoc(); 2889 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) { 2890 2891 // We have a function parameter pack. Substitute into the pattern of the 2892 // expansion. 2893 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, 2894 OldParm->getLocation(), OldParm->getDeclName()); 2895 if (!NewDI) 2896 return nullptr; 2897 2898 if (NewDI->getType()->containsUnexpandedParameterPack()) { 2899 // We still have unexpanded parameter packs, which means that 2900 // our function parameter is still a function parameter pack. 2901 // Therefore, make its type a pack expansion type. 2902 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(), 2903 NumExpansions); 2904 } else if (ExpectParameterPack) { 2905 // We expected to get a parameter pack but didn't (because the type 2906 // itself is not a pack expansion type), so complain. This can occur when 2907 // the substitution goes through an alias template that "loses" the 2908 // pack expansion. 2909 Diag(OldParm->getLocation(), 2910 diag::err_function_parameter_pack_without_parameter_packs) 2911 << NewDI->getType(); 2912 return nullptr; 2913 } 2914 } else { 2915 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), 2916 OldParm->getDeclName()); 2917 } 2918 2919 if (!NewDI) 2920 return nullptr; 2921 2922 if (NewDI->getType()->isVoidType()) { 2923 Diag(OldParm->getLocation(), diag::err_param_with_void_type); 2924 return nullptr; 2925 } 2926 2927 // In abbreviated templates, TemplateTypeParmDecls with possible 2928 // TypeConstraints are created when the parameter list is originally parsed. 2929 // The TypeConstraints can therefore reference other functions parameters in 2930 // the abbreviated function template, which is why we must instantiate them 2931 // here, when the instantiated versions of those referenced parameters are in 2932 // scope. 2933 if (TemplateTypeParmDecl *TTP = 2934 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) { 2935 if (const TypeConstraint *TC = TTP->getTypeConstraint()) { 2936 auto *Inst = cast_or_null<TemplateTypeParmDecl>( 2937 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs)); 2938 // We will first get here when instantiating the abbreviated function 2939 // template's described function, but we might also get here later. 2940 // Make sure we do not instantiate the TypeConstraint more than once. 2941 if (Inst && !Inst->getTypeConstraint()) { 2942 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint)) 2943 return nullptr; 2944 } 2945 } 2946 } 2947 2948 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(), 2949 OldParm->getInnerLocStart(), 2950 OldParm->getLocation(), 2951 OldParm->getIdentifier(), 2952 NewDI->getType(), NewDI, 2953 OldParm->getStorageClass()); 2954 if (!NewParm) 2955 return nullptr; 2956 2957 // Mark the (new) default argument as uninstantiated (if any). 2958 if (OldParm->hasUninstantiatedDefaultArg()) { 2959 Expr *Arg = OldParm->getUninstantiatedDefaultArg(); 2960 NewParm->setUninstantiatedDefaultArg(Arg); 2961 } else if (OldParm->hasUnparsedDefaultArg()) { 2962 NewParm->setUnparsedDefaultArg(); 2963 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm); 2964 } else if (Expr *Arg = OldParm->getDefaultArg()) { 2965 // Default arguments cannot be substituted until the declaration context 2966 // for the associated function or lambda capture class is available. 2967 // This is necessary for cases like the following where construction of 2968 // the lambda capture class for the outer lambda is dependent on the 2969 // parameter types but where the default argument is dependent on the 2970 // outer lambda's declaration context. 2971 // template <typename T> 2972 // auto f() { 2973 // return [](T = []{ return T{}; }()) { return 0; }; 2974 // } 2975 NewParm->setUninstantiatedDefaultArg(Arg); 2976 } 2977 2978 NewParm->setExplicitObjectParameterLoc( 2979 OldParm->getExplicitObjectParamThisLoc()); 2980 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); 2981 2982 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) { 2983 // Add the new parameter to the instantiated parameter pack. 2984 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm); 2985 } else { 2986 // Introduce an Old -> New mapping 2987 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); 2988 } 2989 2990 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext 2991 // can be anything, is this right ? 2992 NewParm->setDeclContext(CurContext); 2993 2994 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(), 2995 OldParm->getFunctionScopeIndex() + indexAdjustment); 2996 2997 InstantiateAttrs(TemplateArgs, OldParm, NewParm); 2998 2999 return NewParm; 3000 } 3001 3002 /// Substitute the given template arguments into the given set of 3003 /// parameters, producing the set of parameter types that would be generated 3004 /// from such a substitution. 3005 bool Sema::SubstParmTypes( 3006 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, 3007 const FunctionProtoType::ExtParameterInfo *ExtParamInfos, 3008 const MultiLevelTemplateArgumentList &TemplateArgs, 3009 SmallVectorImpl<QualType> &ParamTypes, 3010 SmallVectorImpl<ParmVarDecl *> *OutParams, 3011 ExtParameterInfoBuilder &ParamInfos) { 3012 assert(!CodeSynthesisContexts.empty() && 3013 "Cannot perform an instantiation without some context on the " 3014 "instantiation stack"); 3015 3016 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 3017 DeclarationName()); 3018 return Instantiator.TransformFunctionTypeParams( 3019 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos); 3020 } 3021 3022 /// Substitute the given template arguments into the default argument. 3023 bool Sema::SubstDefaultArgument( 3024 SourceLocation Loc, 3025 ParmVarDecl *Param, 3026 const MultiLevelTemplateArgumentList &TemplateArgs, 3027 bool ForCallExpr) { 3028 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); 3029 Expr *PatternExpr = Param->getUninstantiatedDefaultArg(); 3030 3031 EnterExpressionEvaluationContext EvalContext( 3032 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 3033 3034 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost()); 3035 if (Inst.isInvalid()) 3036 return true; 3037 if (Inst.isAlreadyInstantiating()) { 3038 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 3039 Param->setInvalidDecl(); 3040 return true; 3041 } 3042 3043 ExprResult Result; 3044 { 3045 // C++ [dcl.fct.default]p5: 3046 // The names in the [default argument] expression are bound, and 3047 // the semantic constraints are checked, at the point where the 3048 // default argument expression appears. 3049 ContextRAII SavedContext(*this, FD); 3050 std::unique_ptr<LocalInstantiationScope> LIS; 3051 3052 if (ForCallExpr) { 3053 // When instantiating a default argument due to use in a call expression, 3054 // an instantiation scope that includes the parameters of the callee is 3055 // required to satisfy references from the default argument. For example: 3056 // template<typename T> void f(T a, int = decltype(a)()); 3057 // void g() { f(0); } 3058 LIS = std::make_unique<LocalInstantiationScope>(*this); 3059 FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern( 3060 /*ForDefinition*/ false); 3061 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs)) 3062 return true; 3063 } 3064 3065 runWithSufficientStackSpace(Loc, [&] { 3066 Result = SubstInitializer(PatternExpr, TemplateArgs, 3067 /*DirectInit*/false); 3068 }); 3069 } 3070 if (Result.isInvalid()) 3071 return true; 3072 3073 if (ForCallExpr) { 3074 // Check the expression as an initializer for the parameter. 3075 InitializedEntity Entity 3076 = InitializedEntity::InitializeParameter(Context, Param); 3077 InitializationKind Kind = InitializationKind::CreateCopy( 3078 Param->getLocation(), 3079 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc()); 3080 Expr *ResultE = Result.getAs<Expr>(); 3081 3082 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3083 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3084 if (Result.isInvalid()) 3085 return true; 3086 3087 Result = 3088 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 3089 /*DiscardedValue*/ false); 3090 } else { 3091 // FIXME: Obtain the source location for the '=' token. 3092 SourceLocation EqualLoc = PatternExpr->getBeginLoc(); 3093 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc); 3094 } 3095 if (Result.isInvalid()) 3096 return true; 3097 3098 // Remember the instantiated default argument. 3099 Param->setDefaultArg(Result.getAs<Expr>()); 3100 3101 return false; 3102 } 3103 3104 /// Perform substitution on the base class specifiers of the 3105 /// given class template specialization. 3106 /// 3107 /// Produces a diagnostic and returns true on error, returns false and 3108 /// attaches the instantiated base classes to the class template 3109 /// specialization if successful. 3110 bool 3111 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 3112 CXXRecordDecl *Pattern, 3113 const MultiLevelTemplateArgumentList &TemplateArgs) { 3114 bool Invalid = false; 3115 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; 3116 for (const auto &Base : Pattern->bases()) { 3117 if (!Base.getType()->isDependentType()) { 3118 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) { 3119 if (RD->isInvalidDecl()) 3120 Instantiation->setInvalidDecl(); 3121 } 3122 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base)); 3123 continue; 3124 } 3125 3126 SourceLocation EllipsisLoc; 3127 TypeSourceInfo *BaseTypeLoc; 3128 if (Base.isPackExpansion()) { 3129 // This is a pack expansion. See whether we should expand it now, or 3130 // wait until later. 3131 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 3132 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(), 3133 Unexpanded); 3134 bool ShouldExpand = false; 3135 bool RetainExpansion = false; 3136 std::optional<unsigned> NumExpansions; 3137 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(), 3138 Base.getSourceRange(), 3139 Unexpanded, 3140 TemplateArgs, ShouldExpand, 3141 RetainExpansion, 3142 NumExpansions)) { 3143 Invalid = true; 3144 continue; 3145 } 3146 3147 // If we should expand this pack expansion now, do so. 3148 if (ShouldExpand) { 3149 for (unsigned I = 0; I != *NumExpansions; ++I) { 3150 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 3151 3152 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), 3153 TemplateArgs, 3154 Base.getSourceRange().getBegin(), 3155 DeclarationName()); 3156 if (!BaseTypeLoc) { 3157 Invalid = true; 3158 continue; 3159 } 3160 3161 if (CXXBaseSpecifier *InstantiatedBase 3162 = CheckBaseSpecifier(Instantiation, 3163 Base.getSourceRange(), 3164 Base.isVirtual(), 3165 Base.getAccessSpecifierAsWritten(), 3166 BaseTypeLoc, 3167 SourceLocation())) 3168 InstantiatedBases.push_back(InstantiatedBase); 3169 else 3170 Invalid = true; 3171 } 3172 3173 continue; 3174 } 3175 3176 // The resulting base specifier will (still) be a pack expansion. 3177 EllipsisLoc = Base.getEllipsisLoc(); 3178 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); 3179 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), 3180 TemplateArgs, 3181 Base.getSourceRange().getBegin(), 3182 DeclarationName()); 3183 } else { 3184 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), 3185 TemplateArgs, 3186 Base.getSourceRange().getBegin(), 3187 DeclarationName()); 3188 } 3189 3190 if (!BaseTypeLoc) { 3191 Invalid = true; 3192 continue; 3193 } 3194 3195 if (CXXBaseSpecifier *InstantiatedBase 3196 = CheckBaseSpecifier(Instantiation, 3197 Base.getSourceRange(), 3198 Base.isVirtual(), 3199 Base.getAccessSpecifierAsWritten(), 3200 BaseTypeLoc, 3201 EllipsisLoc)) 3202 InstantiatedBases.push_back(InstantiatedBase); 3203 else 3204 Invalid = true; 3205 } 3206 3207 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases)) 3208 Invalid = true; 3209 3210 return Invalid; 3211 } 3212 3213 // Defined via #include from SemaTemplateInstantiateDecl.cpp 3214 namespace clang { 3215 namespace sema { 3216 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, 3217 const MultiLevelTemplateArgumentList &TemplateArgs); 3218 Attr *instantiateTemplateAttributeForDecl( 3219 const Attr *At, ASTContext &C, Sema &S, 3220 const MultiLevelTemplateArgumentList &TemplateArgs); 3221 } 3222 } 3223 3224 /// Instantiate the definition of a class from a given pattern. 3225 /// 3226 /// \param PointOfInstantiation The point of instantiation within the 3227 /// source code. 3228 /// 3229 /// \param Instantiation is the declaration whose definition is being 3230 /// instantiated. This will be either a class template specialization 3231 /// or a member class of a class template specialization. 3232 /// 3233 /// \param Pattern is the pattern from which the instantiation 3234 /// occurs. This will be either the declaration of a class template or 3235 /// the declaration of a member class of a class template. 3236 /// 3237 /// \param TemplateArgs The template arguments to be substituted into 3238 /// the pattern. 3239 /// 3240 /// \param TSK the kind of implicit or explicit instantiation to perform. 3241 /// 3242 /// \param Complain whether to complain if the class cannot be instantiated due 3243 /// to the lack of a definition. 3244 /// 3245 /// \returns true if an error occurred, false otherwise. 3246 bool 3247 Sema::InstantiateClass(SourceLocation PointOfInstantiation, 3248 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 3249 const MultiLevelTemplateArgumentList &TemplateArgs, 3250 TemplateSpecializationKind TSK, 3251 bool Complain) { 3252 CXXRecordDecl *PatternDef 3253 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 3254 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, 3255 Instantiation->getInstantiatedFromMemberClass(), 3256 Pattern, PatternDef, TSK, Complain)) 3257 return true; 3258 3259 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() { 3260 std::string Name; 3261 llvm::raw_string_ostream OS(Name); 3262 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(), 3263 /*Qualified=*/true); 3264 return Name; 3265 }); 3266 3267 Pattern = PatternDef; 3268 3269 // Record the point of instantiation. 3270 if (MemberSpecializationInfo *MSInfo 3271 = Instantiation->getMemberSpecializationInfo()) { 3272 MSInfo->setTemplateSpecializationKind(TSK); 3273 MSInfo->setPointOfInstantiation(PointOfInstantiation); 3274 } else if (ClassTemplateSpecializationDecl *Spec 3275 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) { 3276 Spec->setTemplateSpecializationKind(TSK); 3277 Spec->setPointOfInstantiation(PointOfInstantiation); 3278 } 3279 3280 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 3281 if (Inst.isInvalid()) 3282 return true; 3283 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller"); 3284 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), 3285 "instantiating class definition"); 3286 3287 // Enter the scope of this instantiation. We don't use 3288 // PushDeclContext because we don't have a scope. 3289 ContextRAII SavedContext(*this, Instantiation); 3290 EnterExpressionEvaluationContext EvalContext( 3291 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 3292 3293 // If this is an instantiation of a local class, merge this local 3294 // instantiation scope with the enclosing scope. Otherwise, every 3295 // instantiation of a class has its own local instantiation scope. 3296 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); 3297 LocalInstantiationScope Scope(*this, MergeWithParentScope); 3298 3299 // Some class state isn't processed immediately but delayed till class 3300 // instantiation completes. We may not be ready to handle any delayed state 3301 // already on the stack as it might correspond to a different class, so save 3302 // it now and put it back later. 3303 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this); 3304 3305 // Pull attributes from the pattern onto the instantiation. 3306 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 3307 3308 // Start the definition of this instantiation. 3309 Instantiation->startDefinition(); 3310 3311 // The instantiation is visible here, even if it was first declared in an 3312 // unimported module. 3313 Instantiation->setVisibleDespiteOwningModule(); 3314 3315 // FIXME: This loses the as-written tag kind for an explicit instantiation. 3316 Instantiation->setTagKind(Pattern->getTagKind()); 3317 3318 // Do substitution on the base class specifiers. 3319 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) 3320 Instantiation->setInvalidDecl(); 3321 3322 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 3323 Instantiator.setEvaluateConstraints(false); 3324 SmallVector<Decl*, 4> Fields; 3325 // Delay instantiation of late parsed attributes. 3326 LateInstantiatedAttrVec LateAttrs; 3327 Instantiator.enableLateAttributeInstantiation(&LateAttrs); 3328 3329 bool MightHaveConstexprVirtualFunctions = false; 3330 for (auto *Member : Pattern->decls()) { 3331 // Don't instantiate members not belonging in this semantic context. 3332 // e.g. for: 3333 // @code 3334 // template <int i> class A { 3335 // class B *g; 3336 // }; 3337 // @endcode 3338 // 'class B' has the template as lexical context but semantically it is 3339 // introduced in namespace scope. 3340 if (Member->getDeclContext() != Pattern) 3341 continue; 3342 3343 // BlockDecls can appear in a default-member-initializer. They must be the 3344 // child of a BlockExpr, so we only know how to instantiate them from there. 3345 // Similarly, lambda closure types are recreated when instantiating the 3346 // corresponding LambdaExpr. 3347 if (isa<BlockDecl>(Member) || 3348 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda())) 3349 continue; 3350 3351 if (Member->isInvalidDecl()) { 3352 Instantiation->setInvalidDecl(); 3353 continue; 3354 } 3355 3356 Decl *NewMember = Instantiator.Visit(Member); 3357 if (NewMember) { 3358 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) { 3359 Fields.push_back(Field); 3360 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) { 3361 // C++11 [temp.inst]p1: The implicit instantiation of a class template 3362 // specialization causes the implicit instantiation of the definitions 3363 // of unscoped member enumerations. 3364 // Record a point of instantiation for this implicit instantiation. 3365 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() && 3366 Enum->isCompleteDefinition()) { 3367 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo(); 3368 assert(MSInfo && "no spec info for member enum specialization"); 3369 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation); 3370 MSInfo->setPointOfInstantiation(PointOfInstantiation); 3371 } 3372 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) { 3373 if (SA->isFailed()) { 3374 // A static_assert failed. Bail out; instantiating this 3375 // class is probably not meaningful. 3376 Instantiation->setInvalidDecl(); 3377 break; 3378 } 3379 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) { 3380 if (MD->isConstexpr() && !MD->getFriendObjectKind() && 3381 (MD->isVirtualAsWritten() || Instantiation->getNumBases())) 3382 MightHaveConstexprVirtualFunctions = true; 3383 } 3384 3385 if (NewMember->isInvalidDecl()) 3386 Instantiation->setInvalidDecl(); 3387 } else { 3388 // FIXME: Eventually, a NULL return will mean that one of the 3389 // instantiations was a semantic disaster, and we'll want to mark the 3390 // declaration invalid. 3391 // For now, we expect to skip some members that we can't yet handle. 3392 } 3393 } 3394 3395 // Finish checking fields. 3396 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields, 3397 SourceLocation(), SourceLocation(), ParsedAttributesView()); 3398 CheckCompletedCXXClass(nullptr, Instantiation); 3399 3400 // Default arguments are parsed, if not instantiated. We can go instantiate 3401 // default arg exprs for default constructors if necessary now. Unless we're 3402 // parsing a class, in which case wait until that's finished. 3403 if (ParsingClassDepth == 0) 3404 ActOnFinishCXXNonNestedClass(); 3405 3406 // Instantiate late parsed attributes, and attach them to their decls. 3407 // See Sema::InstantiateAttrs 3408 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(), 3409 E = LateAttrs.end(); I != E; ++I) { 3410 assert(CurrentInstantiationScope == Instantiator.getStartingScope()); 3411 CurrentInstantiationScope = I->Scope; 3412 3413 // Allow 'this' within late-parsed attributes. 3414 auto *ND = cast<NamedDecl>(I->NewDecl); 3415 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); 3416 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), 3417 ND->isCXXInstanceMember()); 3418 3419 Attr *NewAttr = 3420 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs); 3421 if (NewAttr) 3422 I->NewDecl->addAttr(NewAttr); 3423 LocalInstantiationScope::deleteScopes(I->Scope, 3424 Instantiator.getStartingScope()); 3425 } 3426 Instantiator.disableLateAttributeInstantiation(); 3427 LateAttrs.clear(); 3428 3429 ActOnFinishDelayedMemberInitializers(Instantiation); 3430 3431 // FIXME: We should do something similar for explicit instantiations so they 3432 // end up in the right module. 3433 if (TSK == TSK_ImplicitInstantiation) { 3434 Instantiation->setLocation(Pattern->getLocation()); 3435 Instantiation->setLocStart(Pattern->getInnerLocStart()); 3436 Instantiation->setBraceRange(Pattern->getBraceRange()); 3437 } 3438 3439 if (!Instantiation->isInvalidDecl()) { 3440 // Perform any dependent diagnostics from the pattern. 3441 if (Pattern->isDependentContext()) 3442 PerformDependentDiagnostics(Pattern, TemplateArgs); 3443 3444 // Instantiate any out-of-line class template partial 3445 // specializations now. 3446 for (TemplateDeclInstantiator::delayed_partial_spec_iterator 3447 P = Instantiator.delayed_partial_spec_begin(), 3448 PEnd = Instantiator.delayed_partial_spec_end(); 3449 P != PEnd; ++P) { 3450 if (!Instantiator.InstantiateClassTemplatePartialSpecialization( 3451 P->first, P->second)) { 3452 Instantiation->setInvalidDecl(); 3453 break; 3454 } 3455 } 3456 3457 // Instantiate any out-of-line variable template partial 3458 // specializations now. 3459 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator 3460 P = Instantiator.delayed_var_partial_spec_begin(), 3461 PEnd = Instantiator.delayed_var_partial_spec_end(); 3462 P != PEnd; ++P) { 3463 if (!Instantiator.InstantiateVarTemplatePartialSpecialization( 3464 P->first, P->second)) { 3465 Instantiation->setInvalidDecl(); 3466 break; 3467 } 3468 } 3469 } 3470 3471 // Exit the scope of this instantiation. 3472 SavedContext.pop(); 3473 3474 if (!Instantiation->isInvalidDecl()) { 3475 // Always emit the vtable for an explicit instantiation definition 3476 // of a polymorphic class template specialization. Otherwise, eagerly 3477 // instantiate only constexpr virtual functions in preparation for their use 3478 // in constant evaluation. 3479 if (TSK == TSK_ExplicitInstantiationDefinition) 3480 MarkVTableUsed(PointOfInstantiation, Instantiation, true); 3481 else if (MightHaveConstexprVirtualFunctions) 3482 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation, 3483 /*ConstexprOnly*/ true); 3484 } 3485 3486 Consumer.HandleTagDeclDefinition(Instantiation); 3487 3488 return Instantiation->isInvalidDecl(); 3489 } 3490 3491 /// Instantiate the definition of an enum from a given pattern. 3492 /// 3493 /// \param PointOfInstantiation The point of instantiation within the 3494 /// source code. 3495 /// \param Instantiation is the declaration whose definition is being 3496 /// instantiated. This will be a member enumeration of a class 3497 /// temploid specialization, or a local enumeration within a 3498 /// function temploid specialization. 3499 /// \param Pattern The templated declaration from which the instantiation 3500 /// occurs. 3501 /// \param TemplateArgs The template arguments to be substituted into 3502 /// the pattern. 3503 /// \param TSK The kind of implicit or explicit instantiation to perform. 3504 /// 3505 /// \return \c true if an error occurred, \c false otherwise. 3506 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation, 3507 EnumDecl *Instantiation, EnumDecl *Pattern, 3508 const MultiLevelTemplateArgumentList &TemplateArgs, 3509 TemplateSpecializationKind TSK) { 3510 EnumDecl *PatternDef = Pattern->getDefinition(); 3511 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, 3512 Instantiation->getInstantiatedFromMemberEnum(), 3513 Pattern, PatternDef, TSK,/*Complain*/true)) 3514 return true; 3515 Pattern = PatternDef; 3516 3517 // Record the point of instantiation. 3518 if (MemberSpecializationInfo *MSInfo 3519 = Instantiation->getMemberSpecializationInfo()) { 3520 MSInfo->setTemplateSpecializationKind(TSK); 3521 MSInfo->setPointOfInstantiation(PointOfInstantiation); 3522 } 3523 3524 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 3525 if (Inst.isInvalid()) 3526 return true; 3527 if (Inst.isAlreadyInstantiating()) 3528 return false; 3529 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), 3530 "instantiating enum definition"); 3531 3532 // The instantiation is visible here, even if it was first declared in an 3533 // unimported module. 3534 Instantiation->setVisibleDespiteOwningModule(); 3535 3536 // Enter the scope of this instantiation. We don't use 3537 // PushDeclContext because we don't have a scope. 3538 ContextRAII SavedContext(*this, Instantiation); 3539 EnterExpressionEvaluationContext EvalContext( 3540 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 3541 3542 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true); 3543 3544 // Pull attributes from the pattern onto the instantiation. 3545 InstantiateAttrs(TemplateArgs, Pattern, Instantiation); 3546 3547 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); 3548 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern); 3549 3550 // Exit the scope of this instantiation. 3551 SavedContext.pop(); 3552 3553 return Instantiation->isInvalidDecl(); 3554 } 3555 3556 3557 /// Instantiate the definition of a field from the given pattern. 3558 /// 3559 /// \param PointOfInstantiation The point of instantiation within the 3560 /// source code. 3561 /// \param Instantiation is the declaration whose definition is being 3562 /// instantiated. This will be a class of a class temploid 3563 /// specialization, or a local enumeration within a function temploid 3564 /// specialization. 3565 /// \param Pattern The templated declaration from which the instantiation 3566 /// occurs. 3567 /// \param TemplateArgs The template arguments to be substituted into 3568 /// the pattern. 3569 /// 3570 /// \return \c true if an error occurred, \c false otherwise. 3571 bool Sema::InstantiateInClassInitializer( 3572 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 3573 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) { 3574 // If there is no initializer, we don't need to do anything. 3575 if (!Pattern->hasInClassInitializer()) 3576 return false; 3577 3578 assert(Instantiation->getInClassInitStyle() == 3579 Pattern->getInClassInitStyle() && 3580 "pattern and instantiation disagree about init style"); 3581 3582 // Error out if we haven't parsed the initializer of the pattern yet because 3583 // we are waiting for the closing brace of the outer class. 3584 Expr *OldInit = Pattern->getInClassInitializer(); 3585 if (!OldInit) { 3586 RecordDecl *PatternRD = Pattern->getParent(); 3587 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext(); 3588 Diag(PointOfInstantiation, 3589 diag::err_default_member_initializer_not_yet_parsed) 3590 << OutermostClass << Pattern; 3591 Diag(Pattern->getEndLoc(), 3592 diag::note_default_member_initializer_not_yet_parsed); 3593 Instantiation->setInvalidDecl(); 3594 return true; 3595 } 3596 3597 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 3598 if (Inst.isInvalid()) 3599 return true; 3600 if (Inst.isAlreadyInstantiating()) { 3601 // Error out if we hit an instantiation cycle for this initializer. 3602 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle) 3603 << Instantiation; 3604 return true; 3605 } 3606 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), 3607 "instantiating default member init"); 3608 3609 // Enter the scope of this instantiation. We don't use PushDeclContext because 3610 // we don't have a scope. 3611 ContextRAII SavedContext(*this, Instantiation->getParent()); 3612 EnterExpressionEvaluationContext EvalContext( 3613 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 3614 ExprEvalContexts.back().DelayedDefaultInitializationContext = { 3615 PointOfInstantiation, Instantiation, CurContext}; 3616 3617 LocalInstantiationScope Scope(*this, true); 3618 3619 // Instantiate the initializer. 3620 ActOnStartCXXInClassMemberInitializer(); 3621 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers()); 3622 3623 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs, 3624 /*CXXDirectInit=*/false); 3625 Expr *Init = NewInit.get(); 3626 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class"); 3627 ActOnFinishCXXInClassMemberInitializer( 3628 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init); 3629 3630 if (auto *L = getASTMutationListener()) 3631 L->DefaultMemberInitializerInstantiated(Instantiation); 3632 3633 // Return true if the in-class initializer is still missing. 3634 return !Instantiation->getInClassInitializer(); 3635 } 3636 3637 namespace { 3638 /// A partial specialization whose template arguments have matched 3639 /// a given template-id. 3640 struct PartialSpecMatchResult { 3641 ClassTemplatePartialSpecializationDecl *Partial; 3642 TemplateArgumentList *Args; 3643 }; 3644 } 3645 3646 bool Sema::usesPartialOrExplicitSpecialization( 3647 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) { 3648 if (ClassTemplateSpec->getTemplateSpecializationKind() == 3649 TSK_ExplicitSpecialization) 3650 return true; 3651 3652 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 3653 ClassTemplateSpec->getSpecializedTemplate() 3654 ->getPartialSpecializations(PartialSpecs); 3655 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 3656 TemplateDeductionInfo Info(Loc); 3657 if (!DeduceTemplateArguments(PartialSpecs[I], 3658 ClassTemplateSpec->getTemplateArgs(), Info)) 3659 return true; 3660 } 3661 3662 return false; 3663 } 3664 3665 /// Get the instantiation pattern to use to instantiate the definition of a 3666 /// given ClassTemplateSpecializationDecl (either the pattern of the primary 3667 /// template or of a partial specialization). 3668 static ActionResult<CXXRecordDecl *> 3669 getPatternForClassTemplateSpecialization( 3670 Sema &S, SourceLocation PointOfInstantiation, 3671 ClassTemplateSpecializationDecl *ClassTemplateSpec, 3672 TemplateSpecializationKind TSK) { 3673 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec); 3674 if (Inst.isInvalid()) 3675 return {/*Invalid=*/true}; 3676 if (Inst.isAlreadyInstantiating()) 3677 return {/*Invalid=*/false}; 3678 3679 llvm::PointerUnion<ClassTemplateDecl *, 3680 ClassTemplatePartialSpecializationDecl *> 3681 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); 3682 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) { 3683 // Find best matching specialization. 3684 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 3685 3686 // C++ [temp.class.spec.match]p1: 3687 // When a class template is used in a context that requires an 3688 // instantiation of the class, it is necessary to determine 3689 // whether the instantiation is to be generated using the primary 3690 // template or one of the partial specializations. This is done by 3691 // matching the template arguments of the class template 3692 // specialization with the template argument lists of the partial 3693 // specializations. 3694 typedef PartialSpecMatchResult MatchResult; 3695 SmallVector<MatchResult, 4> Matched; 3696 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 3697 Template->getPartialSpecializations(PartialSpecs); 3698 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); 3699 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 3700 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; 3701 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 3702 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments( 3703 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) { 3704 // Store the failed-deduction information for use in diagnostics, later. 3705 // TODO: Actually use the failed-deduction info? 3706 FailedCandidates.addCandidate().set( 3707 DeclAccessPair::make(Template, AS_public), Partial, 3708 MakeDeductionFailureInfo(S.Context, Result, Info)); 3709 (void)Result; 3710 } else { 3711 Matched.push_back(PartialSpecMatchResult()); 3712 Matched.back().Partial = Partial; 3713 Matched.back().Args = Info.takeCanonical(); 3714 } 3715 } 3716 3717 // If we're dealing with a member template where the template parameters 3718 // have been instantiated, this provides the original template parameters 3719 // from which the member template's parameters were instantiated. 3720 3721 if (Matched.size() >= 1) { 3722 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin(); 3723 if (Matched.size() == 1) { 3724 // -- If exactly one matching specialization is found, the 3725 // instantiation is generated from that specialization. 3726 // We don't need to do anything for this. 3727 } else { 3728 // -- If more than one matching specialization is found, the 3729 // partial order rules (14.5.4.2) are used to determine 3730 // whether one of the specializations is more specialized 3731 // than the others. If none of the specializations is more 3732 // specialized than all of the other matching 3733 // specializations, then the use of the class template is 3734 // ambiguous and the program is ill-formed. 3735 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1, 3736 PEnd = Matched.end(); 3737 P != PEnd; ++P) { 3738 if (S.getMoreSpecializedPartialSpecialization( 3739 P->Partial, Best->Partial, PointOfInstantiation) == 3740 P->Partial) 3741 Best = P; 3742 } 3743 3744 // Determine if the best partial specialization is more specialized than 3745 // the others. 3746 bool Ambiguous = false; 3747 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), 3748 PEnd = Matched.end(); 3749 P != PEnd; ++P) { 3750 if (P != Best && S.getMoreSpecializedPartialSpecialization( 3751 P->Partial, Best->Partial, 3752 PointOfInstantiation) != Best->Partial) { 3753 Ambiguous = true; 3754 break; 3755 } 3756 } 3757 3758 if (Ambiguous) { 3759 // Partial ordering did not produce a clear winner. Complain. 3760 Inst.Clear(); 3761 ClassTemplateSpec->setInvalidDecl(); 3762 S.Diag(PointOfInstantiation, 3763 diag::err_partial_spec_ordering_ambiguous) 3764 << ClassTemplateSpec; 3765 3766 // Print the matching partial specializations. 3767 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), 3768 PEnd = Matched.end(); 3769 P != PEnd; ++P) 3770 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match) 3771 << S.getTemplateArgumentBindingsText( 3772 P->Partial->getTemplateParameters(), *P->Args); 3773 3774 return {/*Invalid=*/true}; 3775 } 3776 } 3777 3778 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args); 3779 } else { 3780 // -- If no matches are found, the instantiation is generated 3781 // from the primary template. 3782 } 3783 } 3784 3785 CXXRecordDecl *Pattern = nullptr; 3786 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); 3787 if (auto *PartialSpec = 3788 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { 3789 // Instantiate using the best class template partial specialization. 3790 while (PartialSpec->getInstantiatedFromMember()) { 3791 // If we've found an explicit specialization of this class template, 3792 // stop here and use that as the pattern. 3793 if (PartialSpec->isMemberSpecialization()) 3794 break; 3795 3796 PartialSpec = PartialSpec->getInstantiatedFromMember(); 3797 } 3798 Pattern = PartialSpec; 3799 } else { 3800 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 3801 while (Template->getInstantiatedFromMemberTemplate()) { 3802 // If we've found an explicit specialization of this class template, 3803 // stop here and use that as the pattern. 3804 if (Template->isMemberSpecialization()) 3805 break; 3806 3807 Template = Template->getInstantiatedFromMemberTemplate(); 3808 } 3809 Pattern = Template->getTemplatedDecl(); 3810 } 3811 3812 return Pattern; 3813 } 3814 3815 bool Sema::InstantiateClassTemplateSpecialization( 3816 SourceLocation PointOfInstantiation, 3817 ClassTemplateSpecializationDecl *ClassTemplateSpec, 3818 TemplateSpecializationKind TSK, bool Complain) { 3819 // Perform the actual instantiation on the canonical declaration. 3820 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 3821 ClassTemplateSpec->getCanonicalDecl()); 3822 if (ClassTemplateSpec->isInvalidDecl()) 3823 return true; 3824 3825 ActionResult<CXXRecordDecl *> Pattern = 3826 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation, 3827 ClassTemplateSpec, TSK); 3828 if (!Pattern.isUsable()) 3829 return Pattern.isInvalid(); 3830 3831 return InstantiateClass( 3832 PointOfInstantiation, ClassTemplateSpec, Pattern.get(), 3833 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain); 3834 } 3835 3836 /// Instantiates the definitions of all of the member 3837 /// of the given class, which is an instantiation of a class template 3838 /// or a member class of a template. 3839 void 3840 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 3841 CXXRecordDecl *Instantiation, 3842 const MultiLevelTemplateArgumentList &TemplateArgs, 3843 TemplateSpecializationKind TSK) { 3844 // FIXME: We need to notify the ASTMutationListener that we did all of these 3845 // things, in case we have an explicit instantiation definition in a PCM, a 3846 // module, or preamble, and the declaration is in an imported AST. 3847 assert( 3848 (TSK == TSK_ExplicitInstantiationDefinition || 3849 TSK == TSK_ExplicitInstantiationDeclaration || 3850 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && 3851 "Unexpected template specialization kind!"); 3852 for (auto *D : Instantiation->decls()) { 3853 bool SuppressNew = false; 3854 if (auto *Function = dyn_cast<FunctionDecl>(D)) { 3855 if (FunctionDecl *Pattern = 3856 Function->getInstantiatedFromMemberFunction()) { 3857 3858 if (Function->isIneligibleOrNotSelected()) 3859 continue; 3860 3861 if (Function->getTrailingRequiresClause()) { 3862 ConstraintSatisfaction Satisfaction; 3863 if (CheckFunctionConstraints(Function, Satisfaction) || 3864 !Satisfaction.IsSatisfied) { 3865 continue; 3866 } 3867 } 3868 3869 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 3870 continue; 3871 3872 MemberSpecializationInfo *MSInfo = 3873 Function->getMemberSpecializationInfo(); 3874 assert(MSInfo && "No member specialization information?"); 3875 if (MSInfo->getTemplateSpecializationKind() 3876 == TSK_ExplicitSpecialization) 3877 continue; 3878 3879 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 3880 Function, 3881 MSInfo->getTemplateSpecializationKind(), 3882 MSInfo->getPointOfInstantiation(), 3883 SuppressNew) || 3884 SuppressNew) 3885 continue; 3886 3887 // C++11 [temp.explicit]p8: 3888 // An explicit instantiation definition that names a class template 3889 // specialization explicitly instantiates the class template 3890 // specialization and is only an explicit instantiation definition 3891 // of members whose definition is visible at the point of 3892 // instantiation. 3893 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined()) 3894 continue; 3895 3896 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); 3897 3898 if (Function->isDefined()) { 3899 // Let the ASTConsumer know that this function has been explicitly 3900 // instantiated now, and its linkage might have changed. 3901 Consumer.HandleTopLevelDecl(DeclGroupRef(Function)); 3902 } else if (TSK == TSK_ExplicitInstantiationDefinition) { 3903 InstantiateFunctionDefinition(PointOfInstantiation, Function); 3904 } else if (TSK == TSK_ImplicitInstantiation) { 3905 PendingLocalImplicitInstantiations.push_back( 3906 std::make_pair(Function, PointOfInstantiation)); 3907 } 3908 } 3909 } else if (auto *Var = dyn_cast<VarDecl>(D)) { 3910 if (isa<VarTemplateSpecializationDecl>(Var)) 3911 continue; 3912 3913 if (Var->isStaticDataMember()) { 3914 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 3915 continue; 3916 3917 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 3918 assert(MSInfo && "No member specialization information?"); 3919 if (MSInfo->getTemplateSpecializationKind() 3920 == TSK_ExplicitSpecialization) 3921 continue; 3922 3923 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 3924 Var, 3925 MSInfo->getTemplateSpecializationKind(), 3926 MSInfo->getPointOfInstantiation(), 3927 SuppressNew) || 3928 SuppressNew) 3929 continue; 3930 3931 if (TSK == TSK_ExplicitInstantiationDefinition) { 3932 // C++0x [temp.explicit]p8: 3933 // An explicit instantiation definition that names a class template 3934 // specialization explicitly instantiates the class template 3935 // specialization and is only an explicit instantiation definition 3936 // of members whose definition is visible at the point of 3937 // instantiation. 3938 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition()) 3939 continue; 3940 3941 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 3942 InstantiateVariableDefinition(PointOfInstantiation, Var); 3943 } else { 3944 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 3945 } 3946 } 3947 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) { 3948 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 3949 continue; 3950 3951 // Always skip the injected-class-name, along with any 3952 // redeclarations of nested classes, since both would cause us 3953 // to try to instantiate the members of a class twice. 3954 // Skip closure types; they'll get instantiated when we instantiate 3955 // the corresponding lambda-expression. 3956 if (Record->isInjectedClassName() || Record->getPreviousDecl() || 3957 Record->isLambda()) 3958 continue; 3959 3960 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); 3961 assert(MSInfo && "No member specialization information?"); 3962 3963 if (MSInfo->getTemplateSpecializationKind() 3964 == TSK_ExplicitSpecialization) 3965 continue; 3966 3967 if (Context.getTargetInfo().getTriple().isOSWindows() && 3968 TSK == TSK_ExplicitInstantiationDeclaration) { 3969 // On Windows, explicit instantiation decl of the outer class doesn't 3970 // affect the inner class. Typically extern template declarations are 3971 // used in combination with dll import/export annotations, but those 3972 // are not propagated from the outer class templates to inner classes. 3973 // Therefore, do not instantiate inner classes on this platform, so 3974 // that users don't end up with undefined symbols during linking. 3975 continue; 3976 } 3977 3978 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, 3979 Record, 3980 MSInfo->getTemplateSpecializationKind(), 3981 MSInfo->getPointOfInstantiation(), 3982 SuppressNew) || 3983 SuppressNew) 3984 continue; 3985 3986 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 3987 assert(Pattern && "Missing instantiated-from-template information"); 3988 3989 if (!Record->getDefinition()) { 3990 if (!Pattern->getDefinition()) { 3991 // C++0x [temp.explicit]p8: 3992 // An explicit instantiation definition that names a class template 3993 // specialization explicitly instantiates the class template 3994 // specialization and is only an explicit instantiation definition 3995 // of members whose definition is visible at the point of 3996 // instantiation. 3997 if (TSK == TSK_ExplicitInstantiationDeclaration) { 3998 MSInfo->setTemplateSpecializationKind(TSK); 3999 MSInfo->setPointOfInstantiation(PointOfInstantiation); 4000 } 4001 4002 continue; 4003 } 4004 4005 InstantiateClass(PointOfInstantiation, Record, Pattern, 4006 TemplateArgs, 4007 TSK); 4008 } else { 4009 if (TSK == TSK_ExplicitInstantiationDefinition && 4010 Record->getTemplateSpecializationKind() == 4011 TSK_ExplicitInstantiationDeclaration) { 4012 Record->setTemplateSpecializationKind(TSK); 4013 MarkVTableUsed(PointOfInstantiation, Record, true); 4014 } 4015 } 4016 4017 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 4018 if (Pattern) 4019 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, 4020 TSK); 4021 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) { 4022 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); 4023 assert(MSInfo && "No member specialization information?"); 4024 4025 if (MSInfo->getTemplateSpecializationKind() 4026 == TSK_ExplicitSpecialization) 4027 continue; 4028 4029 if (CheckSpecializationInstantiationRedecl( 4030 PointOfInstantiation, TSK, Enum, 4031 MSInfo->getTemplateSpecializationKind(), 4032 MSInfo->getPointOfInstantiation(), SuppressNew) || 4033 SuppressNew) 4034 continue; 4035 4036 if (Enum->getDefinition()) 4037 continue; 4038 4039 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern(); 4040 assert(Pattern && "Missing instantiated-from-template information"); 4041 4042 if (TSK == TSK_ExplicitInstantiationDefinition) { 4043 if (!Pattern->getDefinition()) 4044 continue; 4045 4046 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK); 4047 } else { 4048 MSInfo->setTemplateSpecializationKind(TSK); 4049 MSInfo->setPointOfInstantiation(PointOfInstantiation); 4050 } 4051 } else if (auto *Field = dyn_cast<FieldDecl>(D)) { 4052 // No need to instantiate in-class initializers during explicit 4053 // instantiation. 4054 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) { 4055 CXXRecordDecl *ClassPattern = 4056 Instantiation->getTemplateInstantiationPattern(); 4057 DeclContext::lookup_result Lookup = 4058 ClassPattern->lookup(Field->getDeclName()); 4059 FieldDecl *Pattern = Lookup.find_first<FieldDecl>(); 4060 assert(Pattern); 4061 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern, 4062 TemplateArgs); 4063 } 4064 } 4065 } 4066 } 4067 4068 /// Instantiate the definitions of all of the members of the 4069 /// given class template specialization, which was named as part of an 4070 /// explicit instantiation. 4071 void 4072 Sema::InstantiateClassTemplateSpecializationMembers( 4073 SourceLocation PointOfInstantiation, 4074 ClassTemplateSpecializationDecl *ClassTemplateSpec, 4075 TemplateSpecializationKind TSK) { 4076 // C++0x [temp.explicit]p7: 4077 // An explicit instantiation that names a class template 4078 // specialization is an explicit instantion of the same kind 4079 // (declaration or definition) of each of its members (not 4080 // including members inherited from base classes) that has not 4081 // been previously explicitly specialized in the translation unit 4082 // containing the explicit instantiation, except as described 4083 // below. 4084 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 4085 getTemplateInstantiationArgs(ClassTemplateSpec), 4086 TSK); 4087 } 4088 4089 StmtResult 4090 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { 4091 if (!S) 4092 return S; 4093 4094 TemplateInstantiator Instantiator(*this, TemplateArgs, 4095 SourceLocation(), 4096 DeclarationName()); 4097 return Instantiator.TransformStmt(S); 4098 } 4099 4100 bool Sema::SubstTemplateArguments( 4101 ArrayRef<TemplateArgumentLoc> Args, 4102 const MultiLevelTemplateArgumentList &TemplateArgs, 4103 TemplateArgumentListInfo &Out) { 4104 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 4105 DeclarationName()); 4106 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out); 4107 } 4108 4109 ExprResult 4110 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 4111 if (!E) 4112 return E; 4113 4114 TemplateInstantiator Instantiator(*this, TemplateArgs, 4115 SourceLocation(), 4116 DeclarationName()); 4117 return Instantiator.TransformExpr(E); 4118 } 4119 4120 ExprResult 4121 Sema::SubstConstraintExpr(Expr *E, 4122 const MultiLevelTemplateArgumentList &TemplateArgs) { 4123 // FIXME: should call SubstExpr directly if this function is equivalent or 4124 // should it be different? 4125 return SubstExpr(E, TemplateArgs); 4126 } 4127 4128 ExprResult Sema::SubstConstraintExprWithoutSatisfaction( 4129 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 4130 if (!E) 4131 return E; 4132 4133 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 4134 DeclarationName()); 4135 Instantiator.setEvaluateConstraints(false); 4136 return Instantiator.TransformExpr(E); 4137 } 4138 4139 ExprResult Sema::SubstInitializer(Expr *Init, 4140 const MultiLevelTemplateArgumentList &TemplateArgs, 4141 bool CXXDirectInit) { 4142 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 4143 DeclarationName()); 4144 return Instantiator.TransformInitializer(Init, CXXDirectInit); 4145 } 4146 4147 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, 4148 const MultiLevelTemplateArgumentList &TemplateArgs, 4149 SmallVectorImpl<Expr *> &Outputs) { 4150 if (Exprs.empty()) 4151 return false; 4152 4153 TemplateInstantiator Instantiator(*this, TemplateArgs, 4154 SourceLocation(), 4155 DeclarationName()); 4156 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(), 4157 IsCall, Outputs); 4158 } 4159 4160 NestedNameSpecifierLoc 4161 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 4162 const MultiLevelTemplateArgumentList &TemplateArgs) { 4163 if (!NNS) 4164 return NestedNameSpecifierLoc(); 4165 4166 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), 4167 DeclarationName()); 4168 return Instantiator.TransformNestedNameSpecifierLoc(NNS); 4169 } 4170 4171 /// Do template substitution on declaration name info. 4172 DeclarationNameInfo 4173 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 4174 const MultiLevelTemplateArgumentList &TemplateArgs) { 4175 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(), 4176 NameInfo.getName()); 4177 return Instantiator.TransformDeclarationNameInfo(NameInfo); 4178 } 4179 4180 TemplateName 4181 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, 4182 TemplateName Name, SourceLocation Loc, 4183 const MultiLevelTemplateArgumentList &TemplateArgs) { 4184 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 4185 DeclarationName()); 4186 CXXScopeSpec SS; 4187 SS.Adopt(QualifierLoc); 4188 return Instantiator.TransformTemplateName(SS, Name, Loc); 4189 } 4190 4191 static const Decl *getCanonicalParmVarDecl(const Decl *D) { 4192 // When storing ParmVarDecls in the local instantiation scope, we always 4193 // want to use the ParmVarDecl from the canonical function declaration, 4194 // since the map is then valid for any redeclaration or definition of that 4195 // function. 4196 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) { 4197 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 4198 unsigned i = PV->getFunctionScopeIndex(); 4199 // This parameter might be from a freestanding function type within the 4200 // function and isn't necessarily referring to one of FD's parameters. 4201 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV) 4202 return FD->getCanonicalDecl()->getParamDecl(i); 4203 } 4204 } 4205 return D; 4206 } 4207 4208 4209 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * 4210 LocalInstantiationScope::findInstantiationOf(const Decl *D) { 4211 D = getCanonicalParmVarDecl(D); 4212 for (LocalInstantiationScope *Current = this; Current; 4213 Current = Current->Outer) { 4214 4215 // Check if we found something within this scope. 4216 const Decl *CheckD = D; 4217 do { 4218 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD); 4219 if (Found != Current->LocalDecls.end()) 4220 return &Found->second; 4221 4222 // If this is a tag declaration, it's possible that we need to look for 4223 // a previous declaration. 4224 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD)) 4225 CheckD = Tag->getPreviousDecl(); 4226 else 4227 CheckD = nullptr; 4228 } while (CheckD); 4229 4230 // If we aren't combined with our outer scope, we're done. 4231 if (!Current->CombineWithOuterScope) 4232 break; 4233 } 4234 4235 // If we're performing a partial substitution during template argument 4236 // deduction, we may not have values for template parameters yet. 4237 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 4238 isa<TemplateTemplateParmDecl>(D)) 4239 return nullptr; 4240 4241 // Local types referenced prior to definition may require instantiation. 4242 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 4243 if (RD->isLocalClass()) 4244 return nullptr; 4245 4246 // Enumeration types referenced prior to definition may appear as a result of 4247 // error recovery. 4248 if (isa<EnumDecl>(D)) 4249 return nullptr; 4250 4251 // Materialized typedefs/type alias for implicit deduction guides may require 4252 // instantiation. 4253 if (isa<TypedefNameDecl>(D) && 4254 isa<CXXDeductionGuideDecl>(D->getDeclContext())) 4255 return nullptr; 4256 4257 // If we didn't find the decl, then we either have a sema bug, or we have a 4258 // forward reference to a label declaration. Return null to indicate that 4259 // we have an uninstantiated label. 4260 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope"); 4261 return nullptr; 4262 } 4263 4264 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) { 4265 D = getCanonicalParmVarDecl(D); 4266 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 4267 if (Stored.isNull()) { 4268 #ifndef NDEBUG 4269 // It should not be present in any surrounding scope either. 4270 LocalInstantiationScope *Current = this; 4271 while (Current->CombineWithOuterScope && Current->Outer) { 4272 Current = Current->Outer; 4273 assert(!Current->LocalDecls.contains(D) && 4274 "Instantiated local in inner and outer scopes"); 4275 } 4276 #endif 4277 Stored = Inst; 4278 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) { 4279 Pack->push_back(cast<VarDecl>(Inst)); 4280 } else { 4281 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local"); 4282 } 4283 } 4284 4285 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, 4286 VarDecl *Inst) { 4287 D = getCanonicalParmVarDecl(D); 4288 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>(); 4289 Pack->push_back(Inst); 4290 } 4291 4292 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { 4293 #ifndef NDEBUG 4294 // This should be the first time we've been told about this decl. 4295 for (LocalInstantiationScope *Current = this; 4296 Current && Current->CombineWithOuterScope; Current = Current->Outer) 4297 assert(!Current->LocalDecls.contains(D) && 4298 "Creating local pack after instantiation of local"); 4299 #endif 4300 4301 D = getCanonicalParmVarDecl(D); 4302 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; 4303 DeclArgumentPack *Pack = new DeclArgumentPack; 4304 Stored = Pack; 4305 ArgumentPacks.push_back(Pack); 4306 } 4307 4308 bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) { 4309 for (DeclArgumentPack *Pack : ArgumentPacks) 4310 if (llvm::is_contained(*Pack, D)) 4311 return true; 4312 return false; 4313 } 4314 4315 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, 4316 const TemplateArgument *ExplicitArgs, 4317 unsigned NumExplicitArgs) { 4318 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && 4319 "Already have a partially-substituted pack"); 4320 assert((!PartiallySubstitutedPack 4321 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && 4322 "Wrong number of arguments in partially-substituted pack"); 4323 PartiallySubstitutedPack = Pack; 4324 ArgsInPartiallySubstitutedPack = ExplicitArgs; 4325 NumArgsInPartiallySubstitutedPack = NumExplicitArgs; 4326 } 4327 4328 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( 4329 const TemplateArgument **ExplicitArgs, 4330 unsigned *NumExplicitArgs) const { 4331 if (ExplicitArgs) 4332 *ExplicitArgs = nullptr; 4333 if (NumExplicitArgs) 4334 *NumExplicitArgs = 0; 4335 4336 for (const LocalInstantiationScope *Current = this; Current; 4337 Current = Current->Outer) { 4338 if (Current->PartiallySubstitutedPack) { 4339 if (ExplicitArgs) 4340 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; 4341 if (NumExplicitArgs) 4342 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; 4343 4344 return Current->PartiallySubstitutedPack; 4345 } 4346 4347 if (!Current->CombineWithOuterScope) 4348 break; 4349 } 4350 4351 return nullptr; 4352 } 4353