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