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