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