SemaTemplateInstantiateDecl.cpp revision 6826314938f8510cd1a6b03b5d032592456ae27b
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 "Sema.h" 13#include "Lookup.h" 14#include "clang/AST/ASTConsumer.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/DeclTemplate.h" 17#include "clang/AST/DeclVisitor.h" 18#include "clang/AST/Expr.h" 19#include "clang/Basic/PrettyStackTrace.h" 20#include "clang/Lex/Preprocessor.h" 21#include "llvm/Support/Compiler.h" 22 23using namespace clang; 24 25namespace { 26 class VISIBILITY_HIDDEN TemplateDeclInstantiator 27 : public DeclVisitor<TemplateDeclInstantiator, Decl *> { 28 Sema &SemaRef; 29 DeclContext *Owner; 30 const MultiLevelTemplateArgumentList &TemplateArgs; 31 32 void InstantiateAttrs(Decl *Tmpl, Decl *New); 33 34 public: 35 typedef Sema::OwningExprResult OwningExprResult; 36 37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, 38 const MultiLevelTemplateArgumentList &TemplateArgs) 39 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { } 40 41 // FIXME: Once we get closer to completion, replace these manually-written 42 // declarations with automatically-generated ones from 43 // clang/AST/DeclNodes.def. 44 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); 45 Decl *VisitNamespaceDecl(NamespaceDecl *D); 46 Decl *VisitTypedefDecl(TypedefDecl *D); 47 Decl *VisitVarDecl(VarDecl *D); 48 Decl *VisitFieldDecl(FieldDecl *D); 49 Decl *VisitStaticAssertDecl(StaticAssertDecl *D); 50 Decl *VisitEnumDecl(EnumDecl *D); 51 Decl *VisitEnumConstantDecl(EnumConstantDecl *D); 52 Decl *VisitFriendDecl(FriendDecl *D); 53 Decl *VisitFunctionDecl(FunctionDecl *D, 54 TemplateParameterList *TemplateParams = 0); 55 Decl *VisitCXXRecordDecl(CXXRecordDecl *D); 56 Decl *VisitCXXMethodDecl(CXXMethodDecl *D, 57 TemplateParameterList *TemplateParams = 0); 58 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 59 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 60 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 61 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 62 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D); 63 Decl *VisitClassTemplatePartialSpecializationDecl( 64 ClassTemplatePartialSpecializationDecl *D); 65 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 66 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 67 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 68 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 69 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 70 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 71 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 72 73 // Base case. FIXME: Remove once we can instantiate everything. 74 Decl *VisitDecl(Decl *D) { 75 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 76 Diagnostic::Error, 77 "cannot instantiate %0 yet"); 78 SemaRef.Diag(D->getLocation(), DiagID) 79 << D->getDeclKindName(); 80 81 return 0; 82 } 83 84 const LangOptions &getLangOptions() { 85 return SemaRef.getLangOptions(); 86 } 87 88 // Helper functions for instantiating methods. 89 QualType SubstFunctionType(FunctionDecl *D, 90 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 91 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl); 92 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 93 94 TemplateParameterList * 95 SubstTemplateParams(TemplateParameterList *List); 96 97 bool InstantiateClassTemplatePartialSpecialization( 98 ClassTemplateDecl *ClassTemplate, 99 ClassTemplatePartialSpecializationDecl *PartialSpec); 100 }; 101} 102 103// FIXME: Is this too simple? 104void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) { 105 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr; 106 TmplAttr = TmplAttr->getNext()) { 107 108 // FIXME: Is cloning correct for all attributes? 109 Attr *NewAttr = TmplAttr->clone(SemaRef.Context); 110 111 New->addAttr(NewAttr); 112 } 113} 114 115Decl * 116TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 117 assert(false && "Translation units cannot be instantiated"); 118 return D; 119} 120 121Decl * 122TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 123 assert(false && "Namespaces cannot be instantiated"); 124 return D; 125} 126 127Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 128 bool Invalid = false; 129 DeclaratorInfo *DI = D->getTypeDeclaratorInfo(); 130 if (DI->getType()->isDependentType()) { 131 DI = SemaRef.SubstType(DI, TemplateArgs, 132 D->getLocation(), D->getDeclName()); 133 if (!DI) { 134 Invalid = true; 135 DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy); 136 } 137 } 138 139 // Create the new typedef 140 TypedefDecl *Typedef 141 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 142 D->getIdentifier(), DI); 143 if (Invalid) 144 Typedef->setInvalidDecl(); 145 146 Owner->addDecl(Typedef); 147 148 return Typedef; 149} 150 151Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 152 // Do substitution on the type of the declaration 153 DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(), 154 TemplateArgs, 155 D->getTypeSpecStartLoc(), 156 D->getDeclName()); 157 if (!DI) 158 return 0; 159 160 // Build the instantiated declaration 161 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 162 D->getLocation(), D->getIdentifier(), 163 DI->getType(), DI, 164 D->getStorageClass()); 165 Var->setThreadSpecified(D->isThreadSpecified()); 166 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 167 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 168 169 // If we are instantiating a static data member defined 170 // out-of-line, the instantiation will have the same lexical 171 // context (which will be a namespace scope) as the template. 172 if (D->isOutOfLine()) 173 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 174 175 // FIXME: In theory, we could have a previous declaration for variables that 176 // are not static data members. 177 bool Redeclaration = false; 178 // FIXME: having to fake up a LookupResult is dumb. 179 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(), 180 Sema::LookupOrdinaryName); 181 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration); 182 183 if (D->isOutOfLine()) { 184 D->getLexicalDeclContext()->addDecl(Var); 185 Owner->makeDeclVisibleInContext(Var); 186 } else { 187 Owner->addDecl(Var); 188 } 189 190 // Link instantiations of static data members back to the template from 191 // which they were instantiated. 192 if (Var->isStaticDataMember()) 193 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 194 TSK_ImplicitInstantiation); 195 196 if (D->getInit()) { 197 OwningExprResult Init 198 = SemaRef.SubstExpr(D->getInit(), TemplateArgs); 199 if (Init.isInvalid()) 200 Var->setInvalidDecl(); 201 else if (!D->getType()->isDependentType() && 202 !D->getInit()->isTypeDependent() && 203 !D->getInit()->isValueDependent()) { 204 // If neither the declaration's type nor its initializer are dependent, 205 // we don't want to redo all the checking, especially since the 206 // initializer might have been wrapped by a CXXConstructExpr since we did 207 // it the first time. 208 Var->setInit(SemaRef.Context, Init.takeAs<Expr>()); 209 } 210 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) { 211 // FIXME: We're faking all of the comma locations, which is suboptimal. 212 // Do we even need these comma locations? 213 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs; 214 if (PLE->getNumExprs() > 0) { 215 FakeCommaLocs.reserve(PLE->getNumExprs() - 1); 216 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) { 217 Expr *E = PLE->getExpr(I)->Retain(); 218 FakeCommaLocs.push_back( 219 SemaRef.PP.getLocForEndOfToken(E->getLocEnd())); 220 } 221 PLE->getExpr(PLE->getNumExprs() - 1)->Retain(); 222 } 223 224 // Add the direct initializer to the declaration. 225 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var), 226 PLE->getLParenLoc(), 227 Sema::MultiExprArg(SemaRef, 228 (void**)PLE->getExprs(), 229 PLE->getNumExprs()), 230 FakeCommaLocs.data(), 231 PLE->getRParenLoc()); 232 233 // When Init is destroyed, it will destroy the instantiated ParenListExpr; 234 // we've explicitly retained all of its subexpressions already. 235 } else 236 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init), 237 D->hasCXXDirectInitializer()); 238 } else if (!Var->isStaticDataMember() || Var->isOutOfLine()) 239 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 240 241 return Var; 242} 243 244Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 245 bool Invalid = false; 246 DeclaratorInfo *DI = D->getDeclaratorInfo(); 247 if (DI->getType()->isDependentType()) { 248 DI = SemaRef.SubstType(DI, TemplateArgs, 249 D->getLocation(), D->getDeclName()); 250 if (!DI) { 251 DI = D->getDeclaratorInfo(); 252 Invalid = true; 253 } else if (DI->getType()->isFunctionType()) { 254 // C++ [temp.arg.type]p3: 255 // If a declaration acquires a function type through a type 256 // dependent on a template-parameter and this causes a 257 // declaration that does not use the syntactic form of a 258 // function declarator to have function type, the program is 259 // ill-formed. 260 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 261 << DI->getType(); 262 Invalid = true; 263 } 264 } 265 266 Expr *BitWidth = D->getBitWidth(); 267 if (Invalid) 268 BitWidth = 0; 269 else if (BitWidth) { 270 // The bit-width expression is not potentially evaluated. 271 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 272 273 OwningExprResult InstantiatedBitWidth 274 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 275 if (InstantiatedBitWidth.isInvalid()) { 276 Invalid = true; 277 BitWidth = 0; 278 } else 279 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 280 } 281 282 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 283 DI->getType(), DI, 284 cast<RecordDecl>(Owner), 285 D->getLocation(), 286 D->isMutable(), 287 BitWidth, 288 D->getTypeSpecStartLoc(), 289 D->getAccess(), 290 0); 291 if (!Field) { 292 cast<Decl>(Owner)->setInvalidDecl(); 293 return 0; 294 } 295 296 InstantiateAttrs(D, Field); 297 298 if (Invalid) 299 Field->setInvalidDecl(); 300 301 if (!Field->getDeclName()) { 302 // Keep track of where this decl came from. 303 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 304 } 305 306 Field->setImplicit(D->isImplicit()); 307 Owner->addDecl(Field); 308 309 return Field; 310} 311 312Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 313 FriendDecl::FriendUnion FU; 314 315 // Handle friend type expressions by simply substituting template 316 // parameters into the pattern type. 317 if (Type *Ty = D->getFriendType()) { 318 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs, 319 D->getLocation(), DeclarationName()); 320 if (T.isNull()) return 0; 321 322 assert(getLangOptions().CPlusPlus0x || T->isRecordType()); 323 FU = T.getTypePtr(); 324 325 // Handle everything else by appropriate substitution. 326 } else { 327 NamedDecl *ND = D->getFriendDecl(); 328 assert(ND && "friend decl must be a decl or a type!"); 329 330 // FIXME: We have a problem here, because the nested call to Visit(ND) 331 // will inject the thing that the friend references into the current 332 // owner, which is wrong. 333 Decl *NewND = Visit(ND); 334 if (!NewND) return 0; 335 336 FU = cast<NamedDecl>(NewND); 337 } 338 339 FriendDecl *FD = 340 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU, 341 D->getFriendLoc()); 342 FD->setAccess(AS_public); 343 Owner->addDecl(FD); 344 return FD; 345} 346 347Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 348 Expr *AssertExpr = D->getAssertExpr(); 349 350 // The expression in a static assertion is not potentially evaluated. 351 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 352 353 OwningExprResult InstantiatedAssertExpr 354 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 355 if (InstantiatedAssertExpr.isInvalid()) 356 return 0; 357 358 OwningExprResult Message(SemaRef, D->getMessage()); 359 D->getMessage()->Retain(); 360 Decl *StaticAssert 361 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 362 move(InstantiatedAssertExpr), 363 move(Message)).getAs<Decl>(); 364 return StaticAssert; 365} 366 367Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 368 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 369 D->getLocation(), D->getIdentifier(), 370 D->getTagKeywordLoc(), 371 /*PrevDecl=*/0); 372 Enum->setInstantiationOfMemberEnum(D); 373 Enum->setAccess(D->getAccess()); 374 Owner->addDecl(Enum); 375 Enum->startDefinition(); 376 377 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators; 378 379 EnumConstantDecl *LastEnumConst = 0; 380 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 381 ECEnd = D->enumerator_end(); 382 EC != ECEnd; ++EC) { 383 // The specified value for the enumerator. 384 OwningExprResult Value = SemaRef.Owned((Expr *)0); 385 if (Expr *UninstValue = EC->getInitExpr()) { 386 // The enumerator's value expression is not potentially evaluated. 387 EnterExpressionEvaluationContext Unevaluated(SemaRef, 388 Action::Unevaluated); 389 390 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 391 } 392 393 // Drop the initial value and continue. 394 bool isInvalid = false; 395 if (Value.isInvalid()) { 396 Value = SemaRef.Owned((Expr *)0); 397 isInvalid = true; 398 } 399 400 EnumConstantDecl *EnumConst 401 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 402 EC->getLocation(), EC->getIdentifier(), 403 move(Value)); 404 405 if (isInvalid) { 406 if (EnumConst) 407 EnumConst->setInvalidDecl(); 408 Enum->setInvalidDecl(); 409 } 410 411 if (EnumConst) { 412 Enum->addDecl(EnumConst); 413 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 414 LastEnumConst = EnumConst; 415 } 416 } 417 418 // FIXME: Fixup LBraceLoc and RBraceLoc 419 // FIXME: Empty Scope and AttributeList (required to handle attribute packed). 420 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 421 Sema::DeclPtrTy::make(Enum), 422 &Enumerators[0], Enumerators.size(), 423 0, 0); 424 425 return Enum; 426} 427 428Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 429 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 430 return 0; 431} 432 433namespace { 434 class SortDeclByLocation { 435 SourceManager &SourceMgr; 436 437 public: 438 explicit SortDeclByLocation(SourceManager &SourceMgr) 439 : SourceMgr(SourceMgr) { } 440 441 bool operator()(const Decl *X, const Decl *Y) const { 442 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(), 443 Y->getLocation()); 444 } 445 }; 446} 447 448Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 449 // Create a local instantiation scope for this class template, which 450 // will contain the instantiations of the template parameters. 451 Sema::LocalInstantiationScope Scope(SemaRef); 452 TemplateParameterList *TempParams = D->getTemplateParameters(); 453 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 454 if (!InstParams) 455 return NULL; 456 457 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 458 CXXRecordDecl *RecordInst 459 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner, 460 Pattern->getLocation(), Pattern->getIdentifier(), 461 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL, 462 /*DelayTypeCreation=*/true); 463 464 ClassTemplateDecl *Inst 465 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 466 D->getIdentifier(), InstParams, RecordInst, 0); 467 RecordInst->setDescribedClassTemplate(Inst); 468 if (D->getFriendObjectKind()) 469 Inst->setObjectOfFriendDecl(true); 470 else 471 Inst->setAccess(D->getAccess()); 472 Inst->setInstantiatedFromMemberTemplate(D); 473 474 // Trigger creation of the type for the instantiation. 475 SemaRef.Context.getTypeDeclType(RecordInst); 476 477 // Finish handling of friends. 478 if (Inst->getFriendObjectKind()) { 479 return Inst; 480 } 481 482 Owner->addDecl(Inst); 483 484 // First, we sort the partial specializations by location, so 485 // that we instantiate them in the order they were declared. 486 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 487 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 488 P = D->getPartialSpecializations().begin(), 489 PEnd = D->getPartialSpecializations().end(); 490 P != PEnd; ++P) 491 PartialSpecs.push_back(&*P); 492 std::sort(PartialSpecs.begin(), PartialSpecs.end(), 493 SortDeclByLocation(SemaRef.SourceMgr)); 494 495 // Instantiate all of the partial specializations of this member class 496 // template. 497 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 498 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]); 499 500 return Inst; 501} 502 503Decl * 504TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 505 ClassTemplatePartialSpecializationDecl *D) { 506 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 507 508 // Lookup the already-instantiated declaration in the instantiation 509 // of the class template and return that. 510 DeclContext::lookup_result Found 511 = Owner->lookup(ClassTemplate->getDeclName()); 512 if (Found.first == Found.second) 513 return 0; 514 515 ClassTemplateDecl *InstClassTemplate 516 = dyn_cast<ClassTemplateDecl>(*Found.first); 517 if (!InstClassTemplate) 518 return 0; 519 520 Decl *DCanon = D->getCanonicalDecl(); 521 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 522 P = InstClassTemplate->getPartialSpecializations().begin(), 523 PEnd = InstClassTemplate->getPartialSpecializations().end(); 524 P != PEnd; ++P) { 525 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon) 526 return &*P; 527 } 528 529 return 0; 530} 531 532Decl * 533TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 534 // Create a local instantiation scope for this function template, which 535 // will contain the instantiations of the template parameters and then get 536 // merged with the local instantiation scope for the function template 537 // itself. 538 Sema::LocalInstantiationScope Scope(SemaRef); 539 540 TemplateParameterList *TempParams = D->getTemplateParameters(); 541 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 542 if (!InstParams) 543 return NULL; 544 545 FunctionDecl *Instantiated = 0; 546 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 547 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 548 InstParams)); 549 else 550 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 551 D->getTemplatedDecl(), 552 InstParams)); 553 554 if (!Instantiated) 555 return 0; 556 557 // Link the instantiated function template declaration to the function 558 // template from which it was instantiated. 559 FunctionTemplateDecl *InstTemplate 560 = Instantiated->getDescribedFunctionTemplate(); 561 InstTemplate->setAccess(D->getAccess()); 562 assert(InstTemplate && 563 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 564 if (!InstTemplate->getInstantiatedFromMemberTemplate()) 565 InstTemplate->setInstantiatedFromMemberTemplate(D); 566 567 // Add non-friends into the owner. 568 if (!InstTemplate->getFriendObjectKind()) 569 Owner->addDecl(InstTemplate); 570 return InstTemplate; 571} 572 573Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 574 CXXRecordDecl *PrevDecl = 0; 575 if (D->isInjectedClassName()) 576 PrevDecl = cast<CXXRecordDecl>(Owner); 577 578 CXXRecordDecl *Record 579 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 580 D->getLocation(), D->getIdentifier(), 581 D->getTagKeywordLoc(), PrevDecl); 582 Record->setImplicit(D->isImplicit()); 583 // FIXME: Check against AS_none is an ugly hack to work around the issue that 584 // the tag decls introduced by friend class declarations don't have an access 585 // specifier. Remove once this area of the code gets sorted out. 586 if (D->getAccess() != AS_none) 587 Record->setAccess(D->getAccess()); 588 if (!D->isInjectedClassName()) 589 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 590 591 // If the original function was part of a friend declaration, 592 // inherit its namespace state. 593 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 594 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 595 596 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion()); 597 598 Owner->addDecl(Record); 599 return Record; 600} 601 602/// Normal class members are of more specific types and therefore 603/// don't make it here. This function serves two purposes: 604/// 1) instantiating function templates 605/// 2) substituting friend declarations 606/// FIXME: preserve function definitions in case #2 607 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 608 TemplateParameterList *TemplateParams) { 609 // Check whether there is already a function template specialization for 610 // this declaration. 611 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 612 void *InsertPos = 0; 613 if (FunctionTemplate && !TemplateParams) { 614 llvm::FoldingSetNodeID ID; 615 FunctionTemplateSpecializationInfo::Profile(ID, 616 TemplateArgs.getInnermost().getFlatArgumentList(), 617 TemplateArgs.getInnermost().flat_size(), 618 SemaRef.Context); 619 620 FunctionTemplateSpecializationInfo *Info 621 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 622 InsertPos); 623 624 // If we already have a function template specialization, return it. 625 if (Info) 626 return Info->Function; 627 } 628 629 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0); 630 631 llvm::SmallVector<ParmVarDecl *, 4> Params; 632 QualType T = SubstFunctionType(D, Params); 633 if (T.isNull()) 634 return 0; 635 636 // Build the instantiated method declaration. 637 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(), 638 TemplateArgs); 639 FunctionDecl *Function = 640 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(), 641 D->getDeclName(), T, D->getDeclaratorInfo(), 642 D->getStorageClass(), 643 D->isInlineSpecified(), D->hasWrittenPrototype()); 644 Function->setLexicalDeclContext(Owner); 645 646 // Attach the parameters 647 for (unsigned P = 0; P < Params.size(); ++P) 648 Params[P]->setOwningFunction(Function); 649 Function->setParams(SemaRef.Context, Params.data(), Params.size()); 650 651 if (TemplateParams) { 652 // Our resulting instantiation is actually a function template, since we 653 // are substituting only the outer template parameters. For example, given 654 // 655 // template<typename T> 656 // struct X { 657 // template<typename U> friend void f(T, U); 658 // }; 659 // 660 // X<int> x; 661 // 662 // We are instantiating the friend function template "f" within X<int>, 663 // which means substituting int for T, but leaving "f" as a friend function 664 // template. 665 // Build the function template itself. 666 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner, 667 Function->getLocation(), 668 Function->getDeclName(), 669 TemplateParams, Function); 670 Function->setDescribedFunctionTemplate(FunctionTemplate); 671 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 672 } else if (FunctionTemplate) { 673 // Record this function template specialization. 674 Function->setFunctionTemplateSpecialization(SemaRef.Context, 675 FunctionTemplate, 676 &TemplateArgs.getInnermost(), 677 InsertPos); 678 } 679 680 if (InitFunctionInstantiation(Function, D)) 681 Function->setInvalidDecl(); 682 683 bool Redeclaration = false; 684 bool OverloadableAttrRequired = false; 685 686 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(), 687 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 688 689 if (TemplateParams || !FunctionTemplate) { 690 // Look only into the namespace where the friend would be declared to 691 // find a previous declaration. This is the innermost enclosing namespace, 692 // as described in ActOnFriendFunctionDecl. 693 SemaRef.LookupQualifiedName(Previous, DC); 694 695 // In C++, the previous declaration we find might be a tag type 696 // (class or enum). In this case, the new declaration will hide the 697 // tag type. Note that this does does not apply if we're declaring a 698 // typedef (C++ [dcl.typedef]p4). 699 if (Previous.isSingleTagDecl()) 700 Previous.clear(); 701 } 702 703 SemaRef.CheckFunctionDeclaration(Function, Previous, false, Redeclaration, 704 /*FIXME:*/OverloadableAttrRequired); 705 706 // If the original function was part of a friend declaration, 707 // inherit its namespace state and add it to the owner. 708 NamedDecl *FromFriendD 709 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D; 710 if (FromFriendD->getFriendObjectKind()) { 711 NamedDecl *ToFriendD = 0; 712 NamedDecl *PrevDecl; 713 if (TemplateParams) { 714 ToFriendD = cast<NamedDecl>(FunctionTemplate); 715 PrevDecl = FunctionTemplate->getPreviousDeclaration(); 716 } else { 717 ToFriendD = Function; 718 PrevDecl = Function->getPreviousDeclaration(); 719 } 720 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL); 721 if (!Owner->isDependentContext() && !PrevDecl) 722 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false); 723 724 if (!TemplateParams) 725 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 726 } 727 728 return Function; 729} 730 731Decl * 732TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 733 TemplateParameterList *TemplateParams) { 734 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 735 void *InsertPos = 0; 736 if (FunctionTemplate && !TemplateParams) { 737 // We are creating a function template specialization from a function 738 // template. Check whether there is already a function template 739 // specialization for this particular set of template arguments. 740 llvm::FoldingSetNodeID ID; 741 FunctionTemplateSpecializationInfo::Profile(ID, 742 TemplateArgs.getInnermost().getFlatArgumentList(), 743 TemplateArgs.getInnermost().flat_size(), 744 SemaRef.Context); 745 746 FunctionTemplateSpecializationInfo *Info 747 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 748 InsertPos); 749 750 // If we already have a function template specialization, return it. 751 if (Info) 752 return Info->Function; 753 } 754 755 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0); 756 757 llvm::SmallVector<ParmVarDecl *, 4> Params; 758 QualType T = SubstFunctionType(D, Params); 759 if (T.isNull()) 760 return 0; 761 762 // Build the instantiated method declaration. 763 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 764 CXXMethodDecl *Method = 0; 765 766 DeclarationName Name = D->getDeclName(); 767 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 768 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 769 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName( 770 SemaRef.Context.getCanonicalType(ClassTy)); 771 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 772 Constructor->getLocation(), 773 Name, T, 774 Constructor->getDeclaratorInfo(), 775 Constructor->isExplicit(), 776 Constructor->isInlineSpecified(), false); 777 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 778 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 779 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName( 780 SemaRef.Context.getCanonicalType(ClassTy)); 781 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 782 Destructor->getLocation(), Name, 783 T, Destructor->isInlineSpecified(), false); 784 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 785 CanQualType ConvTy 786 = SemaRef.Context.getCanonicalType( 787 T->getAs<FunctionType>()->getResultType()); 788 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName( 789 ConvTy); 790 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 791 Conversion->getLocation(), Name, 792 T, Conversion->getDeclaratorInfo(), 793 Conversion->isInlineSpecified(), 794 Conversion->isExplicit()); 795 } else { 796 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 797 D->getDeclName(), T, D->getDeclaratorInfo(), 798 D->isStatic(), D->isInlineSpecified()); 799 } 800 801 if (TemplateParams) { 802 // Our resulting instantiation is actually a function template, since we 803 // are substituting only the outer template parameters. For example, given 804 // 805 // template<typename T> 806 // struct X { 807 // template<typename U> void f(T, U); 808 // }; 809 // 810 // X<int> x; 811 // 812 // We are instantiating the member template "f" within X<int>, which means 813 // substituting int for T, but leaving "f" as a member function template. 814 // Build the function template itself. 815 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 816 Method->getLocation(), 817 Method->getDeclName(), 818 TemplateParams, Method); 819 if (D->isOutOfLine()) 820 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 821 Method->setDescribedFunctionTemplate(FunctionTemplate); 822 } else if (FunctionTemplate) { 823 // Record this function template specialization. 824 Method->setFunctionTemplateSpecialization(SemaRef.Context, 825 FunctionTemplate, 826 &TemplateArgs.getInnermost(), 827 InsertPos); 828 } else { 829 // Record that this is an instantiation of a member function. 830 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 831 } 832 833 // If we are instantiating a member function defined 834 // out-of-line, the instantiation will have the same lexical 835 // context (which will be a namespace scope) as the template. 836 if (D->isOutOfLine()) 837 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 838 839 // Attach the parameters 840 for (unsigned P = 0; P < Params.size(); ++P) 841 Params[P]->setOwningFunction(Method); 842 Method->setParams(SemaRef.Context, Params.data(), Params.size()); 843 844 if (InitMethodInstantiation(Method, D)) 845 Method->setInvalidDecl(); 846 847 LookupResult Previous(SemaRef, Name, SourceLocation(), 848 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 849 850 if (!FunctionTemplate || TemplateParams) { 851 SemaRef.LookupQualifiedName(Previous, Owner); 852 853 // In C++, the previous declaration we find might be a tag type 854 // (class or enum). In this case, the new declaration will hide the 855 // tag type. Note that this does does not apply if we're declaring a 856 // typedef (C++ [dcl.typedef]p4). 857 if (Previous.isSingleTagDecl()) 858 Previous.clear(); 859 } 860 861 bool Redeclaration = false; 862 bool OverloadableAttrRequired = false; 863 SemaRef.CheckFunctionDeclaration(Method, Previous, false, Redeclaration, 864 /*FIXME:*/OverloadableAttrRequired); 865 866 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) && 867 !Method->getFriendObjectKind()) 868 Owner->addDecl(Method); 869 870 SemaRef.AddOverriddenMethods(Record, Method); 871 872 return Method; 873} 874 875Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 876 return VisitCXXMethodDecl(D); 877} 878 879Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 880 return VisitCXXMethodDecl(D); 881} 882 883Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 884 return VisitCXXMethodDecl(D); 885} 886 887ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 888 QualType T; 889 DeclaratorInfo *DI = D->getDeclaratorInfo(); 890 if (DI) { 891 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 892 D->getDeclName()); 893 if (DI) T = DI->getType(); 894 } else { 895 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 896 D->getDeclName()); 897 DI = 0; 898 } 899 900 if (T.isNull()) 901 return 0; 902 903 T = SemaRef.adjustParameterType(T); 904 905 // Allocate the parameter 906 ParmVarDecl *Param 907 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(), 908 D->getIdentifier(), T, DI, D->getStorageClass(), 0); 909 910 // Mark the default argument as being uninstantiated. 911 if (D->hasUninstantiatedDefaultArg()) 912 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg()); 913 else if (Expr *Arg = D->getDefaultArg()) 914 Param->setUninstantiatedDefaultArg(Arg); 915 916 // Note: we don't try to instantiate function parameters until after 917 // we've instantiated the function's type. Therefore, we don't have 918 // to check for 'void' parameter types here. 919 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 920 return Param; 921} 922 923Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 924 TemplateTypeParmDecl *D) { 925 // TODO: don't always clone when decls are refcounted. 926 const Type* T = D->getTypeForDecl(); 927 assert(T->isTemplateTypeParmType()); 928 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>(); 929 930 TemplateTypeParmDecl *Inst = 931 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 932 TTPT->getDepth() - 1, TTPT->getIndex(), 933 TTPT->getName(), 934 D->wasDeclaredWithTypename(), 935 D->isParameterPack()); 936 937 if (D->hasDefaultArgument()) 938 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 939 940 // Introduce this template parameter's instantiation into the instantiation 941 // scope. 942 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 943 944 return Inst; 945} 946 947Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 948 NonTypeTemplateParmDecl *D) { 949 // Substitute into the type of the non-type template parameter. 950 QualType T; 951 DeclaratorInfo *DI = D->getDeclaratorInfo(); 952 if (DI) { 953 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 954 D->getDeclName()); 955 if (DI) T = DI->getType(); 956 } else { 957 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 958 D->getDeclName()); 959 DI = 0; 960 } 961 if (T.isNull()) 962 return 0; 963 964 // Check that this type is acceptable for a non-type template parameter. 965 bool Invalid = false; 966 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation()); 967 if (T.isNull()) { 968 T = SemaRef.Context.IntTy; 969 Invalid = true; 970 } 971 972 NonTypeTemplateParmDecl *Param 973 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 974 D->getDepth() - 1, D->getPosition(), 975 D->getIdentifier(), T, DI); 976 if (Invalid) 977 Param->setInvalidDecl(); 978 979 Param->setDefaultArgument(D->getDefaultArgument()); 980 981 // Introduce this template parameter's instantiation into the instantiation 982 // scope. 983 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 984 return Param; 985} 986 987Decl * 988TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 989 TemplateTemplateParmDecl *D) { 990 // Instantiate the template parameter list of the template template parameter. 991 TemplateParameterList *TempParams = D->getTemplateParameters(); 992 TemplateParameterList *InstParams; 993 { 994 // Perform the actual substitution of template parameters within a new, 995 // local instantiation scope. 996 Sema::LocalInstantiationScope Scope(SemaRef); 997 InstParams = SubstTemplateParams(TempParams); 998 if (!InstParams) 999 return NULL; 1000 } 1001 1002 // Build the template template parameter. 1003 TemplateTemplateParmDecl *Param 1004 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1005 D->getDepth() - 1, D->getPosition(), 1006 D->getIdentifier(), InstParams); 1007 Param->setDefaultArgument(D->getDefaultArgument()); 1008 1009 // Introduce this template parameter's instantiation into the instantiation 1010 // scope. 1011 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1012 1013 return Param; 1014} 1015 1016Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1017 // Using directives are never dependent, so they require no explicit 1018 1019 UsingDirectiveDecl *Inst 1020 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1021 D->getNamespaceKeyLocation(), 1022 D->getQualifierRange(), D->getQualifier(), 1023 D->getIdentLocation(), 1024 D->getNominatedNamespace(), 1025 D->getCommonAncestor()); 1026 Owner->addDecl(Inst); 1027 return Inst; 1028} 1029 1030Decl * TemplateDeclInstantiator 1031 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 1032 NestedNameSpecifier *NNS = 1033 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1034 D->getTargetNestedNameRange(), 1035 TemplateArgs); 1036 if (!NNS) 1037 return 0; 1038 1039 CXXScopeSpec SS; 1040 SS.setRange(D->getTargetNestedNameRange()); 1041 SS.setScopeRep(NNS); 1042 1043 NamedDecl *UD = 1044 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1045 D->getUsingLoc(), SS, D->getLocation(), 1046 D->getDeclName(), 0, 1047 /*instantiation*/ true, 1048 /*typename*/ true, D->getTypenameLoc()); 1049 if (UD) 1050 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD), 1051 D); 1052 return UD; 1053} 1054 1055Decl * TemplateDeclInstantiator 1056 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1057 NestedNameSpecifier *NNS = 1058 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1059 D->getTargetNestedNameRange(), 1060 TemplateArgs); 1061 if (!NNS) 1062 return 0; 1063 1064 CXXScopeSpec SS; 1065 SS.setRange(D->getTargetNestedNameRange()); 1066 SS.setScopeRep(NNS); 1067 1068 NamedDecl *UD = 1069 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1070 D->getUsingLoc(), SS, D->getLocation(), 1071 D->getDeclName(), 0, 1072 /*instantiation*/ true, 1073 /*typename*/ false, SourceLocation()); 1074 if (UD) 1075 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD), 1076 D); 1077 return UD; 1078} 1079 1080Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 1081 const MultiLevelTemplateArgumentList &TemplateArgs) { 1082 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 1083 return Instantiator.Visit(D); 1084} 1085 1086/// \brief Instantiates a nested template parameter list in the current 1087/// instantiation context. 1088/// 1089/// \param L The parameter list to instantiate 1090/// 1091/// \returns NULL if there was an error 1092TemplateParameterList * 1093TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 1094 // Get errors for all the parameters before bailing out. 1095 bool Invalid = false; 1096 1097 unsigned N = L->size(); 1098 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector; 1099 ParamVector Params; 1100 Params.reserve(N); 1101 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 1102 PI != PE; ++PI) { 1103 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 1104 Params.push_back(D); 1105 Invalid = Invalid || !D || D->isInvalidDecl(); 1106 } 1107 1108 // Clean up if we had an error. 1109 if (Invalid) { 1110 for (ParamVector::iterator PI = Params.begin(), PE = Params.end(); 1111 PI != PE; ++PI) 1112 if (*PI) 1113 (*PI)->Destroy(SemaRef.Context); 1114 return NULL; 1115 } 1116 1117 TemplateParameterList *InstL 1118 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 1119 L->getLAngleLoc(), &Params.front(), N, 1120 L->getRAngleLoc()); 1121 return InstL; 1122} 1123 1124/// \brief Instantiate the declaration of a class template partial 1125/// specialization. 1126/// 1127/// \param ClassTemplate the (instantiated) class template that is partially 1128// specialized by the instantiation of \p PartialSpec. 1129/// 1130/// \param PartialSpec the (uninstantiated) class template partial 1131/// specialization that we are instantiating. 1132/// 1133/// \returns true if there was an error, false otherwise. 1134bool 1135TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 1136 ClassTemplateDecl *ClassTemplate, 1137 ClassTemplatePartialSpecializationDecl *PartialSpec) { 1138 // Create a local instantiation scope for this class template partial 1139 // specialization, which will contain the instantiations of the template 1140 // parameters. 1141 Sema::LocalInstantiationScope Scope(SemaRef); 1142 1143 // Substitute into the template parameters of the class template partial 1144 // specialization. 1145 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 1146 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1147 if (!InstParams) 1148 return true; 1149 1150 // Substitute into the template arguments of the class template partial 1151 // specialization. 1152 const TemplateArgumentLoc *PartialSpecTemplateArgs 1153 = PartialSpec->getTemplateArgsAsWritten(); 1154 unsigned N = PartialSpec->getNumTemplateArgsAsWritten(); 1155 1156 llvm::SmallVector<TemplateArgumentLoc, 4> InstTemplateArgs(N); 1157 for (unsigned I = 0; I != N; ++I) { 1158 if (SemaRef.Subst(PartialSpecTemplateArgs[I], InstTemplateArgs[I], 1159 TemplateArgs)) 1160 return true; 1161 } 1162 1163 1164 // Check that the template argument list is well-formed for this 1165 // class template. 1166 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 1167 InstTemplateArgs.size()); 1168 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 1169 PartialSpec->getLocation(), 1170 /*FIXME:*/PartialSpec->getLocation(), 1171 InstTemplateArgs.data(), 1172 InstTemplateArgs.size(), 1173 /*FIXME:*/PartialSpec->getLocation(), 1174 false, 1175 Converted)) 1176 return true; 1177 1178 // Figure out where to insert this class template partial specialization 1179 // in the member template's set of class template partial specializations. 1180 llvm::FoldingSetNodeID ID; 1181 ClassTemplatePartialSpecializationDecl::Profile(ID, 1182 Converted.getFlatArguments(), 1183 Converted.flatSize(), 1184 SemaRef.Context); 1185 void *InsertPos = 0; 1186 ClassTemplateSpecializationDecl *PrevDecl 1187 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 1188 InsertPos); 1189 1190 // Build the canonical type that describes the converted template 1191 // arguments of the class template partial specialization. 1192 QualType CanonType 1193 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1194 Converted.getFlatArguments(), 1195 Converted.flatSize()); 1196 1197 // Build the fully-sugared type for this class template 1198 // specialization as the user wrote in the specialization 1199 // itself. This means that we'll pretty-print the type retrieved 1200 // from the specialization's declaration the way that the user 1201 // actually wrote the specialization, rather than formatting the 1202 // name based on the "canonical" representation used to store the 1203 // template arguments in the specialization. 1204 QualType WrittenTy 1205 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1206 InstTemplateArgs.data(), 1207 InstTemplateArgs.size(), 1208 CanonType); 1209 1210 if (PrevDecl) { 1211 // We've already seen a partial specialization with the same template 1212 // parameters and template arguments. This can happen, for example, when 1213 // substituting the outer template arguments ends up causing two 1214 // class template partial specializations of a member class template 1215 // to have identical forms, e.g., 1216 // 1217 // template<typename T, typename U> 1218 // struct Outer { 1219 // template<typename X, typename Y> struct Inner; 1220 // template<typename Y> struct Inner<T, Y>; 1221 // template<typename Y> struct Inner<U, Y>; 1222 // }; 1223 // 1224 // Outer<int, int> outer; // error: the partial specializations of Inner 1225 // // have the same signature. 1226 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 1227 << WrittenTy; 1228 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 1229 << SemaRef.Context.getTypeDeclType(PrevDecl); 1230 return true; 1231 } 1232 1233 1234 // Create the class template partial specialization declaration. 1235 ClassTemplatePartialSpecializationDecl *InstPartialSpec 1236 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner, 1237 PartialSpec->getLocation(), 1238 InstParams, 1239 ClassTemplate, 1240 Converted, 1241 InstTemplateArgs.data(), 1242 InstTemplateArgs.size(), 1243 0); 1244 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 1245 InstPartialSpec->setTypeAsWritten(WrittenTy); 1246 1247 // Add this partial specialization to the set of class template partial 1248 // specializations. 1249 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec, 1250 InsertPos); 1251 return false; 1252} 1253 1254/// \brief Does substitution on the type of the given function, including 1255/// all of the function parameters. 1256/// 1257/// \param D The function whose type will be the basis of the substitution 1258/// 1259/// \param Params the instantiated parameter declarations 1260 1261/// \returns the instantiated function's type if successful, a NULL 1262/// type if there was an error. 1263QualType 1264TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 1265 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 1266 bool InvalidDecl = false; 1267 1268 // Substitute all of the function's formal parameter types. 1269 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs); 1270 llvm::SmallVector<QualType, 4> ParamTys; 1271 for (FunctionDecl::param_iterator P = D->param_begin(), 1272 PEnd = D->param_end(); 1273 P != PEnd; ++P) { 1274 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { 1275 if (PInst->getType()->isVoidType()) { 1276 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); 1277 PInst->setInvalidDecl(); 1278 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), 1279 PInst->getType(), 1280 diag::err_abstract_type_in_decl, 1281 Sema::AbstractParamType)) 1282 PInst->setInvalidDecl(); 1283 1284 Params.push_back(PInst); 1285 ParamTys.push_back(PInst->getType()); 1286 1287 if (PInst->isInvalidDecl()) 1288 InvalidDecl = true; 1289 } else 1290 InvalidDecl = true; 1291 } 1292 1293 // FIXME: Deallocate dead declarations. 1294 if (InvalidDecl) 1295 return QualType(); 1296 1297 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>(); 1298 assert(Proto && "Missing prototype?"); 1299 QualType ResultType 1300 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs, 1301 D->getLocation(), D->getDeclName()); 1302 if (ResultType.isNull()) 1303 return QualType(); 1304 1305 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(), 1306 Proto->isVariadic(), Proto->getTypeQuals(), 1307 D->getLocation(), D->getDeclName()); 1308} 1309 1310/// \brief Initializes the common fields of an instantiation function 1311/// declaration (New) from the corresponding fields of its template (Tmpl). 1312/// 1313/// \returns true if there was an error 1314bool 1315TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 1316 FunctionDecl *Tmpl) { 1317 if (Tmpl->isDeleted()) 1318 New->setDeleted(); 1319 1320 // If we are performing substituting explicitly-specified template arguments 1321 // or deduced template arguments into a function template and we reach this 1322 // point, we are now past the point where SFINAE applies and have committed 1323 // to keeping the new function template specialization. We therefore 1324 // convert the active template instantiation for the function template 1325 // into a template instantiation for this specific function template 1326 // specialization, which is not a SFINAE context, so that we diagnose any 1327 // further errors in the declaration itself. 1328 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 1329 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 1330 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 1331 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 1332 if (FunctionTemplateDecl *FunTmpl 1333 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 1334 assert(FunTmpl->getTemplatedDecl() == Tmpl && 1335 "Deduction from the wrong function template?"); 1336 (void) FunTmpl; 1337 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 1338 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 1339 --SemaRef.NonInstantiationEntries; 1340 } 1341 } 1342 1343 return false; 1344} 1345 1346/// \brief Initializes common fields of an instantiated method 1347/// declaration (New) from the corresponding fields of its template 1348/// (Tmpl). 1349/// 1350/// \returns true if there was an error 1351bool 1352TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 1353 CXXMethodDecl *Tmpl) { 1354 if (InitFunctionInstantiation(New, Tmpl)) 1355 return true; 1356 1357 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 1358 New->setAccess(Tmpl->getAccess()); 1359 if (Tmpl->isVirtualAsWritten()) { 1360 New->setVirtualAsWritten(true); 1361 Record->setAggregate(false); 1362 Record->setPOD(false); 1363 Record->setEmpty(false); 1364 Record->setPolymorphic(true); 1365 } 1366 if (Tmpl->isPure()) { 1367 New->setPure(); 1368 Record->setAbstract(true); 1369 } 1370 1371 // FIXME: attributes 1372 // FIXME: New needs a pointer to Tmpl 1373 return false; 1374} 1375 1376/// \brief Instantiate the definition of the given function from its 1377/// template. 1378/// 1379/// \param PointOfInstantiation the point at which the instantiation was 1380/// required. Note that this is not precisely a "point of instantiation" 1381/// for the function, but it's close. 1382/// 1383/// \param Function the already-instantiated declaration of a 1384/// function template specialization or member function of a class template 1385/// specialization. 1386/// 1387/// \param Recursive if true, recursively instantiates any functions that 1388/// are required by this instantiation. 1389/// 1390/// \param DefinitionRequired if true, then we are performing an explicit 1391/// instantiation where the body of the function is required. Complain if 1392/// there is no such body. 1393void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 1394 FunctionDecl *Function, 1395 bool Recursive, 1396 bool DefinitionRequired) { 1397 if (Function->isInvalidDecl()) 1398 return; 1399 1400 assert(!Function->getBody() && "Already instantiated!"); 1401 1402 // Never instantiate an explicit specialization. 1403 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1404 return; 1405 1406 // Find the function body that we'll be substituting. 1407 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 1408 Stmt *Pattern = 0; 1409 if (PatternDecl) 1410 Pattern = PatternDecl->getBody(PatternDecl); 1411 1412 if (!Pattern) { 1413 if (DefinitionRequired) { 1414 if (Function->getPrimaryTemplate()) 1415 Diag(PointOfInstantiation, 1416 diag::err_explicit_instantiation_undefined_func_template) 1417 << Function->getPrimaryTemplate(); 1418 else 1419 Diag(PointOfInstantiation, 1420 diag::err_explicit_instantiation_undefined_member) 1421 << 1 << Function->getDeclName() << Function->getDeclContext(); 1422 1423 if (PatternDecl) 1424 Diag(PatternDecl->getLocation(), 1425 diag::note_explicit_instantiation_here); 1426 } 1427 1428 return; 1429 } 1430 1431 // C++0x [temp.explicit]p9: 1432 // Except for inline functions, other explicit instantiation declarations 1433 // have the effect of suppressing the implicit instantiation of the entity 1434 // to which they refer. 1435 if (Function->getTemplateSpecializationKind() 1436 == TSK_ExplicitInstantiationDeclaration && 1437 !PatternDecl->isInlined()) 1438 return; 1439 1440 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 1441 if (Inst) 1442 return; 1443 1444 // If we're performing recursive template instantiation, create our own 1445 // queue of pending implicit instantiations that we will instantiate later, 1446 // while we're still within our own instantiation context. 1447 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1448 if (Recursive) 1449 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1450 1451 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 1452 1453 // Introduce a new scope where local variable instantiations will be 1454 // recorded. 1455 LocalInstantiationScope Scope(*this); 1456 1457 // Introduce the instantiated function parameters into the local 1458 // instantiation scope. 1459 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 1460 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 1461 Function->getParamDecl(I)); 1462 1463 // Enter the scope of this instantiation. We don't use 1464 // PushDeclContext because we don't have a scope. 1465 DeclContext *PreviousContext = CurContext; 1466 CurContext = Function; 1467 1468 MultiLevelTemplateArgumentList TemplateArgs = 1469 getTemplateInstantiationArgs(Function); 1470 1471 // If this is a constructor, instantiate the member initializers. 1472 if (const CXXConstructorDecl *Ctor = 1473 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 1474 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 1475 TemplateArgs); 1476 } 1477 1478 // Instantiate the function body. 1479 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs); 1480 1481 if (Body.isInvalid()) 1482 Function->setInvalidDecl(); 1483 1484 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 1485 /*IsInstantiation=*/true); 1486 1487 CurContext = PreviousContext; 1488 1489 DeclGroupRef DG(Function); 1490 Consumer.HandleTopLevelDecl(DG); 1491 1492 if (Recursive) { 1493 // Instantiate any pending implicit instantiations found during the 1494 // instantiation of this template. 1495 PerformPendingImplicitInstantiations(); 1496 1497 // Restore the set of pending implicit instantiations. 1498 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1499 } 1500} 1501 1502/// \brief Instantiate the definition of the given variable from its 1503/// template. 1504/// 1505/// \param PointOfInstantiation the point at which the instantiation was 1506/// required. Note that this is not precisely a "point of instantiation" 1507/// for the function, but it's close. 1508/// 1509/// \param Var the already-instantiated declaration of a static member 1510/// variable of a class template specialization. 1511/// 1512/// \param Recursive if true, recursively instantiates any functions that 1513/// are required by this instantiation. 1514/// 1515/// \param DefinitionRequired if true, then we are performing an explicit 1516/// instantiation where an out-of-line definition of the member variable 1517/// is required. Complain if there is no such definition. 1518void Sema::InstantiateStaticDataMemberDefinition( 1519 SourceLocation PointOfInstantiation, 1520 VarDecl *Var, 1521 bool Recursive, 1522 bool DefinitionRequired) { 1523 if (Var->isInvalidDecl()) 1524 return; 1525 1526 // Find the out-of-line definition of this static data member. 1527 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 1528 assert(Def && "This data member was not instantiated from a template?"); 1529 assert(Def->isStaticDataMember() && "Not a static data member?"); 1530 Def = Def->getOutOfLineDefinition(); 1531 1532 if (!Def) { 1533 // We did not find an out-of-line definition of this static data member, 1534 // so we won't perform any instantiation. Rather, we rely on the user to 1535 // instantiate this definition (or provide a specialization for it) in 1536 // another translation unit. 1537 if (DefinitionRequired) { 1538 Def = Var->getInstantiatedFromStaticDataMember(); 1539 Diag(PointOfInstantiation, 1540 diag::err_explicit_instantiation_undefined_member) 1541 << 2 << Var->getDeclName() << Var->getDeclContext(); 1542 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 1543 } 1544 1545 return; 1546 } 1547 1548 // Never instantiate an explicit specialization. 1549 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1550 return; 1551 1552 // C++0x [temp.explicit]p9: 1553 // Except for inline functions, other explicit instantiation declarations 1554 // have the effect of suppressing the implicit instantiation of the entity 1555 // to which they refer. 1556 if (Var->getTemplateSpecializationKind() 1557 == TSK_ExplicitInstantiationDeclaration) 1558 return; 1559 1560 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 1561 if (Inst) 1562 return; 1563 1564 // If we're performing recursive template instantiation, create our own 1565 // queue of pending implicit instantiations that we will instantiate later, 1566 // while we're still within our own instantiation context. 1567 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1568 if (Recursive) 1569 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1570 1571 // Enter the scope of this instantiation. We don't use 1572 // PushDeclContext because we don't have a scope. 1573 DeclContext *PreviousContext = CurContext; 1574 CurContext = Var->getDeclContext(); 1575 1576 VarDecl *OldVar = Var; 1577 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 1578 getTemplateInstantiationArgs(Var))); 1579 CurContext = PreviousContext; 1580 1581 if (Var) { 1582 Var->setPreviousDeclaration(OldVar); 1583 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 1584 assert(MSInfo && "Missing member specialization information?"); 1585 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 1586 MSInfo->getPointOfInstantiation()); 1587 DeclGroupRef DG(Var); 1588 Consumer.HandleTopLevelDecl(DG); 1589 } 1590 1591 if (Recursive) { 1592 // Instantiate any pending implicit instantiations found during the 1593 // instantiation of this template. 1594 PerformPendingImplicitInstantiations(); 1595 1596 // Restore the set of pending implicit instantiations. 1597 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1598 } 1599} 1600 1601void 1602Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 1603 const CXXConstructorDecl *Tmpl, 1604 const MultiLevelTemplateArgumentList &TemplateArgs) { 1605 1606 llvm::SmallVector<MemInitTy*, 4> NewInits; 1607 1608 // Instantiate all the initializers. 1609 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 1610 InitsEnd = Tmpl->init_end(); 1611 Inits != InitsEnd; ++Inits) { 1612 CXXBaseOrMemberInitializer *Init = *Inits; 1613 1614 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this); 1615 1616 // Instantiate all the arguments. 1617 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end(); 1618 Args != ArgsEnd; ++Args) { 1619 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs); 1620 1621 if (NewArg.isInvalid()) 1622 New->setInvalidDecl(); 1623 else 1624 NewArgs.push_back(NewArg.takeAs<Expr>()); 1625 } 1626 1627 MemInitResult NewInit; 1628 1629 if (Init->isBaseInitializer()) { 1630 QualType BaseType(Init->getBaseClass(), 0); 1631 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(), 1632 New->getDeclName()); 1633 1634 NewInit = BuildBaseInitializer(BaseType, 1635 (Expr **)NewArgs.data(), 1636 NewArgs.size(), 1637 Init->getSourceLocation(), 1638 Init->getRParenLoc(), 1639 New->getParent()); 1640 } else if (Init->isMemberInitializer()) { 1641 FieldDecl *Member; 1642 1643 // Is this an anonymous union? 1644 if (FieldDecl *UnionInit = Init->getAnonUnionMember()) 1645 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs)); 1646 else 1647 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(), 1648 TemplateArgs)); 1649 1650 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 1651 NewArgs.size(), 1652 Init->getSourceLocation(), 1653 Init->getRParenLoc()); 1654 } 1655 1656 if (NewInit.isInvalid()) 1657 New->setInvalidDecl(); 1658 else { 1659 // FIXME: It would be nice if ASTOwningVector had a release function. 1660 NewArgs.take(); 1661 1662 NewInits.push_back((MemInitTy *)NewInit.get()); 1663 } 1664 } 1665 1666 // Assign all the initializers to the new constructor. 1667 ActOnMemInitializers(DeclPtrTy::make(New), 1668 /*FIXME: ColonLoc */ 1669 SourceLocation(), 1670 NewInits.data(), NewInits.size()); 1671} 1672 1673// TODO: this could be templated if the various decl types used the 1674// same method name. 1675static bool isInstantiationOf(ClassTemplateDecl *Pattern, 1676 ClassTemplateDecl *Instance) { 1677 Pattern = Pattern->getCanonicalDecl(); 1678 1679 do { 1680 Instance = Instance->getCanonicalDecl(); 1681 if (Pattern == Instance) return true; 1682 Instance = Instance->getInstantiatedFromMemberTemplate(); 1683 } while (Instance); 1684 1685 return false; 1686} 1687 1688static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 1689 FunctionTemplateDecl *Instance) { 1690 Pattern = Pattern->getCanonicalDecl(); 1691 1692 do { 1693 Instance = Instance->getCanonicalDecl(); 1694 if (Pattern == Instance) return true; 1695 Instance = Instance->getInstantiatedFromMemberTemplate(); 1696 } while (Instance); 1697 1698 return false; 1699} 1700 1701static bool 1702isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 1703 ClassTemplatePartialSpecializationDecl *Instance) { 1704 Pattern 1705 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 1706 do { 1707 Instance = cast<ClassTemplatePartialSpecializationDecl>( 1708 Instance->getCanonicalDecl()); 1709 if (Pattern == Instance) 1710 return true; 1711 Instance = Instance->getInstantiatedFromMember(); 1712 } while (Instance); 1713 1714 return false; 1715} 1716 1717static bool isInstantiationOf(CXXRecordDecl *Pattern, 1718 CXXRecordDecl *Instance) { 1719 Pattern = Pattern->getCanonicalDecl(); 1720 1721 do { 1722 Instance = Instance->getCanonicalDecl(); 1723 if (Pattern == Instance) return true; 1724 Instance = Instance->getInstantiatedFromMemberClass(); 1725 } while (Instance); 1726 1727 return false; 1728} 1729 1730static bool isInstantiationOf(FunctionDecl *Pattern, 1731 FunctionDecl *Instance) { 1732 Pattern = Pattern->getCanonicalDecl(); 1733 1734 do { 1735 Instance = Instance->getCanonicalDecl(); 1736 if (Pattern == Instance) return true; 1737 Instance = Instance->getInstantiatedFromMemberFunction(); 1738 } while (Instance); 1739 1740 return false; 1741} 1742 1743static bool isInstantiationOf(EnumDecl *Pattern, 1744 EnumDecl *Instance) { 1745 Pattern = Pattern->getCanonicalDecl(); 1746 1747 do { 1748 Instance = Instance->getCanonicalDecl(); 1749 if (Pattern == Instance) return true; 1750 Instance = Instance->getInstantiatedFromMemberEnum(); 1751 } while (Instance); 1752 1753 return false; 1754} 1755 1756static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 1757 UsingDecl *Instance, 1758 ASTContext &C) { 1759 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern; 1760} 1761 1762static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 1763 UsingDecl *Instance, 1764 ASTContext &C) { 1765 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern; 1766} 1767 1768static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 1769 VarDecl *Instance) { 1770 assert(Instance->isStaticDataMember()); 1771 1772 Pattern = Pattern->getCanonicalDecl(); 1773 1774 do { 1775 Instance = Instance->getCanonicalDecl(); 1776 if (Pattern == Instance) return true; 1777 Instance = Instance->getInstantiatedFromStaticDataMember(); 1778 } while (Instance); 1779 1780 return false; 1781} 1782 1783static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 1784 if (D->getKind() != Other->getKind()) { 1785 if (UnresolvedUsingTypenameDecl *UUD 1786 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 1787 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 1788 return isInstantiationOf(UUD, UD, Ctx); 1789 } 1790 } 1791 1792 if (UnresolvedUsingValueDecl *UUD 1793 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 1794 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 1795 return isInstantiationOf(UUD, UD, Ctx); 1796 } 1797 } 1798 1799 return false; 1800 } 1801 1802 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 1803 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 1804 1805 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 1806 return isInstantiationOf(cast<FunctionDecl>(D), Function); 1807 1808 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 1809 return isInstantiationOf(cast<EnumDecl>(D), Enum); 1810 1811 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 1812 if (Var->isStaticDataMember()) 1813 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 1814 1815 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 1816 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 1817 1818 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 1819 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 1820 1821 if (ClassTemplatePartialSpecializationDecl *PartialSpec 1822 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 1823 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 1824 PartialSpec); 1825 1826 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 1827 if (!Field->getDeclName()) { 1828 // This is an unnamed field. 1829 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 1830 cast<FieldDecl>(D); 1831 } 1832 } 1833 1834 return D->getDeclName() && isa<NamedDecl>(Other) && 1835 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 1836} 1837 1838template<typename ForwardIterator> 1839static NamedDecl *findInstantiationOf(ASTContext &Ctx, 1840 NamedDecl *D, 1841 ForwardIterator first, 1842 ForwardIterator last) { 1843 for (; first != last; ++first) 1844 if (isInstantiationOf(Ctx, D, *first)) 1845 return cast<NamedDecl>(*first); 1846 1847 return 0; 1848} 1849 1850/// \brief Finds the instantiation of the given declaration context 1851/// within the current instantiation. 1852/// 1853/// \returns NULL if there was an error 1854DeclContext *Sema::FindInstantiatedContext(DeclContext* DC, 1855 const MultiLevelTemplateArgumentList &TemplateArgs) { 1856 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 1857 Decl* ID = FindInstantiatedDecl(D, TemplateArgs); 1858 return cast_or_null<DeclContext>(ID); 1859 } else return DC; 1860} 1861 1862/// \brief Find the instantiation of the given declaration within the 1863/// current instantiation. 1864/// 1865/// This routine is intended to be used when \p D is a declaration 1866/// referenced from within a template, that needs to mapped into the 1867/// corresponding declaration within an instantiation. For example, 1868/// given: 1869/// 1870/// \code 1871/// template<typename T> 1872/// struct X { 1873/// enum Kind { 1874/// KnownValue = sizeof(T) 1875/// }; 1876/// 1877/// bool getKind() const { return KnownValue; } 1878/// }; 1879/// 1880/// template struct X<int>; 1881/// \endcode 1882/// 1883/// In the instantiation of X<int>::getKind(), we need to map the 1884/// EnumConstantDecl for KnownValue (which refers to 1885/// X<T>::<Kind>::KnownValue) to its instantiation 1886/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 1887/// this mapping from within the instantiation of X<int>. 1888NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D, 1889 const MultiLevelTemplateArgumentList &TemplateArgs) { 1890 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) { 1891 // Transform all of the elements of the overloaded function set. 1892 OverloadedFunctionDecl *Result 1893 = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName()); 1894 1895 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 1896 FEnd = Ovl->function_end(); 1897 F != FEnd; ++F) { 1898 Result->addOverload( 1899 AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F, 1900 TemplateArgs))); 1901 } 1902 1903 return Result; 1904 } 1905 1906 DeclContext *ParentDC = D->getDeclContext(); 1907 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 1908 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 1909 ParentDC->isFunctionOrMethod()) { 1910 // D is a local of some kind. Look into the map of local 1911 // declarations to their instantiations. 1912 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 1913 } 1914 1915 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 1916 if (!Record->isDependentContext()) 1917 return D; 1918 1919 // If the RecordDecl is actually the injected-class-name or a "templated" 1920 // declaration for a class template or class template partial 1921 // specialization, substitute into the injected-class-name of the 1922 // class template or partial specialization to find the new DeclContext. 1923 QualType T; 1924 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 1925 1926 if (ClassTemplate) { 1927 T = ClassTemplate->getInjectedClassNameType(Context); 1928 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 1929 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 1930 T = Context.getTypeDeclType(Record); 1931 ClassTemplate = PartialSpec->getSpecializedTemplate(); 1932 } 1933 1934 if (!T.isNull()) { 1935 // Substitute into the injected-class-name to get the type corresponding 1936 // to the instantiation we want. This substitution should never fail, 1937 // since we know we can instantiate the injected-class-name or we wouldn't 1938 // have gotten to the injected-class-name! 1939 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra 1940 // instantiation in the common case? 1941 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName()); 1942 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail."); 1943 1944 if (!T->isDependentType()) { 1945 assert(T->isRecordType() && "Instantiation must produce a record type"); 1946 return T->getAs<RecordType>()->getDecl(); 1947 } 1948 1949 // We are performing "partial" template instantiation to create the 1950 // member declarations for the members of a class template 1951 // specialization. Therefore, D is actually referring to something in 1952 // the current instantiation. Look through the current context, 1953 // which contains actual instantiations, to find the instantiation of 1954 // the "current instantiation" that D refers to. 1955 for (DeclContext *DC = CurContext; !DC->isFileContext(); 1956 DC = DC->getParent()) { 1957 if (ClassTemplateSpecializationDecl *Spec 1958 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 1959 if (isInstantiationOf(ClassTemplate, 1960 Spec->getSpecializedTemplate())) 1961 return Spec; 1962 } 1963 1964 assert(false && 1965 "Unable to find declaration for the current instantiation"); 1966 return Record; 1967 } 1968 1969 // Fall through to deal with other dependent record types (e.g., 1970 // anonymous unions in class templates). 1971 } 1972 1973 if (!ParentDC->isDependentContext()) 1974 return D; 1975 1976 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs); 1977 if (!ParentDC) 1978 return 0; 1979 1980 if (ParentDC != D->getDeclContext()) { 1981 // We performed some kind of instantiation in the parent context, 1982 // so now we need to look into the instantiated parent context to 1983 // find the instantiation of the declaration D. 1984 NamedDecl *Result = 0; 1985 if (D->getDeclName()) { 1986 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 1987 Result = findInstantiationOf(Context, D, Found.first, Found.second); 1988 } else { 1989 // Since we don't have a name for the entity we're looking for, 1990 // our only option is to walk through all of the declarations to 1991 // find that name. This will occur in a few cases: 1992 // 1993 // - anonymous struct/union within a template 1994 // - unnamed class/struct/union/enum within a template 1995 // 1996 // FIXME: Find a better way to find these instantiations! 1997 Result = findInstantiationOf(Context, D, 1998 ParentDC->decls_begin(), 1999 ParentDC->decls_end()); 2000 } 2001 2002 assert(Result && "Unable to find instantiation of declaration!"); 2003 D = Result; 2004 } 2005 2006 return D; 2007} 2008 2009/// \brief Performs template instantiation for all implicit template 2010/// instantiations we have seen until this point. 2011void Sema::PerformPendingImplicitInstantiations() { 2012 while (!PendingImplicitInstantiations.empty()) { 2013 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front(); 2014 PendingImplicitInstantiations.pop_front(); 2015 2016 // Instantiate function definitions 2017 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 2018 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function), 2019 Function->getLocation(), *this, 2020 Context.getSourceManager(), 2021 "instantiating function definition"); 2022 2023 if (!Function->getBody()) 2024 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 2025 continue; 2026 } 2027 2028 // Instantiate static data member definitions. 2029 VarDecl *Var = cast<VarDecl>(Inst.first); 2030 assert(Var->isStaticDataMember() && "Not a static data member?"); 2031 2032 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var), 2033 Var->getLocation(), *this, 2034 Context.getSourceManager(), 2035 "instantiating static data member " 2036 "definition"); 2037 2038 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 2039 } 2040} 2041