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