SemaTemplateInstantiateDecl.cpp revision 895162da2d52f4243f61081d7436de66af4503fc
1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations. 10// 11//===----------------------------------------------------------------------===/ 12#include "Sema.h" 13#include "Lookup.h" 14#include "clang/AST/ASTConsumer.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/DeclTemplate.h" 17#include "clang/AST/DeclVisitor.h" 18#include "clang/AST/DependentDiagnostic.h" 19#include "clang/AST/Expr.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/AST/TypeLoc.h" 22#include "clang/Basic/PrettyStackTrace.h" 23#include "clang/Lex/Preprocessor.h" 24 25using namespace clang; 26 27namespace { 28 class TemplateDeclInstantiator 29 : public DeclVisitor<TemplateDeclInstantiator, Decl *> { 30 Sema &SemaRef; 31 DeclContext *Owner; 32 const MultiLevelTemplateArgumentList &TemplateArgs; 33 34 void InstantiateAttrs(Decl *Tmpl, Decl *New); 35 36 public: 37 typedef Sema::OwningExprResult OwningExprResult; 38 39 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, 40 const MultiLevelTemplateArgumentList &TemplateArgs) 41 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { } 42 43 // FIXME: Once we get closer to completion, replace these manually-written 44 // declarations with automatically-generated ones from 45 // clang/AST/DeclNodes.def. 46 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); 47 Decl *VisitNamespaceDecl(NamespaceDecl *D); 48 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 49 Decl *VisitTypedefDecl(TypedefDecl *D); 50 Decl *VisitVarDecl(VarDecl *D); 51 Decl *VisitFieldDecl(FieldDecl *D); 52 Decl *VisitStaticAssertDecl(StaticAssertDecl *D); 53 Decl *VisitEnumDecl(EnumDecl *D); 54 Decl *VisitEnumConstantDecl(EnumConstantDecl *D); 55 Decl *VisitFriendDecl(FriendDecl *D); 56 Decl *VisitFunctionDecl(FunctionDecl *D, 57 TemplateParameterList *TemplateParams = 0); 58 Decl *VisitCXXRecordDecl(CXXRecordDecl *D); 59 Decl *VisitCXXMethodDecl(CXXMethodDecl *D, 60 TemplateParameterList *TemplateParams = 0); 61 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 62 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 63 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 64 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 65 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D); 66 Decl *VisitClassTemplatePartialSpecializationDecl( 67 ClassTemplatePartialSpecializationDecl *D); 68 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 69 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 70 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 71 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 72 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 73 Decl *VisitUsingDecl(UsingDecl *D); 74 Decl *VisitUsingShadowDecl(UsingShadowDecl *D); 75 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 76 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 77 78 // Base case. FIXME: Remove once we can instantiate everything. 79 Decl *VisitDecl(Decl *D) { 80 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 81 Diagnostic::Error, 82 "cannot instantiate %0 yet"); 83 SemaRef.Diag(D->getLocation(), DiagID) 84 << D->getDeclKindName(); 85 86 return 0; 87 } 88 89 const LangOptions &getLangOptions() { 90 return SemaRef.getLangOptions(); 91 } 92 93 // Helper functions for instantiating methods. 94 TypeSourceInfo *SubstFunctionType(FunctionDecl *D, 95 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 96 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl); 97 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 98 99 TemplateParameterList * 100 SubstTemplateParams(TemplateParameterList *List); 101 102 bool SubstQualifier(const DeclaratorDecl *OldDecl, 103 DeclaratorDecl *NewDecl); 104 bool SubstQualifier(const TagDecl *OldDecl, 105 TagDecl *NewDecl); 106 107 bool InstantiateClassTemplatePartialSpecialization( 108 ClassTemplateDecl *ClassTemplate, 109 ClassTemplatePartialSpecializationDecl *PartialSpec); 110 }; 111} 112 113bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 114 DeclaratorDecl *NewDecl) { 115 NestedNameSpecifier *OldQual = OldDecl->getQualifier(); 116 if (!OldQual) return false; 117 118 SourceRange QualRange = OldDecl->getQualifierRange(); 119 120 NestedNameSpecifier *NewQual 121 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs); 122 if (!NewQual) 123 return true; 124 125 NewDecl->setQualifierInfo(NewQual, QualRange); 126 return false; 127} 128 129bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 130 TagDecl *NewDecl) { 131 NestedNameSpecifier *OldQual = OldDecl->getQualifier(); 132 if (!OldQual) return false; 133 134 SourceRange QualRange = OldDecl->getQualifierRange(); 135 136 NestedNameSpecifier *NewQual 137 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs); 138 if (!NewQual) 139 return true; 140 141 NewDecl->setQualifierInfo(NewQual, QualRange); 142 return false; 143} 144 145// FIXME: Is this too simple? 146void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) { 147 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr; 148 TmplAttr = TmplAttr->getNext()) { 149 150 // FIXME: Is cloning correct for all attributes? 151 Attr *NewAttr = TmplAttr->clone(SemaRef.Context); 152 153 New->addAttr(NewAttr); 154 } 155} 156 157Decl * 158TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 159 assert(false && "Translation units cannot be instantiated"); 160 return D; 161} 162 163Decl * 164TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 165 assert(false && "Namespaces cannot be instantiated"); 166 return D; 167} 168 169Decl * 170TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 171 NamespaceAliasDecl *Inst 172 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 173 D->getNamespaceLoc(), 174 D->getAliasLoc(), 175 D->getNamespace()->getIdentifier(), 176 D->getQualifierRange(), 177 D->getQualifier(), 178 D->getTargetNameLoc(), 179 D->getNamespace()); 180 Owner->addDecl(Inst); 181 return Inst; 182} 183 184Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 185 bool Invalid = false; 186 TypeSourceInfo *DI = D->getTypeSourceInfo(); 187 if (DI->getType()->isDependentType()) { 188 DI = SemaRef.SubstType(DI, TemplateArgs, 189 D->getLocation(), D->getDeclName()); 190 if (!DI) { 191 Invalid = true; 192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 193 } 194 } 195 196 // Create the new typedef 197 TypedefDecl *Typedef 198 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 199 D->getIdentifier(), DI); 200 if (Invalid) 201 Typedef->setInvalidDecl(); 202 203 if (const TagType *TT = DI->getType()->getAs<TagType>()) { 204 TagDecl *TD = TT->getDecl(); 205 206 // If the TagDecl that the TypedefDecl points to is an anonymous decl 207 // keep track of the TypedefDecl. 208 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 209 TD->setTypedefForAnonDecl(Typedef); 210 } 211 212 if (TypedefDecl *Prev = D->getPreviousDeclaration()) { 213 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 214 TemplateArgs); 215 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev)); 216 } 217 218 219 Typedef->setAccess(D->getAccess()); 220 Owner->addDecl(Typedef); 221 222 return Typedef; 223} 224 225/// \brief Instantiate the arguments provided as part of initialization. 226/// 227/// \returns true if an error occurred, false otherwise. 228static bool InstantiateInitializationArguments(Sema &SemaRef, 229 Expr **Args, unsigned NumArgs, 230 const MultiLevelTemplateArgumentList &TemplateArgs, 231 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs, 232 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) { 233 for (unsigned I = 0; I != NumArgs; ++I) { 234 // When we hit the first defaulted argument, break out of the loop: 235 // we don't pass those default arguments on. 236 if (Args[I]->isDefaultArgument()) 237 break; 238 239 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs); 240 if (Arg.isInvalid()) 241 return true; 242 243 Expr *ArgExpr = (Expr *)Arg.get(); 244 InitArgs.push_back(Arg.release()); 245 246 // FIXME: We're faking all of the comma locations. Do we need them? 247 FakeCommaLocs.push_back( 248 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd())); 249 } 250 251 return false; 252} 253 254/// \brief Instantiate an initializer, breaking it into separate 255/// initialization arguments. 256/// 257/// \param S The semantic analysis object. 258/// 259/// \param Init The initializer to instantiate. 260/// 261/// \param TemplateArgs Template arguments to be substituted into the 262/// initializer. 263/// 264/// \param NewArgs Will be filled in with the instantiation arguments. 265/// 266/// \returns true if an error occurred, false otherwise 267static bool InstantiateInitializer(Sema &S, Expr *Init, 268 const MultiLevelTemplateArgumentList &TemplateArgs, 269 SourceLocation &LParenLoc, 270 llvm::SmallVector<SourceLocation, 4> &CommaLocs, 271 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs, 272 SourceLocation &RParenLoc) { 273 NewArgs.clear(); 274 LParenLoc = SourceLocation(); 275 RParenLoc = SourceLocation(); 276 277 if (!Init) 278 return false; 279 280 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init)) 281 Init = ExprTemp->getSubExpr(); 282 283 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init)) 284 Init = Binder->getSubExpr(); 285 286 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init)) 287 Init = ICE->getSubExprAsWritten(); 288 289 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 290 LParenLoc = ParenList->getLParenLoc(); 291 RParenLoc = ParenList->getRParenLoc(); 292 return InstantiateInitializationArguments(S, ParenList->getExprs(), 293 ParenList->getNumExprs(), 294 TemplateArgs, CommaLocs, 295 NewArgs); 296 } 297 298 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) { 299 if (!isa<CXXTemporaryObjectExpr>(Construct)) { 300 if (InstantiateInitializationArguments(S, 301 Construct->getArgs(), 302 Construct->getNumArgs(), 303 TemplateArgs, 304 CommaLocs, NewArgs)) 305 return true; 306 307 // FIXME: Fake locations! 308 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart()); 309 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back(); 310 return false; 311 } 312 } 313 314 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs); 315 if (Result.isInvalid()) 316 return true; 317 318 NewArgs.push_back(Result.takeAs<Expr>()); 319 return false; 320} 321 322Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 323 // Do substitution on the type of the declaration 324 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 325 TemplateArgs, 326 D->getTypeSpecStartLoc(), 327 D->getDeclName()); 328 if (!DI) 329 return 0; 330 331 // Build the instantiated declaration 332 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 333 D->getLocation(), D->getIdentifier(), 334 DI->getType(), DI, 335 D->getStorageClass(), 336 D->getStorageClassAsWritten()); 337 Var->setThreadSpecified(D->isThreadSpecified()); 338 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 339 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 340 341 // Substitute the nested name specifier, if any. 342 if (SubstQualifier(D, Var)) 343 return 0; 344 345 // If we are instantiating a static data member defined 346 // out-of-line, the instantiation will have the same lexical 347 // context (which will be a namespace scope) as the template. 348 if (D->isOutOfLine()) 349 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 350 351 Var->setAccess(D->getAccess()); 352 353 // FIXME: In theory, we could have a previous declaration for variables that 354 // are not static data members. 355 bool Redeclaration = false; 356 // FIXME: having to fake up a LookupResult is dumb. 357 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(), 358 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 359 if (D->isStaticDataMember()) 360 SemaRef.LookupQualifiedName(Previous, Owner, false); 361 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration); 362 363 if (D->isOutOfLine()) { 364 D->getLexicalDeclContext()->addDecl(Var); 365 Owner->makeDeclVisibleInContext(Var); 366 } else { 367 Owner->addDecl(Var); 368 } 369 370 // Link instantiations of static data members back to the template from 371 // which they were instantiated. 372 if (Var->isStaticDataMember()) 373 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 374 TSK_ImplicitInstantiation); 375 376 if (Var->getAnyInitializer()) { 377 // We already have an initializer in the class. 378 } else if (D->getInit()) { 379 if (Var->isStaticDataMember() && !D->isOutOfLine()) 380 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated); 381 else 382 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 383 384 // Instantiate the initializer. 385 SourceLocation LParenLoc, RParenLoc; 386 llvm::SmallVector<SourceLocation, 4> CommaLocs; 387 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef); 388 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc, 389 CommaLocs, InitArgs, RParenLoc)) { 390 // Attach the initializer to the declaration. 391 if (D->hasCXXDirectInitializer()) { 392 // Add the direct initializer to the declaration. 393 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var), 394 LParenLoc, 395 move_arg(InitArgs), 396 CommaLocs.data(), 397 RParenLoc); 398 } else if (InitArgs.size() == 1) { 399 Expr *Init = (Expr*)(InitArgs.take()[0]); 400 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), 401 SemaRef.Owned(Init), 402 false); 403 } else { 404 assert(InitArgs.size() == 0); 405 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 406 } 407 } else { 408 // FIXME: Not too happy about invalidating the declaration 409 // because of a bogus initializer. 410 Var->setInvalidDecl(); 411 } 412 413 SemaRef.PopExpressionEvaluationContext(); 414 } else if (!Var->isStaticDataMember() || Var->isOutOfLine()) 415 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 416 417 return Var; 418} 419 420Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 421 bool Invalid = false; 422 TypeSourceInfo *DI = D->getTypeSourceInfo(); 423 if (DI->getType()->isDependentType()) { 424 DI = SemaRef.SubstType(DI, TemplateArgs, 425 D->getLocation(), D->getDeclName()); 426 if (!DI) { 427 DI = D->getTypeSourceInfo(); 428 Invalid = true; 429 } else if (DI->getType()->isFunctionType()) { 430 // C++ [temp.arg.type]p3: 431 // If a declaration acquires a function type through a type 432 // dependent on a template-parameter and this causes a 433 // declaration that does not use the syntactic form of a 434 // function declarator to have function type, the program is 435 // ill-formed. 436 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 437 << DI->getType(); 438 Invalid = true; 439 } 440 } 441 442 Expr *BitWidth = D->getBitWidth(); 443 if (Invalid) 444 BitWidth = 0; 445 else if (BitWidth) { 446 // The bit-width expression is not potentially evaluated. 447 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 448 449 OwningExprResult InstantiatedBitWidth 450 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 451 if (InstantiatedBitWidth.isInvalid()) { 452 Invalid = true; 453 BitWidth = 0; 454 } else 455 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 456 } 457 458 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 459 DI->getType(), DI, 460 cast<RecordDecl>(Owner), 461 D->getLocation(), 462 D->isMutable(), 463 BitWidth, 464 D->getTypeSpecStartLoc(), 465 D->getAccess(), 466 0); 467 if (!Field) { 468 cast<Decl>(Owner)->setInvalidDecl(); 469 return 0; 470 } 471 472 InstantiateAttrs(D, Field); 473 474 if (Invalid) 475 Field->setInvalidDecl(); 476 477 if (!Field->getDeclName()) { 478 // Keep track of where this decl came from. 479 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 480 } 481 482 Field->setImplicit(D->isImplicit()); 483 Field->setAccess(D->getAccess()); 484 Owner->addDecl(Field); 485 486 return Field; 487} 488 489Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 490 // Handle friend type expressions by simply substituting template 491 // parameters into the pattern type and checking the result. 492 if (TypeSourceInfo *Ty = D->getFriendType()) { 493 TypeSourceInfo *InstTy = 494 SemaRef.SubstType(Ty, TemplateArgs, 495 D->getLocation(), DeclarationName()); 496 if (!InstTy) 497 return 0; 498 499 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy); 500 if (!FD) 501 return 0; 502 503 FD->setAccess(AS_public); 504 Owner->addDecl(FD); 505 return FD; 506 } 507 508 NamedDecl *ND = D->getFriendDecl(); 509 assert(ND && "friend decl must be a decl or a type!"); 510 511 // All of the Visit implementations for the various potential friend 512 // declarations have to be carefully written to work for friend 513 // objects, with the most important detail being that the target 514 // decl should almost certainly not be placed in Owner. 515 Decl *NewND = Visit(ND); 516 if (!NewND) return 0; 517 518 FriendDecl *FD = 519 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 520 cast<NamedDecl>(NewND), D->getFriendLoc()); 521 FD->setAccess(AS_public); 522 Owner->addDecl(FD); 523 return FD; 524} 525 526Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 527 Expr *AssertExpr = D->getAssertExpr(); 528 529 // The expression in a static assertion is not potentially evaluated. 530 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 531 532 OwningExprResult InstantiatedAssertExpr 533 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 534 if (InstantiatedAssertExpr.isInvalid()) 535 return 0; 536 537 OwningExprResult Message(SemaRef, D->getMessage()); 538 D->getMessage()->Retain(); 539 Decl *StaticAssert 540 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 541 move(InstantiatedAssertExpr), 542 move(Message)).getAs<Decl>(); 543 return StaticAssert; 544} 545 546Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 547 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 548 D->getLocation(), D->getIdentifier(), 549 D->getTagKeywordLoc(), 550 /*PrevDecl=*/0); 551 Enum->setInstantiationOfMemberEnum(D); 552 Enum->setAccess(D->getAccess()); 553 if (SubstQualifier(D, Enum)) return 0; 554 Owner->addDecl(Enum); 555 Enum->startDefinition(); 556 557 if (D->getDeclContext()->isFunctionOrMethod()) 558 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 559 560 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators; 561 562 EnumConstantDecl *LastEnumConst = 0; 563 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 564 ECEnd = D->enumerator_end(); 565 EC != ECEnd; ++EC) { 566 // The specified value for the enumerator. 567 OwningExprResult Value = SemaRef.Owned((Expr *)0); 568 if (Expr *UninstValue = EC->getInitExpr()) { 569 // The enumerator's value expression is not potentially evaluated. 570 EnterExpressionEvaluationContext Unevaluated(SemaRef, 571 Action::Unevaluated); 572 573 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 574 } 575 576 // Drop the initial value and continue. 577 bool isInvalid = false; 578 if (Value.isInvalid()) { 579 Value = SemaRef.Owned((Expr *)0); 580 isInvalid = true; 581 } 582 583 EnumConstantDecl *EnumConst 584 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 585 EC->getLocation(), EC->getIdentifier(), 586 move(Value)); 587 588 if (isInvalid) { 589 if (EnumConst) 590 EnumConst->setInvalidDecl(); 591 Enum->setInvalidDecl(); 592 } 593 594 if (EnumConst) { 595 EnumConst->setAccess(Enum->getAccess()); 596 Enum->addDecl(EnumConst); 597 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 598 LastEnumConst = EnumConst; 599 600 if (D->getDeclContext()->isFunctionOrMethod()) { 601 // If the enumeration is within a function or method, record the enum 602 // constant as a local. 603 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst); 604 } 605 } 606 } 607 608 // FIXME: Fixup LBraceLoc and RBraceLoc 609 // FIXME: Empty Scope and AttributeList (required to handle attribute packed). 610 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 611 Sema::DeclPtrTy::make(Enum), 612 &Enumerators[0], Enumerators.size(), 613 0, 0); 614 615 return Enum; 616} 617 618Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 619 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 620 return 0; 621} 622 623Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 624 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 625 626 // Create a local instantiation scope for this class template, which 627 // will contain the instantiations of the template parameters. 628 Sema::LocalInstantiationScope Scope(SemaRef); 629 TemplateParameterList *TempParams = D->getTemplateParameters(); 630 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 631 if (!InstParams) 632 return NULL; 633 634 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 635 636 // Instantiate the qualifier. We have to do this first in case 637 // we're a friend declaration, because if we are then we need to put 638 // the new declaration in the appropriate context. 639 NestedNameSpecifier *Qualifier = Pattern->getQualifier(); 640 if (Qualifier) { 641 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 642 Pattern->getQualifierRange(), 643 TemplateArgs); 644 if (!Qualifier) return 0; 645 } 646 647 CXXRecordDecl *PrevDecl = 0; 648 ClassTemplateDecl *PrevClassTemplate = 0; 649 650 // If this isn't a friend, then it's a member template, in which 651 // case we just want to build the instantiation in the 652 // specialization. If it is a friend, we want to build it in 653 // the appropriate context. 654 DeclContext *DC = Owner; 655 if (isFriend) { 656 if (Qualifier) { 657 CXXScopeSpec SS; 658 SS.setScopeRep(Qualifier); 659 SS.setRange(Pattern->getQualifierRange()); 660 DC = SemaRef.computeDeclContext(SS); 661 if (!DC) return 0; 662 } else { 663 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 664 Pattern->getDeclContext(), 665 TemplateArgs); 666 } 667 668 // Look for a previous declaration of the template in the owning 669 // context. 670 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 671 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 672 SemaRef.LookupQualifiedName(R, DC); 673 674 if (R.isSingleResult()) { 675 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 676 if (PrevClassTemplate) 677 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 678 } 679 680 if (!PrevClassTemplate && Qualifier) { 681 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 682 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 683 << Pattern->getQualifierRange(); 684 return 0; 685 } 686 687 bool AdoptedPreviousTemplateParams = false; 688 if (PrevClassTemplate) { 689 bool Complain = true; 690 691 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 692 // template for struct std::tr1::__detail::_Map_base, where the 693 // template parameters of the friend declaration don't match the 694 // template parameters of the original declaration. In this one 695 // case, we don't complain about the ill-formed friend 696 // declaration. 697 if (isFriend && Pattern->getIdentifier() && 698 Pattern->getIdentifier()->isStr("_Map_base") && 699 DC->isNamespace() && 700 cast<NamespaceDecl>(DC)->getIdentifier() && 701 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 702 DeclContext *DCParent = DC->getParent(); 703 if (DCParent->isNamespace() && 704 cast<NamespaceDecl>(DCParent)->getIdentifier() && 705 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 706 DeclContext *DCParent2 = DCParent->getParent(); 707 if (DCParent2->isNamespace() && 708 cast<NamespaceDecl>(DCParent2)->getIdentifier() && 709 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") && 710 DCParent2->getParent()->isTranslationUnit()) 711 Complain = false; 712 } 713 } 714 715 TemplateParameterList *PrevParams 716 = PrevClassTemplate->getTemplateParameters(); 717 718 // Make sure the parameter lists match. 719 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 720 Complain, 721 Sema::TPL_TemplateMatch)) { 722 if (Complain) 723 return 0; 724 725 AdoptedPreviousTemplateParams = true; 726 InstParams = PrevParams; 727 } 728 729 // Do some additional validation, then merge default arguments 730 // from the existing declarations. 731 if (!AdoptedPreviousTemplateParams && 732 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 733 Sema::TPC_ClassTemplate)) 734 return 0; 735 } 736 } 737 738 CXXRecordDecl *RecordInst 739 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 740 Pattern->getLocation(), Pattern->getIdentifier(), 741 Pattern->getTagKeywordLoc(), PrevDecl, 742 /*DelayTypeCreation=*/true); 743 744 if (Qualifier) 745 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange()); 746 747 ClassTemplateDecl *Inst 748 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 749 D->getIdentifier(), InstParams, RecordInst, 750 PrevClassTemplate); 751 RecordInst->setDescribedClassTemplate(Inst); 752 753 if (isFriend) { 754 if (PrevClassTemplate) 755 Inst->setAccess(PrevClassTemplate->getAccess()); 756 else 757 Inst->setAccess(D->getAccess()); 758 759 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0); 760 // TODO: do we want to track the instantiation progeny of this 761 // friend target decl? 762 } else { 763 Inst->setAccess(D->getAccess()); 764 Inst->setInstantiatedFromMemberTemplate(D); 765 } 766 767 // Trigger creation of the type for the instantiation. 768 SemaRef.Context.getInjectedClassNameType(RecordInst, 769 Inst->getInjectedClassNameSpecialization(SemaRef.Context)); 770 771 // Finish handling of friends. 772 if (isFriend) { 773 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false); 774 return Inst; 775 } 776 777 Owner->addDecl(Inst); 778 779 // Instantiate all of the partial specializations of this member class 780 // template. 781 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 782 D->getPartialSpecializations(PartialSpecs); 783 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 784 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]); 785 786 return Inst; 787} 788 789Decl * 790TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 791 ClassTemplatePartialSpecializationDecl *D) { 792 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 793 794 // Lookup the already-instantiated declaration in the instantiation 795 // of the class template and return that. 796 DeclContext::lookup_result Found 797 = Owner->lookup(ClassTemplate->getDeclName()); 798 if (Found.first == Found.second) 799 return 0; 800 801 ClassTemplateDecl *InstClassTemplate 802 = dyn_cast<ClassTemplateDecl>(*Found.first); 803 if (!InstClassTemplate) 804 return 0; 805 806 Decl *DCanon = D->getCanonicalDecl(); 807 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 808 P = InstClassTemplate->getPartialSpecializations().begin(), 809 PEnd = InstClassTemplate->getPartialSpecializations().end(); 810 P != PEnd; ++P) { 811 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon) 812 return &*P; 813 } 814 815 return 0; 816} 817 818Decl * 819TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 820 // Create a local instantiation scope for this function template, which 821 // will contain the instantiations of the template parameters and then get 822 // merged with the local instantiation scope for the function template 823 // itself. 824 Sema::LocalInstantiationScope Scope(SemaRef); 825 826 TemplateParameterList *TempParams = D->getTemplateParameters(); 827 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 828 if (!InstParams) 829 return NULL; 830 831 FunctionDecl *Instantiated = 0; 832 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 833 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 834 InstParams)); 835 else 836 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 837 D->getTemplatedDecl(), 838 InstParams)); 839 840 if (!Instantiated) 841 return 0; 842 843 Instantiated->setAccess(D->getAccess()); 844 845 // Link the instantiated function template declaration to the function 846 // template from which it was instantiated. 847 FunctionTemplateDecl *InstTemplate 848 = Instantiated->getDescribedFunctionTemplate(); 849 InstTemplate->setAccess(D->getAccess()); 850 assert(InstTemplate && 851 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 852 853 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 854 855 // Link the instantiation back to the pattern *unless* this is a 856 // non-definition friend declaration. 857 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 858 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 859 InstTemplate->setInstantiatedFromMemberTemplate(D); 860 861 // Make declarations visible in the appropriate context. 862 if (!isFriend) 863 Owner->addDecl(InstTemplate); 864 865 return InstTemplate; 866} 867 868Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 869 CXXRecordDecl *PrevDecl = 0; 870 if (D->isInjectedClassName()) 871 PrevDecl = cast<CXXRecordDecl>(Owner); 872 else if (D->getPreviousDeclaration()) { 873 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 874 D->getPreviousDeclaration(), 875 TemplateArgs); 876 if (!Prev) return 0; 877 PrevDecl = cast<CXXRecordDecl>(Prev); 878 } 879 880 CXXRecordDecl *Record 881 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 882 D->getLocation(), D->getIdentifier(), 883 D->getTagKeywordLoc(), PrevDecl); 884 885 // Substitute the nested name specifier, if any. 886 if (SubstQualifier(D, Record)) 887 return 0; 888 889 Record->setImplicit(D->isImplicit()); 890 // FIXME: Check against AS_none is an ugly hack to work around the issue that 891 // the tag decls introduced by friend class declarations don't have an access 892 // specifier. Remove once this area of the code gets sorted out. 893 if (D->getAccess() != AS_none) 894 Record->setAccess(D->getAccess()); 895 if (!D->isInjectedClassName()) 896 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 897 898 // If the original function was part of a friend declaration, 899 // inherit its namespace state. 900 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 901 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 902 903 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion()); 904 905 Owner->addDecl(Record); 906 return Record; 907} 908 909/// Normal class members are of more specific types and therefore 910/// don't make it here. This function serves two purposes: 911/// 1) instantiating function templates 912/// 2) substituting friend declarations 913/// FIXME: preserve function definitions in case #2 914Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 915 TemplateParameterList *TemplateParams) { 916 // Check whether there is already a function template specialization for 917 // this declaration. 918 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 919 void *InsertPos = 0; 920 if (FunctionTemplate && !TemplateParams) { 921 llvm::FoldingSetNodeID ID; 922 FunctionTemplateSpecializationInfo::Profile(ID, 923 TemplateArgs.getInnermost().getFlatArgumentList(), 924 TemplateArgs.getInnermost().flat_size(), 925 SemaRef.Context); 926 927 FunctionTemplateSpecializationInfo *Info 928 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 929 InsertPos); 930 931 // If we already have a function template specialization, return it. 932 if (Info) 933 return Info->Function; 934 } 935 936 bool isFriend; 937 if (FunctionTemplate) 938 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 939 else 940 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 941 942 bool MergeWithParentScope = (TemplateParams != 0) || 943 !(isa<Decl>(Owner) && 944 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 945 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 946 947 llvm::SmallVector<ParmVarDecl *, 4> Params; 948 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 949 TInfo = SubstFunctionType(D, Params); 950 if (!TInfo) 951 return 0; 952 QualType T = TInfo->getType(); 953 954 NestedNameSpecifier *Qualifier = D->getQualifier(); 955 if (Qualifier) { 956 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 957 D->getQualifierRange(), 958 TemplateArgs); 959 if (!Qualifier) return 0; 960 } 961 962 // If we're instantiating a local function declaration, put the result 963 // in the owner; otherwise we need to find the instantiated context. 964 DeclContext *DC; 965 if (D->getDeclContext()->isFunctionOrMethod()) 966 DC = Owner; 967 else if (isFriend && Qualifier) { 968 CXXScopeSpec SS; 969 SS.setScopeRep(Qualifier); 970 SS.setRange(D->getQualifierRange()); 971 DC = SemaRef.computeDeclContext(SS); 972 if (!DC) return 0; 973 } else { 974 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 975 TemplateArgs); 976 } 977 978 FunctionDecl *Function = 979 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(), 980 D->getDeclName(), T, TInfo, 981 D->getStorageClass(), D->getStorageClassAsWritten(), 982 D->isInlineSpecified(), D->hasWrittenPrototype()); 983 984 if (Qualifier) 985 Function->setQualifierInfo(Qualifier, D->getQualifierRange()); 986 987 DeclContext *LexicalDC = Owner; 988 if (!isFriend && D->isOutOfLine()) { 989 assert(D->getDeclContext()->isFileContext()); 990 LexicalDC = D->getDeclContext(); 991 } 992 993 Function->setLexicalDeclContext(LexicalDC); 994 995 // Attach the parameters 996 for (unsigned P = 0; P < Params.size(); ++P) 997 Params[P]->setOwningFunction(Function); 998 Function->setParams(Params.data(), Params.size()); 999 1000 if (TemplateParams) { 1001 // Our resulting instantiation is actually a function template, since we 1002 // are substituting only the outer template parameters. For example, given 1003 // 1004 // template<typename T> 1005 // struct X { 1006 // template<typename U> friend void f(T, U); 1007 // }; 1008 // 1009 // X<int> x; 1010 // 1011 // We are instantiating the friend function template "f" within X<int>, 1012 // which means substituting int for T, but leaving "f" as a friend function 1013 // template. 1014 // Build the function template itself. 1015 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1016 Function->getLocation(), 1017 Function->getDeclName(), 1018 TemplateParams, Function); 1019 Function->setDescribedFunctionTemplate(FunctionTemplate); 1020 1021 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1022 1023 if (isFriend && D->isThisDeclarationADefinition()) { 1024 // TODO: should we remember this connection regardless of whether 1025 // the friend declaration provided a body? 1026 FunctionTemplate->setInstantiatedFromMemberTemplate( 1027 D->getDescribedFunctionTemplate()); 1028 } 1029 } else if (FunctionTemplate) { 1030 // Record this function template specialization. 1031 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1032 &TemplateArgs.getInnermost(), 1033 InsertPos); 1034 } else if (isFriend && D->isThisDeclarationADefinition()) { 1035 // TODO: should we remember this connection regardless of whether 1036 // the friend declaration provided a body? 1037 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1038 } 1039 1040 if (InitFunctionInstantiation(Function, D)) 1041 Function->setInvalidDecl(); 1042 1043 bool Redeclaration = false; 1044 bool OverloadableAttrRequired = false; 1045 bool isExplicitSpecialization = false; 1046 1047 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(), 1048 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 1049 1050 if (DependentFunctionTemplateSpecializationInfo *Info 1051 = D->getDependentSpecializationInfo()) { 1052 assert(isFriend && "non-friend has dependent specialization info?"); 1053 1054 // This needs to be set now for future sanity. 1055 Function->setObjectOfFriendDecl(/*HasPrevious*/ true); 1056 1057 // Instantiate the explicit template arguments. 1058 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1059 Info->getRAngleLoc()); 1060 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) { 1061 TemplateArgumentLoc Loc; 1062 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs)) 1063 return 0; 1064 1065 ExplicitArgs.addArgument(Loc); 1066 } 1067 1068 // Map the candidate templates to their instantiations. 1069 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1070 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1071 Info->getTemplate(I), 1072 TemplateArgs); 1073 if (!Temp) return 0; 1074 1075 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1076 } 1077 1078 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1079 &ExplicitArgs, 1080 Previous)) 1081 Function->setInvalidDecl(); 1082 1083 isExplicitSpecialization = true; 1084 1085 } else if (TemplateParams || !FunctionTemplate) { 1086 // Look only into the namespace where the friend would be declared to 1087 // find a previous declaration. This is the innermost enclosing namespace, 1088 // as described in ActOnFriendFunctionDecl. 1089 SemaRef.LookupQualifiedName(Previous, DC); 1090 1091 // In C++, the previous declaration we find might be a tag type 1092 // (class or enum). In this case, the new declaration will hide the 1093 // tag type. Note that this does does not apply if we're declaring a 1094 // typedef (C++ [dcl.typedef]p4). 1095 if (Previous.isSingleTagDecl()) 1096 Previous.clear(); 1097 } 1098 1099 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 1100 isExplicitSpecialization, Redeclaration, 1101 /*FIXME:*/OverloadableAttrRequired); 1102 1103 NamedDecl *PrincipalDecl = (TemplateParams 1104 ? cast<NamedDecl>(FunctionTemplate) 1105 : Function); 1106 1107 // If the original function was part of a friend declaration, 1108 // inherit its namespace state and add it to the owner. 1109 if (isFriend) { 1110 NamedDecl *PrevDecl; 1111 if (TemplateParams) 1112 PrevDecl = FunctionTemplate->getPreviousDeclaration(); 1113 else 1114 PrevDecl = Function->getPreviousDeclaration(); 1115 1116 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0); 1117 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false); 1118 } 1119 1120 if (Function->isOverloadedOperator() && !DC->isRecord() && 1121 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1122 PrincipalDecl->setNonMemberOperator(); 1123 1124 return Function; 1125} 1126 1127Decl * 1128TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 1129 TemplateParameterList *TemplateParams) { 1130 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1131 void *InsertPos = 0; 1132 if (FunctionTemplate && !TemplateParams) { 1133 // We are creating a function template specialization from a function 1134 // template. Check whether there is already a function template 1135 // specialization for this particular set of template arguments. 1136 llvm::FoldingSetNodeID ID; 1137 FunctionTemplateSpecializationInfo::Profile(ID, 1138 TemplateArgs.getInnermost().getFlatArgumentList(), 1139 TemplateArgs.getInnermost().flat_size(), 1140 SemaRef.Context); 1141 1142 FunctionTemplateSpecializationInfo *Info 1143 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 1144 InsertPos); 1145 1146 // If we already have a function template specialization, return it. 1147 if (Info) 1148 return Info->Function; 1149 } 1150 1151 bool isFriend; 1152 if (FunctionTemplate) 1153 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1154 else 1155 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1156 1157 bool MergeWithParentScope = (TemplateParams != 0) || 1158 !(isa<Decl>(Owner) && 1159 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1160 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1161 1162 llvm::SmallVector<ParmVarDecl *, 4> Params; 1163 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 1164 TInfo = SubstFunctionType(D, Params); 1165 if (!TInfo) 1166 return 0; 1167 QualType T = TInfo->getType(); 1168 1169 NestedNameSpecifier *Qualifier = D->getQualifier(); 1170 if (Qualifier) { 1171 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 1172 D->getQualifierRange(), 1173 TemplateArgs); 1174 if (!Qualifier) return 0; 1175 } 1176 1177 DeclContext *DC = Owner; 1178 if (isFriend) { 1179 if (Qualifier) { 1180 CXXScopeSpec SS; 1181 SS.setScopeRep(Qualifier); 1182 SS.setRange(D->getQualifierRange()); 1183 DC = SemaRef.computeDeclContext(SS); 1184 } else { 1185 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 1186 D->getDeclContext(), 1187 TemplateArgs); 1188 } 1189 if (!DC) return 0; 1190 } 1191 1192 // Build the instantiated method declaration. 1193 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1194 CXXMethodDecl *Method = 0; 1195 1196 DeclarationName Name = D->getDeclName(); 1197 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1198 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 1199 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName( 1200 SemaRef.Context.getCanonicalType(ClassTy)); 1201 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 1202 Constructor->getLocation(), 1203 Name, T, TInfo, 1204 Constructor->isExplicit(), 1205 Constructor->isInlineSpecified(), 1206 false); 1207 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 1208 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 1209 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName( 1210 SemaRef.Context.getCanonicalType(ClassTy)); 1211 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 1212 Destructor->getLocation(), Name, 1213 T, Destructor->isInlineSpecified(), 1214 false); 1215 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 1216 CanQualType ConvTy 1217 = SemaRef.Context.getCanonicalType( 1218 T->getAs<FunctionType>()->getResultType()); 1219 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName( 1220 ConvTy); 1221 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 1222 Conversion->getLocation(), Name, 1223 T, TInfo, 1224 Conversion->isInlineSpecified(), 1225 Conversion->isExplicit()); 1226 } else { 1227 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 1228 D->getDeclName(), T, TInfo, 1229 D->isStatic(), 1230 D->getStorageClassAsWritten(), 1231 D->isInlineSpecified()); 1232 } 1233 1234 if (Qualifier) 1235 Method->setQualifierInfo(Qualifier, D->getQualifierRange()); 1236 1237 if (TemplateParams) { 1238 // Our resulting instantiation is actually a function template, since we 1239 // are substituting only the outer template parameters. For example, given 1240 // 1241 // template<typename T> 1242 // struct X { 1243 // template<typename U> void f(T, U); 1244 // }; 1245 // 1246 // X<int> x; 1247 // 1248 // We are instantiating the member template "f" within X<int>, which means 1249 // substituting int for T, but leaving "f" as a member function template. 1250 // Build the function template itself. 1251 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 1252 Method->getLocation(), 1253 Method->getDeclName(), 1254 TemplateParams, Method); 1255 if (isFriend) { 1256 FunctionTemplate->setLexicalDeclContext(Owner); 1257 FunctionTemplate->setObjectOfFriendDecl(true); 1258 } else if (D->isOutOfLine()) 1259 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 1260 Method->setDescribedFunctionTemplate(FunctionTemplate); 1261 } else if (FunctionTemplate) { 1262 // Record this function template specialization. 1263 Method->setFunctionTemplateSpecialization(FunctionTemplate, 1264 &TemplateArgs.getInnermost(), 1265 InsertPos); 1266 } else if (!isFriend) { 1267 // Record that this is an instantiation of a member function. 1268 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1269 } 1270 1271 // If we are instantiating a member function defined 1272 // out-of-line, the instantiation will have the same lexical 1273 // context (which will be a namespace scope) as the template. 1274 if (isFriend) { 1275 Method->setLexicalDeclContext(Owner); 1276 Method->setObjectOfFriendDecl(true); 1277 } else if (D->isOutOfLine()) 1278 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 1279 1280 // Attach the parameters 1281 for (unsigned P = 0; P < Params.size(); ++P) 1282 Params[P]->setOwningFunction(Method); 1283 Method->setParams(Params.data(), Params.size()); 1284 1285 if (InitMethodInstantiation(Method, D)) 1286 Method->setInvalidDecl(); 1287 1288 LookupResult Previous(SemaRef, Name, SourceLocation(), 1289 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 1290 1291 if (!FunctionTemplate || TemplateParams || isFriend) { 1292 SemaRef.LookupQualifiedName(Previous, Record); 1293 1294 // In C++, the previous declaration we find might be a tag type 1295 // (class or enum). In this case, the new declaration will hide the 1296 // tag type. Note that this does does not apply if we're declaring a 1297 // typedef (C++ [dcl.typedef]p4). 1298 if (Previous.isSingleTagDecl()) 1299 Previous.clear(); 1300 } 1301 1302 bool Redeclaration = false; 1303 bool OverloadableAttrRequired = false; 1304 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration, 1305 /*FIXME:*/OverloadableAttrRequired); 1306 1307 if (D->isPure()) 1308 SemaRef.CheckPureMethod(Method, SourceRange()); 1309 1310 Method->setAccess(D->getAccess()); 1311 1312 if (FunctionTemplate) { 1313 // If there's a function template, let our caller handle it. 1314 } else if (Method->isInvalidDecl() && !Previous.empty()) { 1315 // Don't hide a (potentially) valid declaration with an invalid one. 1316 } else { 1317 NamedDecl *DeclToAdd = (TemplateParams 1318 ? cast<NamedDecl>(FunctionTemplate) 1319 : Method); 1320 if (isFriend) 1321 Record->makeDeclVisibleInContext(DeclToAdd); 1322 else 1323 Owner->addDecl(DeclToAdd); 1324 } 1325 1326 return Method; 1327} 1328 1329Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1330 return VisitCXXMethodDecl(D); 1331} 1332 1333Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1334 return VisitCXXMethodDecl(D); 1335} 1336 1337Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 1338 return VisitCXXMethodDecl(D); 1339} 1340 1341ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 1342 return SemaRef.SubstParmVarDecl(D, TemplateArgs); 1343} 1344 1345Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1346 TemplateTypeParmDecl *D) { 1347 // TODO: don't always clone when decls are refcounted. 1348 const Type* T = D->getTypeForDecl(); 1349 assert(T->isTemplateTypeParmType()); 1350 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>(); 1351 1352 TemplateTypeParmDecl *Inst = 1353 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1354 TTPT->getDepth() - 1, TTPT->getIndex(), 1355 TTPT->getName(), 1356 D->wasDeclaredWithTypename(), 1357 D->isParameterPack()); 1358 1359 if (D->hasDefaultArgument()) 1360 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 1361 1362 // Introduce this template parameter's instantiation into the instantiation 1363 // scope. 1364 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1365 1366 return Inst; 1367} 1368 1369Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1370 NonTypeTemplateParmDecl *D) { 1371 // Substitute into the type of the non-type template parameter. 1372 QualType T; 1373 TypeSourceInfo *DI = D->getTypeSourceInfo(); 1374 if (DI) { 1375 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 1376 D->getDeclName()); 1377 if (DI) T = DI->getType(); 1378 } else { 1379 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 1380 D->getDeclName()); 1381 DI = 0; 1382 } 1383 if (T.isNull()) 1384 return 0; 1385 1386 // Check that this type is acceptable for a non-type template parameter. 1387 bool Invalid = false; 1388 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation()); 1389 if (T.isNull()) { 1390 T = SemaRef.Context.IntTy; 1391 Invalid = true; 1392 } 1393 1394 NonTypeTemplateParmDecl *Param 1395 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1396 D->getDepth() - 1, D->getPosition(), 1397 D->getIdentifier(), T, DI); 1398 if (Invalid) 1399 Param->setInvalidDecl(); 1400 1401 Param->setDefaultArgument(D->getDefaultArgument()); 1402 1403 // Introduce this template parameter's instantiation into the instantiation 1404 // scope. 1405 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1406 return Param; 1407} 1408 1409Decl * 1410TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1411 TemplateTemplateParmDecl *D) { 1412 // Instantiate the template parameter list of the template template parameter. 1413 TemplateParameterList *TempParams = D->getTemplateParameters(); 1414 TemplateParameterList *InstParams; 1415 { 1416 // Perform the actual substitution of template parameters within a new, 1417 // local instantiation scope. 1418 Sema::LocalInstantiationScope Scope(SemaRef); 1419 InstParams = SubstTemplateParams(TempParams); 1420 if (!InstParams) 1421 return NULL; 1422 } 1423 1424 // Build the template template parameter. 1425 TemplateTemplateParmDecl *Param 1426 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1427 D->getDepth() - 1, D->getPosition(), 1428 D->getIdentifier(), InstParams); 1429 Param->setDefaultArgument(D->getDefaultArgument()); 1430 1431 // Introduce this template parameter's instantiation into the instantiation 1432 // scope. 1433 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1434 1435 return Param; 1436} 1437 1438Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1439 // Using directives are never dependent, so they require no explicit 1440 1441 UsingDirectiveDecl *Inst 1442 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1443 D->getNamespaceKeyLocation(), 1444 D->getQualifierRange(), D->getQualifier(), 1445 D->getIdentLocation(), 1446 D->getNominatedNamespace(), 1447 D->getCommonAncestor()); 1448 Owner->addDecl(Inst); 1449 return Inst; 1450} 1451 1452Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 1453 // The nested name specifier is non-dependent, so no transformation 1454 // is required. 1455 1456 // We only need to do redeclaration lookups if we're in a class 1457 // scope (in fact, it's not really even possible in non-class 1458 // scopes). 1459 bool CheckRedeclaration = Owner->isRecord(); 1460 1461 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(), 1462 Sema::LookupUsingDeclName, Sema::ForRedeclaration); 1463 1464 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 1465 D->getLocation(), 1466 D->getNestedNameRange(), 1467 D->getUsingLocation(), 1468 D->getTargetNestedNameDecl(), 1469 D->getDeclName(), 1470 D->isTypeName()); 1471 1472 CXXScopeSpec SS; 1473 SS.setScopeRep(D->getTargetNestedNameDecl()); 1474 SS.setRange(D->getNestedNameRange()); 1475 1476 if (CheckRedeclaration) { 1477 Prev.setHideTags(false); 1478 SemaRef.LookupQualifiedName(Prev, Owner); 1479 1480 // Check for invalid redeclarations. 1481 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(), 1482 D->isTypeName(), SS, 1483 D->getLocation(), Prev)) 1484 NewUD->setInvalidDecl(); 1485 1486 } 1487 1488 if (!NewUD->isInvalidDecl() && 1489 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS, 1490 D->getLocation())) 1491 NewUD->setInvalidDecl(); 1492 1493 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 1494 NewUD->setAccess(D->getAccess()); 1495 Owner->addDecl(NewUD); 1496 1497 // Don't process the shadow decls for an invalid decl. 1498 if (NewUD->isInvalidDecl()) 1499 return NewUD; 1500 1501 bool isFunctionScope = Owner->isFunctionOrMethod(); 1502 1503 // Process the shadow decls. 1504 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 1505 I != E; ++I) { 1506 UsingShadowDecl *Shadow = *I; 1507 NamedDecl *InstTarget = 1508 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(), 1509 Shadow->getTargetDecl(), 1510 TemplateArgs)); 1511 1512 if (CheckRedeclaration && 1513 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev)) 1514 continue; 1515 1516 UsingShadowDecl *InstShadow 1517 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget); 1518 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 1519 1520 if (isFunctionScope) 1521 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 1522 } 1523 1524 return NewUD; 1525} 1526 1527Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 1528 // Ignore these; we handle them in bulk when processing the UsingDecl. 1529 return 0; 1530} 1531 1532Decl * TemplateDeclInstantiator 1533 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 1534 NestedNameSpecifier *NNS = 1535 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1536 D->getTargetNestedNameRange(), 1537 TemplateArgs); 1538 if (!NNS) 1539 return 0; 1540 1541 CXXScopeSpec SS; 1542 SS.setRange(D->getTargetNestedNameRange()); 1543 SS.setScopeRep(NNS); 1544 1545 NamedDecl *UD = 1546 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1547 D->getUsingLoc(), SS, D->getLocation(), 1548 D->getDeclName(), 0, 1549 /*instantiation*/ true, 1550 /*typename*/ true, D->getTypenameLoc()); 1551 if (UD) 1552 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1553 1554 return UD; 1555} 1556 1557Decl * TemplateDeclInstantiator 1558 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1559 NestedNameSpecifier *NNS = 1560 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1561 D->getTargetNestedNameRange(), 1562 TemplateArgs); 1563 if (!NNS) 1564 return 0; 1565 1566 CXXScopeSpec SS; 1567 SS.setRange(D->getTargetNestedNameRange()); 1568 SS.setScopeRep(NNS); 1569 1570 NamedDecl *UD = 1571 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1572 D->getUsingLoc(), SS, D->getLocation(), 1573 D->getDeclName(), 0, 1574 /*instantiation*/ true, 1575 /*typename*/ false, SourceLocation()); 1576 if (UD) 1577 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1578 1579 return UD; 1580} 1581 1582Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 1583 const MultiLevelTemplateArgumentList &TemplateArgs) { 1584 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 1585 if (D->isInvalidDecl()) 1586 return 0; 1587 1588 return Instantiator.Visit(D); 1589} 1590 1591/// \brief Instantiates a nested template parameter list in the current 1592/// instantiation context. 1593/// 1594/// \param L The parameter list to instantiate 1595/// 1596/// \returns NULL if there was an error 1597TemplateParameterList * 1598TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 1599 // Get errors for all the parameters before bailing out. 1600 bool Invalid = false; 1601 1602 unsigned N = L->size(); 1603 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector; 1604 ParamVector Params; 1605 Params.reserve(N); 1606 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 1607 PI != PE; ++PI) { 1608 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 1609 Params.push_back(D); 1610 Invalid = Invalid || !D || D->isInvalidDecl(); 1611 } 1612 1613 // Clean up if we had an error. 1614 if (Invalid) { 1615 for (ParamVector::iterator PI = Params.begin(), PE = Params.end(); 1616 PI != PE; ++PI) 1617 if (*PI) 1618 (*PI)->Destroy(SemaRef.Context); 1619 return NULL; 1620 } 1621 1622 TemplateParameterList *InstL 1623 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 1624 L->getLAngleLoc(), &Params.front(), N, 1625 L->getRAngleLoc()); 1626 return InstL; 1627} 1628 1629/// \brief Instantiate the declaration of a class template partial 1630/// specialization. 1631/// 1632/// \param ClassTemplate the (instantiated) class template that is partially 1633// specialized by the instantiation of \p PartialSpec. 1634/// 1635/// \param PartialSpec the (uninstantiated) class template partial 1636/// specialization that we are instantiating. 1637/// 1638/// \returns true if there was an error, false otherwise. 1639bool 1640TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 1641 ClassTemplateDecl *ClassTemplate, 1642 ClassTemplatePartialSpecializationDecl *PartialSpec) { 1643 // Create a local instantiation scope for this class template partial 1644 // specialization, which will contain the instantiations of the template 1645 // parameters. 1646 Sema::LocalInstantiationScope Scope(SemaRef); 1647 1648 // Substitute into the template parameters of the class template partial 1649 // specialization. 1650 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 1651 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1652 if (!InstParams) 1653 return true; 1654 1655 // Substitute into the template arguments of the class template partial 1656 // specialization. 1657 const TemplateArgumentLoc *PartialSpecTemplateArgs 1658 = PartialSpec->getTemplateArgsAsWritten(); 1659 unsigned N = PartialSpec->getNumTemplateArgsAsWritten(); 1660 1661 TemplateArgumentListInfo InstTemplateArgs; // no angle locations 1662 for (unsigned I = 0; I != N; ++I) { 1663 TemplateArgumentLoc Loc; 1664 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs)) 1665 return true; 1666 InstTemplateArgs.addArgument(Loc); 1667 } 1668 1669 1670 // Check that the template argument list is well-formed for this 1671 // class template. 1672 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 1673 InstTemplateArgs.size()); 1674 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 1675 PartialSpec->getLocation(), 1676 InstTemplateArgs, 1677 false, 1678 Converted)) 1679 return true; 1680 1681 // Figure out where to insert this class template partial specialization 1682 // in the member template's set of class template partial specializations. 1683 llvm::FoldingSetNodeID ID; 1684 ClassTemplatePartialSpecializationDecl::Profile(ID, 1685 Converted.getFlatArguments(), 1686 Converted.flatSize(), 1687 SemaRef.Context); 1688 void *InsertPos = 0; 1689 ClassTemplateSpecializationDecl *PrevDecl 1690 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 1691 InsertPos); 1692 1693 // Build the canonical type that describes the converted template 1694 // arguments of the class template partial specialization. 1695 QualType CanonType 1696 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1697 Converted.getFlatArguments(), 1698 Converted.flatSize()); 1699 1700 // Build the fully-sugared type for this class template 1701 // specialization as the user wrote in the specialization 1702 // itself. This means that we'll pretty-print the type retrieved 1703 // from the specialization's declaration the way that the user 1704 // actually wrote the specialization, rather than formatting the 1705 // name based on the "canonical" representation used to store the 1706 // template arguments in the specialization. 1707 TypeSourceInfo *WrittenTy 1708 = SemaRef.Context.getTemplateSpecializationTypeInfo( 1709 TemplateName(ClassTemplate), 1710 PartialSpec->getLocation(), 1711 InstTemplateArgs, 1712 CanonType); 1713 1714 if (PrevDecl) { 1715 // We've already seen a partial specialization with the same template 1716 // parameters and template arguments. This can happen, for example, when 1717 // substituting the outer template arguments ends up causing two 1718 // class template partial specializations of a member class template 1719 // to have identical forms, e.g., 1720 // 1721 // template<typename T, typename U> 1722 // struct Outer { 1723 // template<typename X, typename Y> struct Inner; 1724 // template<typename Y> struct Inner<T, Y>; 1725 // template<typename Y> struct Inner<U, Y>; 1726 // }; 1727 // 1728 // Outer<int, int> outer; // error: the partial specializations of Inner 1729 // // have the same signature. 1730 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 1731 << WrittenTy; 1732 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 1733 << SemaRef.Context.getTypeDeclType(PrevDecl); 1734 return true; 1735 } 1736 1737 1738 // Create the class template partial specialization declaration. 1739 ClassTemplatePartialSpecializationDecl *InstPartialSpec 1740 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner, 1741 PartialSpec->getLocation(), 1742 InstParams, 1743 ClassTemplate, 1744 Converted, 1745 InstTemplateArgs, 1746 CanonType, 1747 0, 1748 ClassTemplate->getPartialSpecializations().size()); 1749 // Substitute the nested name specifier, if any. 1750 if (SubstQualifier(PartialSpec, InstPartialSpec)) 1751 return 0; 1752 1753 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 1754 InstPartialSpec->setTypeAsWritten(WrittenTy); 1755 1756 // Add this partial specialization to the set of class template partial 1757 // specializations. 1758 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec, 1759 InsertPos); 1760 return false; 1761} 1762 1763TypeSourceInfo* 1764TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 1765 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 1766 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 1767 assert(OldTInfo && "substituting function without type source info"); 1768 assert(Params.empty() && "parameter vector is non-empty at start"); 1769 TypeSourceInfo *NewTInfo 1770 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 1771 D->getTypeSpecStartLoc(), 1772 D->getDeclName()); 1773 if (!NewTInfo) 1774 return 0; 1775 1776 if (NewTInfo != OldTInfo) { 1777 // Get parameters from the new type info. 1778 TypeLoc OldTL = OldTInfo->getTypeLoc(); 1779 FunctionProtoTypeLoc *OldProtoLoc = cast<FunctionProtoTypeLoc>(&OldTL); 1780 TypeLoc NewTL = NewTInfo->getTypeLoc(); 1781 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL); 1782 assert(NewProtoLoc && "Missing prototype?"); 1783 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) { 1784 // FIXME: Variadic templates will break this. 1785 Params.push_back(NewProtoLoc->getArg(i)); 1786 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 1787 OldProtoLoc->getArg(i), 1788 NewProtoLoc->getArg(i)); 1789 } 1790 } else { 1791 // The function type itself was not dependent and therefore no 1792 // substitution occurred. However, we still need to instantiate 1793 // the function parameters themselves. 1794 TypeLoc OldTL = OldTInfo->getTypeLoc(); 1795 FunctionProtoTypeLoc *OldProtoLoc = cast<FunctionProtoTypeLoc>(&OldTL); 1796 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) { 1797 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i)); 1798 if (!Parm) 1799 return 0; 1800 Params.push_back(Parm); 1801 } 1802 } 1803 return NewTInfo; 1804} 1805 1806/// \brief Initializes the common fields of an instantiation function 1807/// declaration (New) from the corresponding fields of its template (Tmpl). 1808/// 1809/// \returns true if there was an error 1810bool 1811TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 1812 FunctionDecl *Tmpl) { 1813 if (Tmpl->isDeleted()) 1814 New->setDeleted(); 1815 1816 // If we are performing substituting explicitly-specified template arguments 1817 // or deduced template arguments into a function template and we reach this 1818 // point, we are now past the point where SFINAE applies and have committed 1819 // to keeping the new function template specialization. We therefore 1820 // convert the active template instantiation for the function template 1821 // into a template instantiation for this specific function template 1822 // specialization, which is not a SFINAE context, so that we diagnose any 1823 // further errors in the declaration itself. 1824 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 1825 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 1826 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 1827 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 1828 if (FunctionTemplateDecl *FunTmpl 1829 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 1830 assert(FunTmpl->getTemplatedDecl() == Tmpl && 1831 "Deduction from the wrong function template?"); 1832 (void) FunTmpl; 1833 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 1834 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 1835 --SemaRef.NonInstantiationEntries; 1836 } 1837 } 1838 1839 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 1840 assert(Proto && "Function template without prototype?"); 1841 1842 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() || 1843 Proto->getNoReturnAttr()) { 1844 // The function has an exception specification or a "noreturn" 1845 // attribute. Substitute into each of the exception types. 1846 llvm::SmallVector<QualType, 4> Exceptions; 1847 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 1848 // FIXME: Poor location information! 1849 QualType T 1850 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 1851 New->getLocation(), New->getDeclName()); 1852 if (T.isNull() || 1853 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 1854 continue; 1855 1856 Exceptions.push_back(T); 1857 } 1858 1859 // Rebuild the function type 1860 1861 const FunctionProtoType *NewProto 1862 = New->getType()->getAs<FunctionProtoType>(); 1863 assert(NewProto && "Template instantiation without function prototype?"); 1864 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 1865 NewProto->arg_type_begin(), 1866 NewProto->getNumArgs(), 1867 NewProto->isVariadic(), 1868 NewProto->getTypeQuals(), 1869 Proto->hasExceptionSpec(), 1870 Proto->hasAnyExceptionSpec(), 1871 Exceptions.size(), 1872 Exceptions.data(), 1873 Proto->getExtInfo())); 1874 } 1875 1876 return false; 1877} 1878 1879/// \brief Initializes common fields of an instantiated method 1880/// declaration (New) from the corresponding fields of its template 1881/// (Tmpl). 1882/// 1883/// \returns true if there was an error 1884bool 1885TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 1886 CXXMethodDecl *Tmpl) { 1887 if (InitFunctionInstantiation(New, Tmpl)) 1888 return true; 1889 1890 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 1891 New->setAccess(Tmpl->getAccess()); 1892 if (Tmpl->isVirtualAsWritten()) 1893 Record->setMethodAsVirtual(New); 1894 1895 // FIXME: attributes 1896 // FIXME: New needs a pointer to Tmpl 1897 return false; 1898} 1899 1900/// \brief Instantiate the definition of the given function from its 1901/// template. 1902/// 1903/// \param PointOfInstantiation the point at which the instantiation was 1904/// required. Note that this is not precisely a "point of instantiation" 1905/// for the function, but it's close. 1906/// 1907/// \param Function the already-instantiated declaration of a 1908/// function template specialization or member function of a class template 1909/// specialization. 1910/// 1911/// \param Recursive if true, recursively instantiates any functions that 1912/// are required by this instantiation. 1913/// 1914/// \param DefinitionRequired if true, then we are performing an explicit 1915/// instantiation where the body of the function is required. Complain if 1916/// there is no such body. 1917void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 1918 FunctionDecl *Function, 1919 bool Recursive, 1920 bool DefinitionRequired) { 1921 if (Function->isInvalidDecl()) 1922 return; 1923 1924 assert(!Function->getBody() && "Already instantiated!"); 1925 1926 // Never instantiate an explicit specialization. 1927 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1928 return; 1929 1930 // Find the function body that we'll be substituting. 1931 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 1932 Stmt *Pattern = 0; 1933 if (PatternDecl) 1934 Pattern = PatternDecl->getBody(PatternDecl); 1935 1936 if (!Pattern) { 1937 if (DefinitionRequired) { 1938 if (Function->getPrimaryTemplate()) 1939 Diag(PointOfInstantiation, 1940 diag::err_explicit_instantiation_undefined_func_template) 1941 << Function->getPrimaryTemplate(); 1942 else 1943 Diag(PointOfInstantiation, 1944 diag::err_explicit_instantiation_undefined_member) 1945 << 1 << Function->getDeclName() << Function->getDeclContext(); 1946 1947 if (PatternDecl) 1948 Diag(PatternDecl->getLocation(), 1949 diag::note_explicit_instantiation_here); 1950 } 1951 1952 return; 1953 } 1954 1955 // C++0x [temp.explicit]p9: 1956 // Except for inline functions, other explicit instantiation declarations 1957 // have the effect of suppressing the implicit instantiation of the entity 1958 // to which they refer. 1959 if (Function->getTemplateSpecializationKind() 1960 == TSK_ExplicitInstantiationDeclaration && 1961 !PatternDecl->isInlined()) 1962 return; 1963 1964 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 1965 if (Inst) 1966 return; 1967 1968 // If we're performing recursive template instantiation, create our own 1969 // queue of pending implicit instantiations that we will instantiate later, 1970 // while we're still within our own instantiation context. 1971 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1972 if (Recursive) 1973 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1974 1975 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 1976 1977 // Introduce a new scope where local variable instantiations will be 1978 // recorded, unless we're actually a member function within a local 1979 // class, in which case we need to merge our results with the parent 1980 // scope (of the enclosing function). 1981 bool MergeWithParentScope = false; 1982 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 1983 MergeWithParentScope = Rec->isLocalClass(); 1984 1985 LocalInstantiationScope Scope(*this, MergeWithParentScope); 1986 1987 // Introduce the instantiated function parameters into the local 1988 // instantiation scope. 1989 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 1990 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 1991 Function->getParamDecl(I)); 1992 1993 // Enter the scope of this instantiation. We don't use 1994 // PushDeclContext because we don't have a scope. 1995 DeclContext *PreviousContext = CurContext; 1996 CurContext = Function; 1997 1998 MultiLevelTemplateArgumentList TemplateArgs = 1999 getTemplateInstantiationArgs(Function); 2000 2001 // If this is a constructor, instantiate the member initializers. 2002 if (const CXXConstructorDecl *Ctor = 2003 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 2004 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 2005 TemplateArgs); 2006 } 2007 2008 // Instantiate the function body. 2009 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs); 2010 2011 if (Body.isInvalid()) 2012 Function->setInvalidDecl(); 2013 2014 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 2015 /*IsInstantiation=*/true); 2016 2017 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 2018 2019 CurContext = PreviousContext; 2020 2021 DeclGroupRef DG(Function); 2022 Consumer.HandleTopLevelDecl(DG); 2023 2024 // This class may have local implicit instantiations that need to be 2025 // instantiation within this scope. 2026 PerformPendingImplicitInstantiations(/*LocalOnly=*/true); 2027 Scope.Exit(); 2028 2029 if (Recursive) { 2030 // Instantiate any pending implicit instantiations found during the 2031 // instantiation of this template. 2032 PerformPendingImplicitInstantiations(); 2033 2034 // Restore the set of pending implicit instantiations. 2035 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2036 } 2037} 2038 2039/// \brief Instantiate the definition of the given variable from its 2040/// template. 2041/// 2042/// \param PointOfInstantiation the point at which the instantiation was 2043/// required. Note that this is not precisely a "point of instantiation" 2044/// for the function, but it's close. 2045/// 2046/// \param Var the already-instantiated declaration of a static member 2047/// variable of a class template specialization. 2048/// 2049/// \param Recursive if true, recursively instantiates any functions that 2050/// are required by this instantiation. 2051/// 2052/// \param DefinitionRequired if true, then we are performing an explicit 2053/// instantiation where an out-of-line definition of the member variable 2054/// is required. Complain if there is no such definition. 2055void Sema::InstantiateStaticDataMemberDefinition( 2056 SourceLocation PointOfInstantiation, 2057 VarDecl *Var, 2058 bool Recursive, 2059 bool DefinitionRequired) { 2060 if (Var->isInvalidDecl()) 2061 return; 2062 2063 // Find the out-of-line definition of this static data member. 2064 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 2065 assert(Def && "This data member was not instantiated from a template?"); 2066 assert(Def->isStaticDataMember() && "Not a static data member?"); 2067 Def = Def->getOutOfLineDefinition(); 2068 2069 if (!Def) { 2070 // We did not find an out-of-line definition of this static data member, 2071 // so we won't perform any instantiation. Rather, we rely on the user to 2072 // instantiate this definition (or provide a specialization for it) in 2073 // another translation unit. 2074 if (DefinitionRequired) { 2075 Def = Var->getInstantiatedFromStaticDataMember(); 2076 Diag(PointOfInstantiation, 2077 diag::err_explicit_instantiation_undefined_member) 2078 << 2 << Var->getDeclName() << Var->getDeclContext(); 2079 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 2080 } 2081 2082 return; 2083 } 2084 2085 // Never instantiate an explicit specialization. 2086 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 2087 return; 2088 2089 // C++0x [temp.explicit]p9: 2090 // Except for inline functions, other explicit instantiation declarations 2091 // have the effect of suppressing the implicit instantiation of the entity 2092 // to which they refer. 2093 if (Var->getTemplateSpecializationKind() 2094 == TSK_ExplicitInstantiationDeclaration) 2095 return; 2096 2097 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 2098 if (Inst) 2099 return; 2100 2101 // If we're performing recursive template instantiation, create our own 2102 // queue of pending implicit instantiations that we will instantiate later, 2103 // while we're still within our own instantiation context. 2104 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 2105 if (Recursive) 2106 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2107 2108 // Enter the scope of this instantiation. We don't use 2109 // PushDeclContext because we don't have a scope. 2110 DeclContext *PreviousContext = CurContext; 2111 CurContext = Var->getDeclContext(); 2112 2113 VarDecl *OldVar = Var; 2114 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 2115 getTemplateInstantiationArgs(Var))); 2116 CurContext = PreviousContext; 2117 2118 if (Var) { 2119 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 2120 assert(MSInfo && "Missing member specialization information?"); 2121 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 2122 MSInfo->getPointOfInstantiation()); 2123 DeclGroupRef DG(Var); 2124 Consumer.HandleTopLevelDecl(DG); 2125 } 2126 2127 if (Recursive) { 2128 // Instantiate any pending implicit instantiations found during the 2129 // instantiation of this template. 2130 PerformPendingImplicitInstantiations(); 2131 2132 // Restore the set of pending implicit instantiations. 2133 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2134 } 2135} 2136 2137void 2138Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 2139 const CXXConstructorDecl *Tmpl, 2140 const MultiLevelTemplateArgumentList &TemplateArgs) { 2141 2142 llvm::SmallVector<MemInitTy*, 4> NewInits; 2143 bool AnyErrors = false; 2144 2145 // Instantiate all the initializers. 2146 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 2147 InitsEnd = Tmpl->init_end(); 2148 Inits != InitsEnd; ++Inits) { 2149 CXXBaseOrMemberInitializer *Init = *Inits; 2150 2151 SourceLocation LParenLoc, RParenLoc; 2152 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this); 2153 llvm::SmallVector<SourceLocation, 4> CommaLocs; 2154 2155 // Instantiate the initializer. 2156 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs, 2157 LParenLoc, CommaLocs, NewArgs, RParenLoc)) { 2158 AnyErrors = true; 2159 continue; 2160 } 2161 2162 MemInitResult NewInit; 2163 if (Init->isBaseInitializer()) { 2164 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(), 2165 TemplateArgs, 2166 Init->getSourceLocation(), 2167 New->getDeclName()); 2168 if (!BaseTInfo) { 2169 AnyErrors = true; 2170 New->setInvalidDecl(); 2171 continue; 2172 } 2173 2174 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo, 2175 (Expr **)NewArgs.data(), 2176 NewArgs.size(), 2177 Init->getLParenLoc(), 2178 Init->getRParenLoc(), 2179 New->getParent()); 2180 } else if (Init->isMemberInitializer()) { 2181 FieldDecl *Member; 2182 2183 // Is this an anonymous union? 2184 if (FieldDecl *UnionInit = Init->getAnonUnionMember()) 2185 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(), 2186 UnionInit, TemplateArgs)); 2187 else 2188 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(), 2189 Init->getMember(), 2190 TemplateArgs)); 2191 2192 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 2193 NewArgs.size(), 2194 Init->getSourceLocation(), 2195 Init->getLParenLoc(), 2196 Init->getRParenLoc()); 2197 } 2198 2199 if (NewInit.isInvalid()) { 2200 AnyErrors = true; 2201 New->setInvalidDecl(); 2202 } else { 2203 // FIXME: It would be nice if ASTOwningVector had a release function. 2204 NewArgs.take(); 2205 2206 NewInits.push_back((MemInitTy *)NewInit.get()); 2207 } 2208 } 2209 2210 // Assign all the initializers to the new constructor. 2211 ActOnMemInitializers(DeclPtrTy::make(New), 2212 /*FIXME: ColonLoc */ 2213 SourceLocation(), 2214 NewInits.data(), NewInits.size(), 2215 AnyErrors); 2216} 2217 2218// TODO: this could be templated if the various decl types used the 2219// same method name. 2220static bool isInstantiationOf(ClassTemplateDecl *Pattern, 2221 ClassTemplateDecl *Instance) { 2222 Pattern = Pattern->getCanonicalDecl(); 2223 2224 do { 2225 Instance = Instance->getCanonicalDecl(); 2226 if (Pattern == Instance) return true; 2227 Instance = Instance->getInstantiatedFromMemberTemplate(); 2228 } while (Instance); 2229 2230 return false; 2231} 2232 2233static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 2234 FunctionTemplateDecl *Instance) { 2235 Pattern = Pattern->getCanonicalDecl(); 2236 2237 do { 2238 Instance = Instance->getCanonicalDecl(); 2239 if (Pattern == Instance) return true; 2240 Instance = Instance->getInstantiatedFromMemberTemplate(); 2241 } while (Instance); 2242 2243 return false; 2244} 2245 2246static bool 2247isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 2248 ClassTemplatePartialSpecializationDecl *Instance) { 2249 Pattern 2250 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 2251 do { 2252 Instance = cast<ClassTemplatePartialSpecializationDecl>( 2253 Instance->getCanonicalDecl()); 2254 if (Pattern == Instance) 2255 return true; 2256 Instance = Instance->getInstantiatedFromMember(); 2257 } while (Instance); 2258 2259 return false; 2260} 2261 2262static bool isInstantiationOf(CXXRecordDecl *Pattern, 2263 CXXRecordDecl *Instance) { 2264 Pattern = Pattern->getCanonicalDecl(); 2265 2266 do { 2267 Instance = Instance->getCanonicalDecl(); 2268 if (Pattern == Instance) return true; 2269 Instance = Instance->getInstantiatedFromMemberClass(); 2270 } while (Instance); 2271 2272 return false; 2273} 2274 2275static bool isInstantiationOf(FunctionDecl *Pattern, 2276 FunctionDecl *Instance) { 2277 Pattern = Pattern->getCanonicalDecl(); 2278 2279 do { 2280 Instance = Instance->getCanonicalDecl(); 2281 if (Pattern == Instance) return true; 2282 Instance = Instance->getInstantiatedFromMemberFunction(); 2283 } while (Instance); 2284 2285 return false; 2286} 2287 2288static bool isInstantiationOf(EnumDecl *Pattern, 2289 EnumDecl *Instance) { 2290 Pattern = Pattern->getCanonicalDecl(); 2291 2292 do { 2293 Instance = Instance->getCanonicalDecl(); 2294 if (Pattern == Instance) return true; 2295 Instance = Instance->getInstantiatedFromMemberEnum(); 2296 } while (Instance); 2297 2298 return false; 2299} 2300 2301static bool isInstantiationOf(UsingShadowDecl *Pattern, 2302 UsingShadowDecl *Instance, 2303 ASTContext &C) { 2304 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 2305} 2306 2307static bool isInstantiationOf(UsingDecl *Pattern, 2308 UsingDecl *Instance, 2309 ASTContext &C) { 2310 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2311} 2312 2313static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 2314 UsingDecl *Instance, 2315 ASTContext &C) { 2316 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2317} 2318 2319static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 2320 UsingDecl *Instance, 2321 ASTContext &C) { 2322 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2323} 2324 2325static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 2326 VarDecl *Instance) { 2327 assert(Instance->isStaticDataMember()); 2328 2329 Pattern = Pattern->getCanonicalDecl(); 2330 2331 do { 2332 Instance = Instance->getCanonicalDecl(); 2333 if (Pattern == Instance) return true; 2334 Instance = Instance->getInstantiatedFromStaticDataMember(); 2335 } while (Instance); 2336 2337 return false; 2338} 2339 2340// Other is the prospective instantiation 2341// D is the prospective pattern 2342static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 2343 if (D->getKind() != Other->getKind()) { 2344 if (UnresolvedUsingTypenameDecl *UUD 2345 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 2346 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2347 return isInstantiationOf(UUD, UD, Ctx); 2348 } 2349 } 2350 2351 if (UnresolvedUsingValueDecl *UUD 2352 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 2353 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2354 return isInstantiationOf(UUD, UD, Ctx); 2355 } 2356 } 2357 2358 return false; 2359 } 2360 2361 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 2362 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 2363 2364 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 2365 return isInstantiationOf(cast<FunctionDecl>(D), Function); 2366 2367 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 2368 return isInstantiationOf(cast<EnumDecl>(D), Enum); 2369 2370 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 2371 if (Var->isStaticDataMember()) 2372 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 2373 2374 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 2375 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 2376 2377 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 2378 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 2379 2380 if (ClassTemplatePartialSpecializationDecl *PartialSpec 2381 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 2382 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 2383 PartialSpec); 2384 2385 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 2386 if (!Field->getDeclName()) { 2387 // This is an unnamed field. 2388 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 2389 cast<FieldDecl>(D); 2390 } 2391 } 2392 2393 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 2394 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 2395 2396 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 2397 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 2398 2399 return D->getDeclName() && isa<NamedDecl>(Other) && 2400 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 2401} 2402 2403template<typename ForwardIterator> 2404static NamedDecl *findInstantiationOf(ASTContext &Ctx, 2405 NamedDecl *D, 2406 ForwardIterator first, 2407 ForwardIterator last) { 2408 for (; first != last; ++first) 2409 if (isInstantiationOf(Ctx, D, *first)) 2410 return cast<NamedDecl>(*first); 2411 2412 return 0; 2413} 2414 2415/// \brief Finds the instantiation of the given declaration context 2416/// within the current instantiation. 2417/// 2418/// \returns NULL if there was an error 2419DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 2420 const MultiLevelTemplateArgumentList &TemplateArgs) { 2421 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 2422 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 2423 return cast_or_null<DeclContext>(ID); 2424 } else return DC; 2425} 2426 2427/// \brief Find the instantiation of the given declaration within the 2428/// current instantiation. 2429/// 2430/// This routine is intended to be used when \p D is a declaration 2431/// referenced from within a template, that needs to mapped into the 2432/// corresponding declaration within an instantiation. For example, 2433/// given: 2434/// 2435/// \code 2436/// template<typename T> 2437/// struct X { 2438/// enum Kind { 2439/// KnownValue = sizeof(T) 2440/// }; 2441/// 2442/// bool getKind() const { return KnownValue; } 2443/// }; 2444/// 2445/// template struct X<int>; 2446/// \endcode 2447/// 2448/// In the instantiation of X<int>::getKind(), we need to map the 2449/// EnumConstantDecl for KnownValue (which refers to 2450/// X<T>::<Kind>::KnownValue) to its instantiation 2451/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 2452/// this mapping from within the instantiation of X<int>. 2453NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 2454 const MultiLevelTemplateArgumentList &TemplateArgs) { 2455 DeclContext *ParentDC = D->getDeclContext(); 2456 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 2457 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 2458 ParentDC->isFunctionOrMethod()) { 2459 // D is a local of some kind. Look into the map of local 2460 // declarations to their instantiations. 2461 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 2462 } 2463 2464 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 2465 if (!Record->isDependentContext()) 2466 return D; 2467 2468 // If the RecordDecl is actually the injected-class-name or a 2469 // "templated" declaration for a class template, class template 2470 // partial specialization, or a member class of a class template, 2471 // substitute into the injected-class-name of the class template 2472 // or partial specialization to find the new DeclContext. 2473 QualType T; 2474 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 2475 2476 if (ClassTemplate) { 2477 T = ClassTemplate->getInjectedClassNameSpecialization(Context); 2478 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2479 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 2480 ClassTemplate = PartialSpec->getSpecializedTemplate(); 2481 2482 // If we call SubstType with an InjectedClassNameType here we 2483 // can end up in an infinite loop. 2484 T = Context.getTypeDeclType(Record); 2485 assert(isa<InjectedClassNameType>(T) && 2486 "type of partial specialization is not an InjectedClassNameType"); 2487 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 2488 } 2489 2490 if (!T.isNull()) { 2491 // Substitute into the injected-class-name to get the type 2492 // corresponding to the instantiation we want, which may also be 2493 // the current instantiation (if we're in a template 2494 // definition). This substitution should never fail, since we 2495 // know we can instantiate the injected-class-name or we 2496 // wouldn't have gotten to the injected-class-name! 2497 2498 // FIXME: Can we use the CurrentInstantiationScope to avoid this 2499 // extra instantiation in the common case? 2500 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName()); 2501 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail."); 2502 2503 if (!T->isDependentType()) { 2504 assert(T->isRecordType() && "Instantiation must produce a record type"); 2505 return T->getAs<RecordType>()->getDecl(); 2506 } 2507 2508 // We are performing "partial" template instantiation to create 2509 // the member declarations for the members of a class template 2510 // specialization. Therefore, D is actually referring to something 2511 // in the current instantiation. Look through the current 2512 // context, which contains actual instantiations, to find the 2513 // instantiation of the "current instantiation" that D refers 2514 // to. 2515 bool SawNonDependentContext = false; 2516 for (DeclContext *DC = CurContext; !DC->isFileContext(); 2517 DC = DC->getParent()) { 2518 if (ClassTemplateSpecializationDecl *Spec 2519 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 2520 if (isInstantiationOf(ClassTemplate, 2521 Spec->getSpecializedTemplate())) 2522 return Spec; 2523 2524 if (!DC->isDependentContext()) 2525 SawNonDependentContext = true; 2526 } 2527 2528 // We're performing "instantiation" of a member of the current 2529 // instantiation while we are type-checking the 2530 // definition. Compute the declaration context and return that. 2531 assert(!SawNonDependentContext && 2532 "No dependent context while instantiating record"); 2533 DeclContext *DC = computeDeclContext(T); 2534 assert(DC && 2535 "Unable to find declaration for the current instantiation"); 2536 return cast<CXXRecordDecl>(DC); 2537 } 2538 2539 // Fall through to deal with other dependent record types (e.g., 2540 // anonymous unions in class templates). 2541 } 2542 2543 if (!ParentDC->isDependentContext()) 2544 return D; 2545 2546 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 2547 if (!ParentDC) 2548 return 0; 2549 2550 if (ParentDC != D->getDeclContext()) { 2551 // We performed some kind of instantiation in the parent context, 2552 // so now we need to look into the instantiated parent context to 2553 // find the instantiation of the declaration D. 2554 2555 // If our context used to be dependent, we may need to instantiate 2556 // it before performing lookup into that context. 2557 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 2558 if (!Spec->isDependentContext()) { 2559 QualType T = Context.getTypeDeclType(Spec); 2560 const RecordType *Tag = T->getAs<RecordType>(); 2561 assert(Tag && "type of non-dependent record is not a RecordType"); 2562 if (!Tag->isBeingDefined() && 2563 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 2564 return 0; 2565 } 2566 } 2567 2568 NamedDecl *Result = 0; 2569 if (D->getDeclName()) { 2570 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 2571 Result = findInstantiationOf(Context, D, Found.first, Found.second); 2572 } else { 2573 // Since we don't have a name for the entity we're looking for, 2574 // our only option is to walk through all of the declarations to 2575 // find that name. This will occur in a few cases: 2576 // 2577 // - anonymous struct/union within a template 2578 // - unnamed class/struct/union/enum within a template 2579 // 2580 // FIXME: Find a better way to find these instantiations! 2581 Result = findInstantiationOf(Context, D, 2582 ParentDC->decls_begin(), 2583 ParentDC->decls_end()); 2584 } 2585 2586 // UsingShadowDecls can instantiate to nothing because of using hiding. 2587 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() || 2588 cast<Decl>(ParentDC)->isInvalidDecl()) 2589 && "Unable to find instantiation of declaration!"); 2590 2591 D = Result; 2592 } 2593 2594 return D; 2595} 2596 2597/// \brief Performs template instantiation for all implicit template 2598/// instantiations we have seen until this point. 2599void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) { 2600 while (!PendingLocalImplicitInstantiations.empty() || 2601 (!LocalOnly && !PendingImplicitInstantiations.empty())) { 2602 PendingImplicitInstantiation Inst; 2603 2604 if (PendingLocalImplicitInstantiations.empty()) { 2605 Inst = PendingImplicitInstantiations.front(); 2606 PendingImplicitInstantiations.pop_front(); 2607 } else { 2608 Inst = PendingLocalImplicitInstantiations.front(); 2609 PendingLocalImplicitInstantiations.pop_front(); 2610 } 2611 2612 // Instantiate function definitions 2613 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 2614 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function), 2615 Function->getLocation(), *this, 2616 Context.getSourceManager(), 2617 "instantiating function definition"); 2618 2619 if (!Function->getBody()) 2620 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 2621 continue; 2622 } 2623 2624 // Instantiate static data member definitions. 2625 VarDecl *Var = cast<VarDecl>(Inst.first); 2626 assert(Var->isStaticDataMember() && "Not a static data member?"); 2627 2628 // Don't try to instantiate declarations if the most recent redeclaration 2629 // is invalid. 2630 if (Var->getMostRecentDeclaration()->isInvalidDecl()) 2631 continue; 2632 2633 // Check if the most recent declaration has changed the specialization kind 2634 // and removed the need for implicit instantiation. 2635 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) { 2636 case TSK_Undeclared: 2637 assert(false && "Cannot instantitiate an undeclared specialization."); 2638 case TSK_ExplicitInstantiationDeclaration: 2639 case TSK_ExplicitInstantiationDefinition: 2640 case TSK_ExplicitSpecialization: 2641 continue; // No longer need implicit instantiation. 2642 case TSK_ImplicitInstantiation: 2643 break; 2644 } 2645 2646 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var), 2647 Var->getLocation(), *this, 2648 Context.getSourceManager(), 2649 "instantiating static data member " 2650 "definition"); 2651 2652 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 2653 } 2654} 2655 2656void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 2657 const MultiLevelTemplateArgumentList &TemplateArgs) { 2658 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(), 2659 E = Pattern->ddiag_end(); I != E; ++I) { 2660 DependentDiagnostic *DD = *I; 2661 2662 switch (DD->getKind()) { 2663 case DependentDiagnostic::Access: 2664 HandleDependentAccessCheck(*DD, TemplateArgs); 2665 break; 2666 } 2667 } 2668} 2669