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