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