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