SemaTemplateInstantiateDecl.cpp revision f88b0d6c99e6473e78331271935986535dc4603c
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 623namespace { 624 class SortDeclByLocation { 625 SourceManager &SourceMgr; 626 627 public: 628 explicit SortDeclByLocation(SourceManager &SourceMgr) 629 : SourceMgr(SourceMgr) { } 630 631 bool operator()(const Decl *X, const Decl *Y) const { 632 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(), 633 Y->getLocation()); 634 } 635 }; 636} 637 638Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 639 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 640 641 // Create a local instantiation scope for this class template, which 642 // will contain the instantiations of the template parameters. 643 Sema::LocalInstantiationScope Scope(SemaRef); 644 TemplateParameterList *TempParams = D->getTemplateParameters(); 645 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 646 if (!InstParams) 647 return NULL; 648 649 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 650 651 // Instantiate the qualifier. We have to do this first in case 652 // we're a friend declaration, because if we are then we need to put 653 // the new declaration in the appropriate context. 654 NestedNameSpecifier *Qualifier = Pattern->getQualifier(); 655 if (Qualifier) { 656 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 657 Pattern->getQualifierRange(), 658 TemplateArgs); 659 if (!Qualifier) return 0; 660 } 661 662 CXXRecordDecl *PrevDecl = 0; 663 ClassTemplateDecl *PrevClassTemplate = 0; 664 665 // If this isn't a friend, then it's a member template, in which 666 // case we just want to build the instantiation in the 667 // specialization. If it is a friend, we want to build it in 668 // the appropriate context. 669 DeclContext *DC = Owner; 670 if (isFriend) { 671 if (Qualifier) { 672 CXXScopeSpec SS; 673 SS.setScopeRep(Qualifier); 674 SS.setRange(Pattern->getQualifierRange()); 675 DC = SemaRef.computeDeclContext(SS); 676 if (!DC) return 0; 677 } else { 678 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 679 Pattern->getDeclContext(), 680 TemplateArgs); 681 } 682 683 // Look for a previous declaration of the template in the owning 684 // context. 685 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 686 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 687 SemaRef.LookupQualifiedName(R, DC); 688 689 if (R.isSingleResult()) { 690 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 691 if (PrevClassTemplate) 692 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 693 } 694 695 if (!PrevClassTemplate && Qualifier) { 696 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 697 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 698 << Pattern->getQualifierRange(); 699 return 0; 700 } 701 702 bool AdoptedPreviousTemplateParams = false; 703 if (PrevClassTemplate) { 704 bool Complain = true; 705 706 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 707 // template for struct std::tr1::__detail::_Map_base, where the 708 // template parameters of the friend declaration don't match the 709 // template parameters of the original declaration. In this one 710 // case, we don't complain about the ill-formed friend 711 // declaration. 712 if (isFriend && Pattern->getIdentifier() && 713 Pattern->getIdentifier()->isStr("_Map_base") && 714 DC->isNamespace() && 715 cast<NamespaceDecl>(DC)->getIdentifier() && 716 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 717 DeclContext *DCParent = DC->getParent(); 718 if (DCParent->isNamespace() && 719 cast<NamespaceDecl>(DCParent)->getIdentifier() && 720 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 721 DeclContext *DCParent2 = DCParent->getParent(); 722 if (DCParent2->isNamespace() && 723 cast<NamespaceDecl>(DCParent2)->getIdentifier() && 724 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") && 725 DCParent2->getParent()->isTranslationUnit()) 726 Complain = false; 727 } 728 } 729 730 TemplateParameterList *PrevParams 731 = PrevClassTemplate->getTemplateParameters(); 732 733 // Make sure the parameter lists match. 734 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 735 Complain, 736 Sema::TPL_TemplateMatch)) { 737 if (Complain) 738 return 0; 739 740 AdoptedPreviousTemplateParams = true; 741 InstParams = PrevParams; 742 } 743 744 // Do some additional validation, then merge default arguments 745 // from the existing declarations. 746 if (!AdoptedPreviousTemplateParams && 747 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 748 Sema::TPC_ClassTemplate)) 749 return 0; 750 } 751 } 752 753 CXXRecordDecl *RecordInst 754 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 755 Pattern->getLocation(), Pattern->getIdentifier(), 756 Pattern->getTagKeywordLoc(), PrevDecl, 757 /*DelayTypeCreation=*/true); 758 759 if (Qualifier) 760 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange()); 761 762 ClassTemplateDecl *Inst 763 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 764 D->getIdentifier(), InstParams, RecordInst, 765 PrevClassTemplate); 766 RecordInst->setDescribedClassTemplate(Inst); 767 768 if (isFriend) { 769 if (PrevClassTemplate) 770 Inst->setAccess(PrevClassTemplate->getAccess()); 771 else 772 Inst->setAccess(D->getAccess()); 773 774 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0); 775 // TODO: do we want to track the instantiation progeny of this 776 // friend target decl? 777 } else { 778 Inst->setAccess(D->getAccess()); 779 Inst->setInstantiatedFromMemberTemplate(D); 780 } 781 782 // Trigger creation of the type for the instantiation. 783 SemaRef.Context.getInjectedClassNameType(RecordInst, 784 Inst->getInjectedClassNameSpecialization(SemaRef.Context)); 785 786 // Finish handling of friends. 787 if (isFriend) { 788 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false); 789 return Inst; 790 } 791 792 Owner->addDecl(Inst); 793 794 // First, we sort the partial specializations by location, so 795 // that we instantiate them in the order they were declared. 796 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 797 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 798 P = D->getPartialSpecializations().begin(), 799 PEnd = D->getPartialSpecializations().end(); 800 P != PEnd; ++P) 801 PartialSpecs.push_back(&*P); 802 std::sort(PartialSpecs.begin(), PartialSpecs.end(), 803 SortDeclByLocation(SemaRef.SourceMgr)); 804 805 // Instantiate all of the partial specializations of this member class 806 // template. 807 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 808 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]); 809 810 return Inst; 811} 812 813Decl * 814TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 815 ClassTemplatePartialSpecializationDecl *D) { 816 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 817 818 // Lookup the already-instantiated declaration in the instantiation 819 // of the class template and return that. 820 DeclContext::lookup_result Found 821 = Owner->lookup(ClassTemplate->getDeclName()); 822 if (Found.first == Found.second) 823 return 0; 824 825 ClassTemplateDecl *InstClassTemplate 826 = dyn_cast<ClassTemplateDecl>(*Found.first); 827 if (!InstClassTemplate) 828 return 0; 829 830 Decl *DCanon = D->getCanonicalDecl(); 831 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 832 P = InstClassTemplate->getPartialSpecializations().begin(), 833 PEnd = InstClassTemplate->getPartialSpecializations().end(); 834 P != PEnd; ++P) { 835 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon) 836 return &*P; 837 } 838 839 return 0; 840} 841 842Decl * 843TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 844 // Create a local instantiation scope for this function template, which 845 // will contain the instantiations of the template parameters and then get 846 // merged with the local instantiation scope for the function template 847 // itself. 848 Sema::LocalInstantiationScope Scope(SemaRef); 849 850 TemplateParameterList *TempParams = D->getTemplateParameters(); 851 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 852 if (!InstParams) 853 return NULL; 854 855 FunctionDecl *Instantiated = 0; 856 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 857 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 858 InstParams)); 859 else 860 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 861 D->getTemplatedDecl(), 862 InstParams)); 863 864 if (!Instantiated) 865 return 0; 866 867 Instantiated->setAccess(D->getAccess()); 868 869 // Link the instantiated function template declaration to the function 870 // template from which it was instantiated. 871 FunctionTemplateDecl *InstTemplate 872 = Instantiated->getDescribedFunctionTemplate(); 873 InstTemplate->setAccess(D->getAccess()); 874 assert(InstTemplate && 875 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 876 877 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 878 879 // Link the instantiation back to the pattern *unless* this is a 880 // non-definition friend declaration. 881 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 882 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 883 InstTemplate->setInstantiatedFromMemberTemplate(D); 884 885 // Make declarations visible in the appropriate context. 886 if (!isFriend) 887 Owner->addDecl(InstTemplate); 888 889 return InstTemplate; 890} 891 892Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 893 CXXRecordDecl *PrevDecl = 0; 894 if (D->isInjectedClassName()) 895 PrevDecl = cast<CXXRecordDecl>(Owner); 896 else if (D->getPreviousDeclaration()) { 897 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 898 D->getPreviousDeclaration(), 899 TemplateArgs); 900 if (!Prev) return 0; 901 PrevDecl = cast<CXXRecordDecl>(Prev); 902 } 903 904 CXXRecordDecl *Record 905 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 906 D->getLocation(), D->getIdentifier(), 907 D->getTagKeywordLoc(), PrevDecl); 908 909 // Substitute the nested name specifier, if any. 910 if (SubstQualifier(D, Record)) 911 return 0; 912 913 Record->setImplicit(D->isImplicit()); 914 // FIXME: Check against AS_none is an ugly hack to work around the issue that 915 // the tag decls introduced by friend class declarations don't have an access 916 // specifier. Remove once this area of the code gets sorted out. 917 if (D->getAccess() != AS_none) 918 Record->setAccess(D->getAccess()); 919 if (!D->isInjectedClassName()) 920 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 921 922 // If the original function was part of a friend declaration, 923 // inherit its namespace state. 924 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 925 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 926 927 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion()); 928 929 Owner->addDecl(Record); 930 return Record; 931} 932 933/// Normal class members are of more specific types and therefore 934/// don't make it here. This function serves two purposes: 935/// 1) instantiating function templates 936/// 2) substituting friend declarations 937/// FIXME: preserve function definitions in case #2 938Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 939 TemplateParameterList *TemplateParams) { 940 // Check whether there is already a function template specialization for 941 // this declaration. 942 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 943 void *InsertPos = 0; 944 if (FunctionTemplate && !TemplateParams) { 945 llvm::FoldingSetNodeID ID; 946 FunctionTemplateSpecializationInfo::Profile(ID, 947 TemplateArgs.getInnermost().getFlatArgumentList(), 948 TemplateArgs.getInnermost().flat_size(), 949 SemaRef.Context); 950 951 FunctionTemplateSpecializationInfo *Info 952 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 953 InsertPos); 954 955 // If we already have a function template specialization, return it. 956 if (Info) 957 return Info->Function; 958 } 959 960 bool isFriend; 961 if (FunctionTemplate) 962 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 963 else 964 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 965 966 bool MergeWithParentScope = (TemplateParams != 0) || 967 !(isa<Decl>(Owner) && 968 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 969 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 970 971 llvm::SmallVector<ParmVarDecl *, 4> Params; 972 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 973 TInfo = SubstFunctionType(D, Params); 974 if (!TInfo) 975 return 0; 976 QualType T = TInfo->getType(); 977 978 NestedNameSpecifier *Qualifier = D->getQualifier(); 979 if (Qualifier) { 980 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 981 D->getQualifierRange(), 982 TemplateArgs); 983 if (!Qualifier) return 0; 984 } 985 986 // If we're instantiating a local function declaration, put the result 987 // in the owner; otherwise we need to find the instantiated context. 988 DeclContext *DC; 989 if (D->getDeclContext()->isFunctionOrMethod()) 990 DC = Owner; 991 else if (isFriend && Qualifier) { 992 CXXScopeSpec SS; 993 SS.setScopeRep(Qualifier); 994 SS.setRange(D->getQualifierRange()); 995 DC = SemaRef.computeDeclContext(SS); 996 if (!DC) return 0; 997 } else { 998 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 999 TemplateArgs); 1000 } 1001 1002 FunctionDecl *Function = 1003 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(), 1004 D->getDeclName(), T, TInfo, 1005 D->getStorageClass(), D->getStorageClassAsWritten(), 1006 D->isInlineSpecified(), D->hasWrittenPrototype()); 1007 1008 if (Qualifier) 1009 Function->setQualifierInfo(Qualifier, D->getQualifierRange()); 1010 1011 DeclContext *LexicalDC = Owner; 1012 if (!isFriend && D->isOutOfLine()) { 1013 assert(D->getDeclContext()->isFileContext()); 1014 LexicalDC = D->getDeclContext(); 1015 } 1016 1017 Function->setLexicalDeclContext(LexicalDC); 1018 1019 // Attach the parameters 1020 for (unsigned P = 0; P < Params.size(); ++P) 1021 Params[P]->setOwningFunction(Function); 1022 Function->setParams(Params.data(), Params.size()); 1023 1024 if (TemplateParams) { 1025 // Our resulting instantiation is actually a function template, since we 1026 // are substituting only the outer template parameters. For example, given 1027 // 1028 // template<typename T> 1029 // struct X { 1030 // template<typename U> friend void f(T, U); 1031 // }; 1032 // 1033 // X<int> x; 1034 // 1035 // We are instantiating the friend function template "f" within X<int>, 1036 // which means substituting int for T, but leaving "f" as a friend function 1037 // template. 1038 // Build the function template itself. 1039 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1040 Function->getLocation(), 1041 Function->getDeclName(), 1042 TemplateParams, Function); 1043 Function->setDescribedFunctionTemplate(FunctionTemplate); 1044 1045 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1046 1047 if (isFriend && D->isThisDeclarationADefinition()) { 1048 // TODO: should we remember this connection regardless of whether 1049 // the friend declaration provided a body? 1050 FunctionTemplate->setInstantiatedFromMemberTemplate( 1051 D->getDescribedFunctionTemplate()); 1052 } 1053 } else if (FunctionTemplate) { 1054 // Record this function template specialization. 1055 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1056 &TemplateArgs.getInnermost(), 1057 InsertPos); 1058 } else if (isFriend && D->isThisDeclarationADefinition()) { 1059 // TODO: should we remember this connection regardless of whether 1060 // the friend declaration provided a body? 1061 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1062 } 1063 1064 if (InitFunctionInstantiation(Function, D)) 1065 Function->setInvalidDecl(); 1066 1067 bool Redeclaration = false; 1068 bool OverloadableAttrRequired = false; 1069 bool isExplicitSpecialization = false; 1070 1071 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(), 1072 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 1073 1074 if (DependentFunctionTemplateSpecializationInfo *Info 1075 = D->getDependentSpecializationInfo()) { 1076 assert(isFriend && "non-friend has dependent specialization info?"); 1077 1078 // This needs to be set now for future sanity. 1079 Function->setObjectOfFriendDecl(/*HasPrevious*/ true); 1080 1081 // Instantiate the explicit template arguments. 1082 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1083 Info->getRAngleLoc()); 1084 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) { 1085 TemplateArgumentLoc Loc; 1086 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs)) 1087 return 0; 1088 1089 ExplicitArgs.addArgument(Loc); 1090 } 1091 1092 // Map the candidate templates to their instantiations. 1093 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1094 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1095 Info->getTemplate(I), 1096 TemplateArgs); 1097 if (!Temp) return 0; 1098 1099 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1100 } 1101 1102 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1103 &ExplicitArgs, 1104 Previous)) 1105 Function->setInvalidDecl(); 1106 1107 isExplicitSpecialization = true; 1108 1109 } else if (TemplateParams || !FunctionTemplate) { 1110 // Look only into the namespace where the friend would be declared to 1111 // find a previous declaration. This is the innermost enclosing namespace, 1112 // as described in ActOnFriendFunctionDecl. 1113 SemaRef.LookupQualifiedName(Previous, DC); 1114 1115 // In C++, the previous declaration we find might be a tag type 1116 // (class or enum). In this case, the new declaration will hide the 1117 // tag type. Note that this does does not apply if we're declaring a 1118 // typedef (C++ [dcl.typedef]p4). 1119 if (Previous.isSingleTagDecl()) 1120 Previous.clear(); 1121 } 1122 1123 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 1124 isExplicitSpecialization, Redeclaration, 1125 /*FIXME:*/OverloadableAttrRequired); 1126 1127 // If the original function was part of a friend declaration, 1128 // inherit its namespace state and add it to the owner. 1129 if (isFriend) { 1130 NamedDecl *ToFriendD = 0; 1131 NamedDecl *PrevDecl; 1132 if (TemplateParams) { 1133 ToFriendD = cast<NamedDecl>(FunctionTemplate); 1134 PrevDecl = FunctionTemplate->getPreviousDeclaration(); 1135 } else { 1136 ToFriendD = Function; 1137 PrevDecl = Function->getPreviousDeclaration(); 1138 } 1139 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL); 1140 DC->makeDeclVisibleInContext(ToFriendD, /*Recoverable=*/ false); 1141 } 1142 1143 if (Function->isOverloadedOperator() && !DC->isRecord() && 1144 Function->isInIdentifierNamespace(Decl::IDNS_Ordinary)) { 1145 Function->setNonMemberOperator(); 1146 if (FunctionTemplate) FunctionTemplate->setNonMemberOperator(); 1147 } 1148 1149 return Function; 1150} 1151 1152Decl * 1153TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 1154 TemplateParameterList *TemplateParams) { 1155 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1156 void *InsertPos = 0; 1157 if (FunctionTemplate && !TemplateParams) { 1158 // We are creating a function template specialization from a function 1159 // template. Check whether there is already a function template 1160 // specialization for this particular set of template arguments. 1161 llvm::FoldingSetNodeID ID; 1162 FunctionTemplateSpecializationInfo::Profile(ID, 1163 TemplateArgs.getInnermost().getFlatArgumentList(), 1164 TemplateArgs.getInnermost().flat_size(), 1165 SemaRef.Context); 1166 1167 FunctionTemplateSpecializationInfo *Info 1168 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 1169 InsertPos); 1170 1171 // If we already have a function template specialization, return it. 1172 if (Info) 1173 return Info->Function; 1174 } 1175 1176 bool isFriend; 1177 if (FunctionTemplate) 1178 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1179 else 1180 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1181 1182 bool MergeWithParentScope = (TemplateParams != 0) || 1183 !(isa<Decl>(Owner) && 1184 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1185 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1186 1187 llvm::SmallVector<ParmVarDecl *, 4> Params; 1188 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 1189 TInfo = SubstFunctionType(D, Params); 1190 if (!TInfo) 1191 return 0; 1192 QualType T = TInfo->getType(); 1193 1194 NestedNameSpecifier *Qualifier = D->getQualifier(); 1195 if (Qualifier) { 1196 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 1197 D->getQualifierRange(), 1198 TemplateArgs); 1199 if (!Qualifier) return 0; 1200 } 1201 1202 DeclContext *DC = Owner; 1203 if (isFriend) { 1204 if (Qualifier) { 1205 CXXScopeSpec SS; 1206 SS.setScopeRep(Qualifier); 1207 SS.setRange(D->getQualifierRange()); 1208 DC = SemaRef.computeDeclContext(SS); 1209 } else { 1210 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 1211 D->getDeclContext(), 1212 TemplateArgs); 1213 } 1214 if (!DC) return 0; 1215 } 1216 1217 // Build the instantiated method declaration. 1218 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1219 CXXMethodDecl *Method = 0; 1220 1221 DeclarationName Name = D->getDeclName(); 1222 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1223 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 1224 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName( 1225 SemaRef.Context.getCanonicalType(ClassTy)); 1226 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 1227 Constructor->getLocation(), 1228 Name, T, TInfo, 1229 Constructor->isExplicit(), 1230 Constructor->isInlineSpecified(), 1231 false); 1232 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 1233 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 1234 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName( 1235 SemaRef.Context.getCanonicalType(ClassTy)); 1236 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 1237 Destructor->getLocation(), Name, 1238 T, Destructor->isInlineSpecified(), 1239 false); 1240 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 1241 CanQualType ConvTy 1242 = SemaRef.Context.getCanonicalType( 1243 T->getAs<FunctionType>()->getResultType()); 1244 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName( 1245 ConvTy); 1246 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 1247 Conversion->getLocation(), Name, 1248 T, TInfo, 1249 Conversion->isInlineSpecified(), 1250 Conversion->isExplicit()); 1251 } else { 1252 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 1253 D->getDeclName(), T, TInfo, 1254 D->isStatic(), 1255 D->getStorageClassAsWritten(), 1256 D->isInlineSpecified()); 1257 } 1258 1259 if (Qualifier) 1260 Method->setQualifierInfo(Qualifier, D->getQualifierRange()); 1261 1262 if (TemplateParams) { 1263 // Our resulting instantiation is actually a function template, since we 1264 // are substituting only the outer template parameters. For example, given 1265 // 1266 // template<typename T> 1267 // struct X { 1268 // template<typename U> void f(T, U); 1269 // }; 1270 // 1271 // X<int> x; 1272 // 1273 // We are instantiating the member template "f" within X<int>, which means 1274 // substituting int for T, but leaving "f" as a member function template. 1275 // Build the function template itself. 1276 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 1277 Method->getLocation(), 1278 Method->getDeclName(), 1279 TemplateParams, Method); 1280 if (isFriend) { 1281 FunctionTemplate->setLexicalDeclContext(Owner); 1282 FunctionTemplate->setObjectOfFriendDecl(true); 1283 } else if (D->isOutOfLine()) 1284 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 1285 Method->setDescribedFunctionTemplate(FunctionTemplate); 1286 } else if (FunctionTemplate) { 1287 // Record this function template specialization. 1288 Method->setFunctionTemplateSpecialization(FunctionTemplate, 1289 &TemplateArgs.getInnermost(), 1290 InsertPos); 1291 } else if (!isFriend) { 1292 // Record that this is an instantiation of a member function. 1293 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1294 } 1295 1296 // If we are instantiating a member function defined 1297 // out-of-line, the instantiation will have the same lexical 1298 // context (which will be a namespace scope) as the template. 1299 if (isFriend) { 1300 Method->setLexicalDeclContext(Owner); 1301 Method->setObjectOfFriendDecl(true); 1302 } else if (D->isOutOfLine()) 1303 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 1304 1305 // Attach the parameters 1306 for (unsigned P = 0; P < Params.size(); ++P) 1307 Params[P]->setOwningFunction(Method); 1308 Method->setParams(Params.data(), Params.size()); 1309 1310 if (InitMethodInstantiation(Method, D)) 1311 Method->setInvalidDecl(); 1312 1313 LookupResult Previous(SemaRef, Name, SourceLocation(), 1314 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 1315 1316 if (!FunctionTemplate || TemplateParams || isFriend) { 1317 SemaRef.LookupQualifiedName(Previous, Record); 1318 1319 // In C++, the previous declaration we find might be a tag type 1320 // (class or enum). In this case, the new declaration will hide the 1321 // tag type. Note that this does does not apply if we're declaring a 1322 // typedef (C++ [dcl.typedef]p4). 1323 if (Previous.isSingleTagDecl()) 1324 Previous.clear(); 1325 } 1326 1327 bool Redeclaration = false; 1328 bool OverloadableAttrRequired = false; 1329 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration, 1330 /*FIXME:*/OverloadableAttrRequired); 1331 1332 if (D->isPure()) 1333 SemaRef.CheckPureMethod(Method, SourceRange()); 1334 1335 Method->setAccess(D->getAccess()); 1336 1337 if (FunctionTemplate) { 1338 // If there's a function template, let our caller handle it. 1339 } else if (Method->isInvalidDecl() && !Previous.empty()) { 1340 // Don't hide a (potentially) valid declaration with an invalid one. 1341 } else { 1342 NamedDecl *DeclToAdd = (TemplateParams 1343 ? cast<NamedDecl>(FunctionTemplate) 1344 : Method); 1345 if (isFriend) 1346 Record->makeDeclVisibleInContext(DeclToAdd); 1347 else 1348 Owner->addDecl(DeclToAdd); 1349 } 1350 1351 return Method; 1352} 1353 1354Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1355 return VisitCXXMethodDecl(D); 1356} 1357 1358Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1359 return VisitCXXMethodDecl(D); 1360} 1361 1362Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 1363 return VisitCXXMethodDecl(D); 1364} 1365 1366ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 1367 return SemaRef.SubstParmVarDecl(D, TemplateArgs); 1368} 1369 1370Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1371 TemplateTypeParmDecl *D) { 1372 // TODO: don't always clone when decls are refcounted. 1373 const Type* T = D->getTypeForDecl(); 1374 assert(T->isTemplateTypeParmType()); 1375 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>(); 1376 1377 TemplateTypeParmDecl *Inst = 1378 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1379 TTPT->getDepth() - 1, TTPT->getIndex(), 1380 TTPT->getName(), 1381 D->wasDeclaredWithTypename(), 1382 D->isParameterPack()); 1383 1384 if (D->hasDefaultArgument()) 1385 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 1386 1387 // Introduce this template parameter's instantiation into the instantiation 1388 // scope. 1389 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1390 1391 return Inst; 1392} 1393 1394Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1395 NonTypeTemplateParmDecl *D) { 1396 // Substitute into the type of the non-type template parameter. 1397 QualType T; 1398 TypeSourceInfo *DI = D->getTypeSourceInfo(); 1399 if (DI) { 1400 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 1401 D->getDeclName()); 1402 if (DI) T = DI->getType(); 1403 } else { 1404 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 1405 D->getDeclName()); 1406 DI = 0; 1407 } 1408 if (T.isNull()) 1409 return 0; 1410 1411 // Check that this type is acceptable for a non-type template parameter. 1412 bool Invalid = false; 1413 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation()); 1414 if (T.isNull()) { 1415 T = SemaRef.Context.IntTy; 1416 Invalid = true; 1417 } 1418 1419 NonTypeTemplateParmDecl *Param 1420 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1421 D->getDepth() - 1, D->getPosition(), 1422 D->getIdentifier(), T, DI); 1423 if (Invalid) 1424 Param->setInvalidDecl(); 1425 1426 Param->setDefaultArgument(D->getDefaultArgument()); 1427 1428 // Introduce this template parameter's instantiation into the instantiation 1429 // scope. 1430 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1431 return Param; 1432} 1433 1434Decl * 1435TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1436 TemplateTemplateParmDecl *D) { 1437 // Instantiate the template parameter list of the template template parameter. 1438 TemplateParameterList *TempParams = D->getTemplateParameters(); 1439 TemplateParameterList *InstParams; 1440 { 1441 // Perform the actual substitution of template parameters within a new, 1442 // local instantiation scope. 1443 Sema::LocalInstantiationScope Scope(SemaRef); 1444 InstParams = SubstTemplateParams(TempParams); 1445 if (!InstParams) 1446 return NULL; 1447 } 1448 1449 // Build the template template parameter. 1450 TemplateTemplateParmDecl *Param 1451 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1452 D->getDepth() - 1, D->getPosition(), 1453 D->getIdentifier(), InstParams); 1454 Param->setDefaultArgument(D->getDefaultArgument()); 1455 1456 // Introduce this template parameter's instantiation into the instantiation 1457 // scope. 1458 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1459 1460 return Param; 1461} 1462 1463Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1464 // Using directives are never dependent, so they require no explicit 1465 1466 UsingDirectiveDecl *Inst 1467 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1468 D->getNamespaceKeyLocation(), 1469 D->getQualifierRange(), D->getQualifier(), 1470 D->getIdentLocation(), 1471 D->getNominatedNamespace(), 1472 D->getCommonAncestor()); 1473 Owner->addDecl(Inst); 1474 return Inst; 1475} 1476 1477Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 1478 // The nested name specifier is non-dependent, so no transformation 1479 // is required. 1480 1481 // We only need to do redeclaration lookups if we're in a class 1482 // scope (in fact, it's not really even possible in non-class 1483 // scopes). 1484 bool CheckRedeclaration = Owner->isRecord(); 1485 1486 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(), 1487 Sema::LookupUsingDeclName, Sema::ForRedeclaration); 1488 1489 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 1490 D->getLocation(), 1491 D->getNestedNameRange(), 1492 D->getUsingLocation(), 1493 D->getTargetNestedNameDecl(), 1494 D->getDeclName(), 1495 D->isTypeName()); 1496 1497 CXXScopeSpec SS; 1498 SS.setScopeRep(D->getTargetNestedNameDecl()); 1499 SS.setRange(D->getNestedNameRange()); 1500 1501 if (CheckRedeclaration) { 1502 Prev.setHideTags(false); 1503 SemaRef.LookupQualifiedName(Prev, Owner); 1504 1505 // Check for invalid redeclarations. 1506 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(), 1507 D->isTypeName(), SS, 1508 D->getLocation(), Prev)) 1509 NewUD->setInvalidDecl(); 1510 1511 } 1512 1513 if (!NewUD->isInvalidDecl() && 1514 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS, 1515 D->getLocation())) 1516 NewUD->setInvalidDecl(); 1517 1518 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 1519 NewUD->setAccess(D->getAccess()); 1520 Owner->addDecl(NewUD); 1521 1522 // Don't process the shadow decls for an invalid decl. 1523 if (NewUD->isInvalidDecl()) 1524 return NewUD; 1525 1526 bool isFunctionScope = Owner->isFunctionOrMethod(); 1527 1528 // Process the shadow decls. 1529 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 1530 I != E; ++I) { 1531 UsingShadowDecl *Shadow = *I; 1532 NamedDecl *InstTarget = 1533 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(), 1534 Shadow->getTargetDecl(), 1535 TemplateArgs)); 1536 1537 if (CheckRedeclaration && 1538 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev)) 1539 continue; 1540 1541 UsingShadowDecl *InstShadow 1542 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget); 1543 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 1544 1545 if (isFunctionScope) 1546 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 1547 } 1548 1549 return NewUD; 1550} 1551 1552Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 1553 // Ignore these; we handle them in bulk when processing the UsingDecl. 1554 return 0; 1555} 1556 1557Decl * TemplateDeclInstantiator 1558 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *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*/ true, D->getTypenameLoc()); 1576 if (UD) 1577 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1578 1579 return UD; 1580} 1581 1582Decl * TemplateDeclInstantiator 1583 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1584 NestedNameSpecifier *NNS = 1585 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1586 D->getTargetNestedNameRange(), 1587 TemplateArgs); 1588 if (!NNS) 1589 return 0; 1590 1591 CXXScopeSpec SS; 1592 SS.setRange(D->getTargetNestedNameRange()); 1593 SS.setScopeRep(NNS); 1594 1595 NamedDecl *UD = 1596 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1597 D->getUsingLoc(), SS, D->getLocation(), 1598 D->getDeclName(), 0, 1599 /*instantiation*/ true, 1600 /*typename*/ false, SourceLocation()); 1601 if (UD) 1602 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1603 1604 return UD; 1605} 1606 1607Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 1608 const MultiLevelTemplateArgumentList &TemplateArgs) { 1609 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 1610 if (D->isInvalidDecl()) 1611 return 0; 1612 1613 return Instantiator.Visit(D); 1614} 1615 1616/// \brief Instantiates a nested template parameter list in the current 1617/// instantiation context. 1618/// 1619/// \param L The parameter list to instantiate 1620/// 1621/// \returns NULL if there was an error 1622TemplateParameterList * 1623TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 1624 // Get errors for all the parameters before bailing out. 1625 bool Invalid = false; 1626 1627 unsigned N = L->size(); 1628 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector; 1629 ParamVector Params; 1630 Params.reserve(N); 1631 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 1632 PI != PE; ++PI) { 1633 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 1634 Params.push_back(D); 1635 Invalid = Invalid || !D || D->isInvalidDecl(); 1636 } 1637 1638 // Clean up if we had an error. 1639 if (Invalid) { 1640 for (ParamVector::iterator PI = Params.begin(), PE = Params.end(); 1641 PI != PE; ++PI) 1642 if (*PI) 1643 (*PI)->Destroy(SemaRef.Context); 1644 return NULL; 1645 } 1646 1647 TemplateParameterList *InstL 1648 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 1649 L->getLAngleLoc(), &Params.front(), N, 1650 L->getRAngleLoc()); 1651 return InstL; 1652} 1653 1654/// \brief Instantiate the declaration of a class template partial 1655/// specialization. 1656/// 1657/// \param ClassTemplate the (instantiated) class template that is partially 1658// specialized by the instantiation of \p PartialSpec. 1659/// 1660/// \param PartialSpec the (uninstantiated) class template partial 1661/// specialization that we are instantiating. 1662/// 1663/// \returns true if there was an error, false otherwise. 1664bool 1665TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 1666 ClassTemplateDecl *ClassTemplate, 1667 ClassTemplatePartialSpecializationDecl *PartialSpec) { 1668 // Create a local instantiation scope for this class template partial 1669 // specialization, which will contain the instantiations of the template 1670 // parameters. 1671 Sema::LocalInstantiationScope Scope(SemaRef); 1672 1673 // Substitute into the template parameters of the class template partial 1674 // specialization. 1675 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 1676 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1677 if (!InstParams) 1678 return true; 1679 1680 // Substitute into the template arguments of the class template partial 1681 // specialization. 1682 const TemplateArgumentLoc *PartialSpecTemplateArgs 1683 = PartialSpec->getTemplateArgsAsWritten(); 1684 unsigned N = PartialSpec->getNumTemplateArgsAsWritten(); 1685 1686 TemplateArgumentListInfo InstTemplateArgs; // no angle locations 1687 for (unsigned I = 0; I != N; ++I) { 1688 TemplateArgumentLoc Loc; 1689 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs)) 1690 return true; 1691 InstTemplateArgs.addArgument(Loc); 1692 } 1693 1694 1695 // Check that the template argument list is well-formed for this 1696 // class template. 1697 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 1698 InstTemplateArgs.size()); 1699 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 1700 PartialSpec->getLocation(), 1701 InstTemplateArgs, 1702 false, 1703 Converted)) 1704 return true; 1705 1706 // Figure out where to insert this class template partial specialization 1707 // in the member template's set of class template partial specializations. 1708 llvm::FoldingSetNodeID ID; 1709 ClassTemplatePartialSpecializationDecl::Profile(ID, 1710 Converted.getFlatArguments(), 1711 Converted.flatSize(), 1712 SemaRef.Context); 1713 void *InsertPos = 0; 1714 ClassTemplateSpecializationDecl *PrevDecl 1715 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 1716 InsertPos); 1717 1718 // Build the canonical type that describes the converted template 1719 // arguments of the class template partial specialization. 1720 QualType CanonType 1721 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1722 Converted.getFlatArguments(), 1723 Converted.flatSize()); 1724 1725 // Build the fully-sugared type for this class template 1726 // specialization as the user wrote in the specialization 1727 // itself. This means that we'll pretty-print the type retrieved 1728 // from the specialization's declaration the way that the user 1729 // actually wrote the specialization, rather than formatting the 1730 // name based on the "canonical" representation used to store the 1731 // template arguments in the specialization. 1732 TypeSourceInfo *WrittenTy 1733 = SemaRef.Context.getTemplateSpecializationTypeInfo( 1734 TemplateName(ClassTemplate), 1735 PartialSpec->getLocation(), 1736 InstTemplateArgs, 1737 CanonType); 1738 1739 if (PrevDecl) { 1740 // We've already seen a partial specialization with the same template 1741 // parameters and template arguments. This can happen, for example, when 1742 // substituting the outer template arguments ends up causing two 1743 // class template partial specializations of a member class template 1744 // to have identical forms, e.g., 1745 // 1746 // template<typename T, typename U> 1747 // struct Outer { 1748 // template<typename X, typename Y> struct Inner; 1749 // template<typename Y> struct Inner<T, Y>; 1750 // template<typename Y> struct Inner<U, Y>; 1751 // }; 1752 // 1753 // Outer<int, int> outer; // error: the partial specializations of Inner 1754 // // have the same signature. 1755 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 1756 << WrittenTy; 1757 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 1758 << SemaRef.Context.getTypeDeclType(PrevDecl); 1759 return true; 1760 } 1761 1762 1763 // Create the class template partial specialization declaration. 1764 ClassTemplatePartialSpecializationDecl *InstPartialSpec 1765 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner, 1766 PartialSpec->getLocation(), 1767 InstParams, 1768 ClassTemplate, 1769 Converted, 1770 InstTemplateArgs, 1771 CanonType, 1772 0); 1773 // Substitute the nested name specifier, if any. 1774 if (SubstQualifier(PartialSpec, InstPartialSpec)) 1775 return 0; 1776 1777 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 1778 InstPartialSpec->setTypeAsWritten(WrittenTy); 1779 1780 // Add this partial specialization to the set of class template partial 1781 // specializations. 1782 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec, 1783 InsertPos); 1784 return false; 1785} 1786 1787TypeSourceInfo* 1788TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 1789 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 1790 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 1791 assert(OldTInfo && "substituting function without type source info"); 1792 assert(Params.empty() && "parameter vector is non-empty at start"); 1793 TypeSourceInfo *NewTInfo 1794 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 1795 D->getTypeSpecStartLoc(), 1796 D->getDeclName()); 1797 if (!NewTInfo) 1798 return 0; 1799 1800 if (NewTInfo != OldTInfo) { 1801 // Get parameters from the new type info. 1802 TypeLoc NewTL = NewTInfo->getTypeLoc(); 1803 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL); 1804 assert(NewProtoLoc && "Missing prototype?"); 1805 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) 1806 Params.push_back(NewProtoLoc->getArg(i)); 1807 } else { 1808 // The function type itself was not dependent and therefore no 1809 // substitution occurred. However, we still need to instantiate 1810 // the function parameters themselves. 1811 TypeLoc OldTL = OldTInfo->getTypeLoc(); 1812 FunctionProtoTypeLoc *OldProtoLoc = cast<FunctionProtoTypeLoc>(&OldTL); 1813 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) { 1814 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i)); 1815 if (!Parm) 1816 return 0; 1817 Params.push_back(Parm); 1818 } 1819 } 1820 return NewTInfo; 1821} 1822 1823/// \brief Initializes the common fields of an instantiation function 1824/// declaration (New) from the corresponding fields of its template (Tmpl). 1825/// 1826/// \returns true if there was an error 1827bool 1828TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 1829 FunctionDecl *Tmpl) { 1830 if (Tmpl->isDeleted()) 1831 New->setDeleted(); 1832 1833 // If we are performing substituting explicitly-specified template arguments 1834 // or deduced template arguments into a function template and we reach this 1835 // point, we are now past the point where SFINAE applies and have committed 1836 // to keeping the new function template specialization. We therefore 1837 // convert the active template instantiation for the function template 1838 // into a template instantiation for this specific function template 1839 // specialization, which is not a SFINAE context, so that we diagnose any 1840 // further errors in the declaration itself. 1841 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 1842 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 1843 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 1844 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 1845 if (FunctionTemplateDecl *FunTmpl 1846 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 1847 assert(FunTmpl->getTemplatedDecl() == Tmpl && 1848 "Deduction from the wrong function template?"); 1849 (void) FunTmpl; 1850 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 1851 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 1852 --SemaRef.NonInstantiationEntries; 1853 } 1854 } 1855 1856 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 1857 assert(Proto && "Function template without prototype?"); 1858 1859 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() || 1860 Proto->getNoReturnAttr()) { 1861 // The function has an exception specification or a "noreturn" 1862 // attribute. Substitute into each of the exception types. 1863 llvm::SmallVector<QualType, 4> Exceptions; 1864 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 1865 // FIXME: Poor location information! 1866 QualType T 1867 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 1868 New->getLocation(), New->getDeclName()); 1869 if (T.isNull() || 1870 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 1871 continue; 1872 1873 Exceptions.push_back(T); 1874 } 1875 1876 // Rebuild the function type 1877 1878 const FunctionProtoType *NewProto 1879 = New->getType()->getAs<FunctionProtoType>(); 1880 assert(NewProto && "Template instantiation without function prototype?"); 1881 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 1882 NewProto->arg_type_begin(), 1883 NewProto->getNumArgs(), 1884 NewProto->isVariadic(), 1885 NewProto->getTypeQuals(), 1886 Proto->hasExceptionSpec(), 1887 Proto->hasAnyExceptionSpec(), 1888 Exceptions.size(), 1889 Exceptions.data(), 1890 Proto->getExtInfo())); 1891 } 1892 1893 return false; 1894} 1895 1896/// \brief Initializes common fields of an instantiated method 1897/// declaration (New) from the corresponding fields of its template 1898/// (Tmpl). 1899/// 1900/// \returns true if there was an error 1901bool 1902TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 1903 CXXMethodDecl *Tmpl) { 1904 if (InitFunctionInstantiation(New, Tmpl)) 1905 return true; 1906 1907 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 1908 New->setAccess(Tmpl->getAccess()); 1909 if (Tmpl->isVirtualAsWritten()) 1910 Record->setMethodAsVirtual(New); 1911 1912 // FIXME: attributes 1913 // FIXME: New needs a pointer to Tmpl 1914 return false; 1915} 1916 1917/// \brief Instantiate the definition of the given function from its 1918/// template. 1919/// 1920/// \param PointOfInstantiation the point at which the instantiation was 1921/// required. Note that this is not precisely a "point of instantiation" 1922/// for the function, but it's close. 1923/// 1924/// \param Function the already-instantiated declaration of a 1925/// function template specialization or member function of a class template 1926/// specialization. 1927/// 1928/// \param Recursive if true, recursively instantiates any functions that 1929/// are required by this instantiation. 1930/// 1931/// \param DefinitionRequired if true, then we are performing an explicit 1932/// instantiation where the body of the function is required. Complain if 1933/// there is no such body. 1934void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 1935 FunctionDecl *Function, 1936 bool Recursive, 1937 bool DefinitionRequired) { 1938 if (Function->isInvalidDecl()) 1939 return; 1940 1941 assert(!Function->getBody() && "Already instantiated!"); 1942 1943 // Never instantiate an explicit specialization. 1944 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1945 return; 1946 1947 // Find the function body that we'll be substituting. 1948 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 1949 Stmt *Pattern = 0; 1950 if (PatternDecl) 1951 Pattern = PatternDecl->getBody(PatternDecl); 1952 1953 if (!Pattern) { 1954 if (DefinitionRequired) { 1955 if (Function->getPrimaryTemplate()) 1956 Diag(PointOfInstantiation, 1957 diag::err_explicit_instantiation_undefined_func_template) 1958 << Function->getPrimaryTemplate(); 1959 else 1960 Diag(PointOfInstantiation, 1961 diag::err_explicit_instantiation_undefined_member) 1962 << 1 << Function->getDeclName() << Function->getDeclContext(); 1963 1964 if (PatternDecl) 1965 Diag(PatternDecl->getLocation(), 1966 diag::note_explicit_instantiation_here); 1967 } 1968 1969 return; 1970 } 1971 1972 // C++0x [temp.explicit]p9: 1973 // Except for inline functions, other explicit instantiation declarations 1974 // have the effect of suppressing the implicit instantiation of the entity 1975 // to which they refer. 1976 if (Function->getTemplateSpecializationKind() 1977 == TSK_ExplicitInstantiationDeclaration && 1978 !PatternDecl->isInlined()) 1979 return; 1980 1981 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 1982 if (Inst) 1983 return; 1984 1985 // If we're performing recursive template instantiation, create our own 1986 // queue of pending implicit instantiations that we will instantiate later, 1987 // while we're still within our own instantiation context. 1988 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1989 if (Recursive) 1990 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1991 1992 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 1993 1994 // Introduce a new scope where local variable instantiations will be 1995 // recorded, unless we're actually a member function within a local 1996 // class, in which case we need to merge our results with the parent 1997 // scope (of the enclosing function). 1998 bool MergeWithParentScope = false; 1999 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 2000 MergeWithParentScope = Rec->isLocalClass(); 2001 2002 LocalInstantiationScope Scope(*this, MergeWithParentScope); 2003 2004 // Introduce the instantiated function parameters into the local 2005 // instantiation scope. 2006 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 2007 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 2008 Function->getParamDecl(I)); 2009 2010 // Enter the scope of this instantiation. We don't use 2011 // PushDeclContext because we don't have a scope. 2012 DeclContext *PreviousContext = CurContext; 2013 CurContext = Function; 2014 2015 MultiLevelTemplateArgumentList TemplateArgs = 2016 getTemplateInstantiationArgs(Function); 2017 2018 // If this is a constructor, instantiate the member initializers. 2019 if (const CXXConstructorDecl *Ctor = 2020 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 2021 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 2022 TemplateArgs); 2023 } 2024 2025 // Instantiate the function body. 2026 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs); 2027 2028 if (Body.isInvalid()) 2029 Function->setInvalidDecl(); 2030 2031 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 2032 /*IsInstantiation=*/true); 2033 2034 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 2035 2036 CurContext = PreviousContext; 2037 2038 DeclGroupRef DG(Function); 2039 Consumer.HandleTopLevelDecl(DG); 2040 2041 // This class may have local implicit instantiations that need to be 2042 // instantiation within this scope. 2043 PerformPendingImplicitInstantiations(/*LocalOnly=*/true); 2044 Scope.Exit(); 2045 2046 if (Recursive) { 2047 // Instantiate any pending implicit instantiations found during the 2048 // instantiation of this template. 2049 PerformPendingImplicitInstantiations(); 2050 2051 // Restore the set of pending implicit instantiations. 2052 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2053 } 2054} 2055 2056/// \brief Instantiate the definition of the given variable from its 2057/// template. 2058/// 2059/// \param PointOfInstantiation the point at which the instantiation was 2060/// required. Note that this is not precisely a "point of instantiation" 2061/// for the function, but it's close. 2062/// 2063/// \param Var the already-instantiated declaration of a static member 2064/// variable of a class template specialization. 2065/// 2066/// \param Recursive if true, recursively instantiates any functions that 2067/// are required by this instantiation. 2068/// 2069/// \param DefinitionRequired if true, then we are performing an explicit 2070/// instantiation where an out-of-line definition of the member variable 2071/// is required. Complain if there is no such definition. 2072void Sema::InstantiateStaticDataMemberDefinition( 2073 SourceLocation PointOfInstantiation, 2074 VarDecl *Var, 2075 bool Recursive, 2076 bool DefinitionRequired) { 2077 if (Var->isInvalidDecl()) 2078 return; 2079 2080 // Find the out-of-line definition of this static data member. 2081 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 2082 assert(Def && "This data member was not instantiated from a template?"); 2083 assert(Def->isStaticDataMember() && "Not a static data member?"); 2084 Def = Def->getOutOfLineDefinition(); 2085 2086 if (!Def) { 2087 // We did not find an out-of-line definition of this static data member, 2088 // so we won't perform any instantiation. Rather, we rely on the user to 2089 // instantiate this definition (or provide a specialization for it) in 2090 // another translation unit. 2091 if (DefinitionRequired) { 2092 Def = Var->getInstantiatedFromStaticDataMember(); 2093 Diag(PointOfInstantiation, 2094 diag::err_explicit_instantiation_undefined_member) 2095 << 2 << Var->getDeclName() << Var->getDeclContext(); 2096 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 2097 } 2098 2099 return; 2100 } 2101 2102 // Never instantiate an explicit specialization. 2103 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 2104 return; 2105 2106 // C++0x [temp.explicit]p9: 2107 // Except for inline functions, other explicit instantiation declarations 2108 // have the effect of suppressing the implicit instantiation of the entity 2109 // to which they refer. 2110 if (Var->getTemplateSpecializationKind() 2111 == TSK_ExplicitInstantiationDeclaration) 2112 return; 2113 2114 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 2115 if (Inst) 2116 return; 2117 2118 // If we're performing recursive template instantiation, create our own 2119 // queue of pending implicit instantiations that we will instantiate later, 2120 // while we're still within our own instantiation context. 2121 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 2122 if (Recursive) 2123 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2124 2125 // Enter the scope of this instantiation. We don't use 2126 // PushDeclContext because we don't have a scope. 2127 DeclContext *PreviousContext = CurContext; 2128 CurContext = Var->getDeclContext(); 2129 2130 VarDecl *OldVar = Var; 2131 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 2132 getTemplateInstantiationArgs(Var))); 2133 CurContext = PreviousContext; 2134 2135 if (Var) { 2136 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 2137 assert(MSInfo && "Missing member specialization information?"); 2138 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 2139 MSInfo->getPointOfInstantiation()); 2140 DeclGroupRef DG(Var); 2141 Consumer.HandleTopLevelDecl(DG); 2142 } 2143 2144 if (Recursive) { 2145 // Instantiate any pending implicit instantiations found during the 2146 // instantiation of this template. 2147 PerformPendingImplicitInstantiations(); 2148 2149 // Restore the set of pending implicit instantiations. 2150 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2151 } 2152} 2153 2154void 2155Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 2156 const CXXConstructorDecl *Tmpl, 2157 const MultiLevelTemplateArgumentList &TemplateArgs) { 2158 2159 llvm::SmallVector<MemInitTy*, 4> NewInits; 2160 bool AnyErrors = false; 2161 2162 // Instantiate all the initializers. 2163 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 2164 InitsEnd = Tmpl->init_end(); 2165 Inits != InitsEnd; ++Inits) { 2166 CXXBaseOrMemberInitializer *Init = *Inits; 2167 2168 SourceLocation LParenLoc, RParenLoc; 2169 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this); 2170 llvm::SmallVector<SourceLocation, 4> CommaLocs; 2171 2172 // Instantiate the initializer. 2173 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs, 2174 LParenLoc, CommaLocs, NewArgs, RParenLoc)) { 2175 AnyErrors = true; 2176 continue; 2177 } 2178 2179 MemInitResult NewInit; 2180 if (Init->isBaseInitializer()) { 2181 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(), 2182 TemplateArgs, 2183 Init->getSourceLocation(), 2184 New->getDeclName()); 2185 if (!BaseTInfo) { 2186 AnyErrors = true; 2187 New->setInvalidDecl(); 2188 continue; 2189 } 2190 2191 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo, 2192 (Expr **)NewArgs.data(), 2193 NewArgs.size(), 2194 Init->getLParenLoc(), 2195 Init->getRParenLoc(), 2196 New->getParent()); 2197 } else if (Init->isMemberInitializer()) { 2198 FieldDecl *Member; 2199 2200 // Is this an anonymous union? 2201 if (FieldDecl *UnionInit = Init->getAnonUnionMember()) 2202 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(), 2203 UnionInit, TemplateArgs)); 2204 else 2205 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(), 2206 Init->getMember(), 2207 TemplateArgs)); 2208 2209 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 2210 NewArgs.size(), 2211 Init->getSourceLocation(), 2212 Init->getLParenLoc(), 2213 Init->getRParenLoc()); 2214 } 2215 2216 if (NewInit.isInvalid()) { 2217 AnyErrors = true; 2218 New->setInvalidDecl(); 2219 } else { 2220 // FIXME: It would be nice if ASTOwningVector had a release function. 2221 NewArgs.take(); 2222 2223 NewInits.push_back((MemInitTy *)NewInit.get()); 2224 } 2225 } 2226 2227 // Assign all the initializers to the new constructor. 2228 ActOnMemInitializers(DeclPtrTy::make(New), 2229 /*FIXME: ColonLoc */ 2230 SourceLocation(), 2231 NewInits.data(), NewInits.size(), 2232 AnyErrors); 2233} 2234 2235// TODO: this could be templated if the various decl types used the 2236// same method name. 2237static bool isInstantiationOf(ClassTemplateDecl *Pattern, 2238 ClassTemplateDecl *Instance) { 2239 Pattern = Pattern->getCanonicalDecl(); 2240 2241 do { 2242 Instance = Instance->getCanonicalDecl(); 2243 if (Pattern == Instance) return true; 2244 Instance = Instance->getInstantiatedFromMemberTemplate(); 2245 } while (Instance); 2246 2247 return false; 2248} 2249 2250static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 2251 FunctionTemplateDecl *Instance) { 2252 Pattern = Pattern->getCanonicalDecl(); 2253 2254 do { 2255 Instance = Instance->getCanonicalDecl(); 2256 if (Pattern == Instance) return true; 2257 Instance = Instance->getInstantiatedFromMemberTemplate(); 2258 } while (Instance); 2259 2260 return false; 2261} 2262 2263static bool 2264isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 2265 ClassTemplatePartialSpecializationDecl *Instance) { 2266 Pattern 2267 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 2268 do { 2269 Instance = cast<ClassTemplatePartialSpecializationDecl>( 2270 Instance->getCanonicalDecl()); 2271 if (Pattern == Instance) 2272 return true; 2273 Instance = Instance->getInstantiatedFromMember(); 2274 } while (Instance); 2275 2276 return false; 2277} 2278 2279static bool isInstantiationOf(CXXRecordDecl *Pattern, 2280 CXXRecordDecl *Instance) { 2281 Pattern = Pattern->getCanonicalDecl(); 2282 2283 do { 2284 Instance = Instance->getCanonicalDecl(); 2285 if (Pattern == Instance) return true; 2286 Instance = Instance->getInstantiatedFromMemberClass(); 2287 } while (Instance); 2288 2289 return false; 2290} 2291 2292static bool isInstantiationOf(FunctionDecl *Pattern, 2293 FunctionDecl *Instance) { 2294 Pattern = Pattern->getCanonicalDecl(); 2295 2296 do { 2297 Instance = Instance->getCanonicalDecl(); 2298 if (Pattern == Instance) return true; 2299 Instance = Instance->getInstantiatedFromMemberFunction(); 2300 } while (Instance); 2301 2302 return false; 2303} 2304 2305static bool isInstantiationOf(EnumDecl *Pattern, 2306 EnumDecl *Instance) { 2307 Pattern = Pattern->getCanonicalDecl(); 2308 2309 do { 2310 Instance = Instance->getCanonicalDecl(); 2311 if (Pattern == Instance) return true; 2312 Instance = Instance->getInstantiatedFromMemberEnum(); 2313 } while (Instance); 2314 2315 return false; 2316} 2317 2318static bool isInstantiationOf(UsingShadowDecl *Pattern, 2319 UsingShadowDecl *Instance, 2320 ASTContext &C) { 2321 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 2322} 2323 2324static bool isInstantiationOf(UsingDecl *Pattern, 2325 UsingDecl *Instance, 2326 ASTContext &C) { 2327 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2328} 2329 2330static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 2331 UsingDecl *Instance, 2332 ASTContext &C) { 2333 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2334} 2335 2336static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 2337 UsingDecl *Instance, 2338 ASTContext &C) { 2339 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2340} 2341 2342static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 2343 VarDecl *Instance) { 2344 assert(Instance->isStaticDataMember()); 2345 2346 Pattern = Pattern->getCanonicalDecl(); 2347 2348 do { 2349 Instance = Instance->getCanonicalDecl(); 2350 if (Pattern == Instance) return true; 2351 Instance = Instance->getInstantiatedFromStaticDataMember(); 2352 } while (Instance); 2353 2354 return false; 2355} 2356 2357// Other is the prospective instantiation 2358// D is the prospective pattern 2359static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 2360 if (D->getKind() != Other->getKind()) { 2361 if (UnresolvedUsingTypenameDecl *UUD 2362 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 2363 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2364 return isInstantiationOf(UUD, UD, Ctx); 2365 } 2366 } 2367 2368 if (UnresolvedUsingValueDecl *UUD 2369 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 2370 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2371 return isInstantiationOf(UUD, UD, Ctx); 2372 } 2373 } 2374 2375 return false; 2376 } 2377 2378 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 2379 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 2380 2381 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 2382 return isInstantiationOf(cast<FunctionDecl>(D), Function); 2383 2384 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 2385 return isInstantiationOf(cast<EnumDecl>(D), Enum); 2386 2387 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 2388 if (Var->isStaticDataMember()) 2389 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 2390 2391 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 2392 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 2393 2394 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 2395 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 2396 2397 if (ClassTemplatePartialSpecializationDecl *PartialSpec 2398 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 2399 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 2400 PartialSpec); 2401 2402 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 2403 if (!Field->getDeclName()) { 2404 // This is an unnamed field. 2405 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 2406 cast<FieldDecl>(D); 2407 } 2408 } 2409 2410 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 2411 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 2412 2413 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 2414 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 2415 2416 return D->getDeclName() && isa<NamedDecl>(Other) && 2417 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 2418} 2419 2420template<typename ForwardIterator> 2421static NamedDecl *findInstantiationOf(ASTContext &Ctx, 2422 NamedDecl *D, 2423 ForwardIterator first, 2424 ForwardIterator last) { 2425 for (; first != last; ++first) 2426 if (isInstantiationOf(Ctx, D, *first)) 2427 return cast<NamedDecl>(*first); 2428 2429 return 0; 2430} 2431 2432/// \brief Finds the instantiation of the given declaration context 2433/// within the current instantiation. 2434/// 2435/// \returns NULL if there was an error 2436DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 2437 const MultiLevelTemplateArgumentList &TemplateArgs) { 2438 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 2439 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 2440 return cast_or_null<DeclContext>(ID); 2441 } else return DC; 2442} 2443 2444/// \brief Find the instantiation of the given declaration within the 2445/// current instantiation. 2446/// 2447/// This routine is intended to be used when \p D is a declaration 2448/// referenced from within a template, that needs to mapped into the 2449/// corresponding declaration within an instantiation. For example, 2450/// given: 2451/// 2452/// \code 2453/// template<typename T> 2454/// struct X { 2455/// enum Kind { 2456/// KnownValue = sizeof(T) 2457/// }; 2458/// 2459/// bool getKind() const { return KnownValue; } 2460/// }; 2461/// 2462/// template struct X<int>; 2463/// \endcode 2464/// 2465/// In the instantiation of X<int>::getKind(), we need to map the 2466/// EnumConstantDecl for KnownValue (which refers to 2467/// X<T>::<Kind>::KnownValue) to its instantiation 2468/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 2469/// this mapping from within the instantiation of X<int>. 2470NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 2471 const MultiLevelTemplateArgumentList &TemplateArgs) { 2472 DeclContext *ParentDC = D->getDeclContext(); 2473 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 2474 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 2475 ParentDC->isFunctionOrMethod()) { 2476 // D is a local of some kind. Look into the map of local 2477 // declarations to their instantiations. 2478 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 2479 } 2480 2481 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 2482 if (!Record->isDependentContext()) 2483 return D; 2484 2485 // If the RecordDecl is actually the injected-class-name or a 2486 // "templated" declaration for a class template, class template 2487 // partial specialization, or a member class of a class template, 2488 // substitute into the injected-class-name of the class template 2489 // or partial specialization to find the new DeclContext. 2490 QualType T; 2491 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 2492 2493 if (ClassTemplate) { 2494 T = ClassTemplate->getInjectedClassNameSpecialization(Context); 2495 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2496 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 2497 ClassTemplate = PartialSpec->getSpecializedTemplate(); 2498 2499 // If we call SubstType with an InjectedClassNameType here we 2500 // can end up in an infinite loop. 2501 T = Context.getTypeDeclType(Record); 2502 assert(isa<InjectedClassNameType>(T) && 2503 "type of partial specialization is not an InjectedClassNameType"); 2504 T = cast<InjectedClassNameType>(T)->getUnderlyingType(); 2505 } 2506 2507 if (!T.isNull()) { 2508 // Substitute into the injected-class-name to get the type 2509 // corresponding to the instantiation we want, which may also be 2510 // the current instantiation (if we're in a template 2511 // definition). This substitution should never fail, since we 2512 // know we can instantiate the injected-class-name or we 2513 // wouldn't have gotten to the injected-class-name! 2514 2515 // FIXME: Can we use the CurrentInstantiationScope to avoid this 2516 // extra instantiation in the common case? 2517 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName()); 2518 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail."); 2519 2520 if (!T->isDependentType()) { 2521 assert(T->isRecordType() && "Instantiation must produce a record type"); 2522 return T->getAs<RecordType>()->getDecl(); 2523 } 2524 2525 // We are performing "partial" template instantiation to create 2526 // the member declarations for the members of a class template 2527 // specialization. Therefore, D is actually referring to something 2528 // in the current instantiation. Look through the current 2529 // context, which contains actual instantiations, to find the 2530 // instantiation of the "current instantiation" that D refers 2531 // to. 2532 bool SawNonDependentContext = false; 2533 for (DeclContext *DC = CurContext; !DC->isFileContext(); 2534 DC = DC->getParent()) { 2535 if (ClassTemplateSpecializationDecl *Spec 2536 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 2537 if (isInstantiationOf(ClassTemplate, 2538 Spec->getSpecializedTemplate())) 2539 return Spec; 2540 2541 if (!DC->isDependentContext()) 2542 SawNonDependentContext = true; 2543 } 2544 2545 // We're performing "instantiation" of a member of the current 2546 // instantiation while we are type-checking the 2547 // definition. Compute the declaration context and return that. 2548 assert(!SawNonDependentContext && 2549 "No dependent context while instantiating record"); 2550 DeclContext *DC = computeDeclContext(T); 2551 assert(DC && 2552 "Unable to find declaration for the current instantiation"); 2553 return cast<CXXRecordDecl>(DC); 2554 } 2555 2556 // Fall through to deal with other dependent record types (e.g., 2557 // anonymous unions in class templates). 2558 } 2559 2560 if (!ParentDC->isDependentContext()) 2561 return D; 2562 2563 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 2564 if (!ParentDC) 2565 return 0; 2566 2567 if (ParentDC != D->getDeclContext()) { 2568 // We performed some kind of instantiation in the parent context, 2569 // so now we need to look into the instantiated parent context to 2570 // find the instantiation of the declaration D. 2571 2572 // If our context used to be dependent, we may need to instantiate 2573 // it before performing lookup into that context. 2574 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 2575 if (!Spec->isDependentContext()) { 2576 QualType T = Context.getTypeDeclType(Spec); 2577 const RecordType *Tag = T->getAs<RecordType>(); 2578 assert(Tag && "type of non-dependent record is not a RecordType"); 2579 if (!Tag->isBeingDefined() && 2580 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 2581 return 0; 2582 } 2583 } 2584 2585 NamedDecl *Result = 0; 2586 if (D->getDeclName()) { 2587 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 2588 Result = findInstantiationOf(Context, D, Found.first, Found.second); 2589 } else { 2590 // Since we don't have a name for the entity we're looking for, 2591 // our only option is to walk through all of the declarations to 2592 // find that name. This will occur in a few cases: 2593 // 2594 // - anonymous struct/union within a template 2595 // - unnamed class/struct/union/enum within a template 2596 // 2597 // FIXME: Find a better way to find these instantiations! 2598 Result = findInstantiationOf(Context, D, 2599 ParentDC->decls_begin(), 2600 ParentDC->decls_end()); 2601 } 2602 2603 // UsingShadowDecls can instantiate to nothing because of using hiding. 2604 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() || 2605 cast<Decl>(ParentDC)->isInvalidDecl()) 2606 && "Unable to find instantiation of declaration!"); 2607 2608 D = Result; 2609 } 2610 2611 return D; 2612} 2613 2614/// \brief Performs template instantiation for all implicit template 2615/// instantiations we have seen until this point. 2616void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) { 2617 while (!PendingLocalImplicitInstantiations.empty() || 2618 (!LocalOnly && !PendingImplicitInstantiations.empty())) { 2619 PendingImplicitInstantiation Inst; 2620 2621 if (PendingLocalImplicitInstantiations.empty()) { 2622 Inst = PendingImplicitInstantiations.front(); 2623 PendingImplicitInstantiations.pop_front(); 2624 } else { 2625 Inst = PendingLocalImplicitInstantiations.front(); 2626 PendingLocalImplicitInstantiations.pop_front(); 2627 } 2628 2629 // Instantiate function definitions 2630 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 2631 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function), 2632 Function->getLocation(), *this, 2633 Context.getSourceManager(), 2634 "instantiating function definition"); 2635 2636 if (!Function->getBody()) 2637 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 2638 continue; 2639 } 2640 2641 // Instantiate static data member definitions. 2642 VarDecl *Var = cast<VarDecl>(Inst.first); 2643 assert(Var->isStaticDataMember() && "Not a static data member?"); 2644 2645 // Don't try to instantiate declarations if the most recent redeclaration 2646 // is invalid. 2647 if (Var->getMostRecentDeclaration()->isInvalidDecl()) 2648 continue; 2649 2650 // Check if the most recent declaration has changed the specialization kind 2651 // and removed the need for implicit instantiation. 2652 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) { 2653 case TSK_Undeclared: 2654 assert(false && "Cannot instantitiate an undeclared specialization."); 2655 case TSK_ExplicitInstantiationDeclaration: 2656 case TSK_ExplicitInstantiationDefinition: 2657 case TSK_ExplicitSpecialization: 2658 continue; // No longer need implicit instantiation. 2659 case TSK_ImplicitInstantiation: 2660 break; 2661 } 2662 2663 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var), 2664 Var->getLocation(), *this, 2665 Context.getSourceManager(), 2666 "instantiating static data member " 2667 "definition"); 2668 2669 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 2670 } 2671} 2672 2673void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 2674 const MultiLevelTemplateArgumentList &TemplateArgs) { 2675 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(), 2676 E = Pattern->ddiag_end(); I != E; ++I) { 2677 DependentDiagnostic *DD = *I; 2678 2679 switch (DD->getKind()) { 2680 case DependentDiagnostic::Access: 2681 HandleDependentAccessCheck(*DD, TemplateArgs); 2682 break; 2683 } 2684 } 2685} 2686