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