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