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