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