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