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