SemaTemplateInstantiateDecl.cpp revision 7dafdf51176d2f52e3a27f1ef70161ea2133ff52
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 22using namespace clang; 23 24namespace { 25 class TemplateDeclInstantiator 26 : public DeclVisitor<TemplateDeclInstantiator, Decl *> { 27 Sema &SemaRef; 28 DeclContext *Owner; 29 const MultiLevelTemplateArgumentList &TemplateArgs; 30 31 void InstantiateAttrs(Decl *Tmpl, Decl *New); 32 33 public: 34 typedef Sema::OwningExprResult OwningExprResult; 35 36 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, 37 const MultiLevelTemplateArgumentList &TemplateArgs) 38 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { } 39 40 // FIXME: Once we get closer to completion, replace these manually-written 41 // declarations with automatically-generated ones from 42 // clang/AST/DeclNodes.def. 43 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); 44 Decl *VisitNamespaceDecl(NamespaceDecl *D); 45 Decl *VisitTypedefDecl(TypedefDecl *D); 46 Decl *VisitVarDecl(VarDecl *D); 47 Decl *VisitFieldDecl(FieldDecl *D); 48 Decl *VisitStaticAssertDecl(StaticAssertDecl *D); 49 Decl *VisitEnumDecl(EnumDecl *D); 50 Decl *VisitEnumConstantDecl(EnumConstantDecl *D); 51 Decl *VisitFriendDecl(FriendDecl *D); 52 Decl *VisitFunctionDecl(FunctionDecl *D, 53 TemplateParameterList *TemplateParams = 0); 54 Decl *VisitCXXRecordDecl(CXXRecordDecl *D); 55 Decl *VisitCXXMethodDecl(CXXMethodDecl *D, 56 TemplateParameterList *TemplateParams = 0); 57 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 58 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 59 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 60 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 61 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D); 62 Decl *VisitClassTemplatePartialSpecializationDecl( 63 ClassTemplatePartialSpecializationDecl *D); 64 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 65 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 66 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 67 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 68 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 69 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 70 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 71 72 // Base case. FIXME: Remove once we can instantiate everything. 73 Decl *VisitDecl(Decl *D) { 74 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 75 Diagnostic::Error, 76 "cannot instantiate %0 yet"); 77 SemaRef.Diag(D->getLocation(), DiagID) 78 << D->getDeclKindName(); 79 80 return 0; 81 } 82 83 const LangOptions &getLangOptions() { 84 return SemaRef.getLangOptions(); 85 } 86 87 // Helper functions for instantiating methods. 88 QualType SubstFunctionType(FunctionDecl *D, 89 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 90 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl); 91 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 92 93 TemplateParameterList * 94 SubstTemplateParams(TemplateParameterList *List); 95 96 bool InstantiateClassTemplatePartialSpecialization( 97 ClassTemplateDecl *ClassTemplate, 98 ClassTemplatePartialSpecializationDecl *PartialSpec); 99 }; 100} 101 102// FIXME: Is this too simple? 103void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) { 104 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr; 105 TmplAttr = TmplAttr->getNext()) { 106 107 // FIXME: Is cloning correct for all attributes? 108 Attr *NewAttr = TmplAttr->clone(SemaRef.Context); 109 110 New->addAttr(NewAttr); 111 } 112} 113 114Decl * 115TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 116 assert(false && "Translation units cannot be instantiated"); 117 return D; 118} 119 120Decl * 121TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 122 assert(false && "Namespaces cannot be instantiated"); 123 return D; 124} 125 126Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 127 bool Invalid = false; 128 DeclaratorInfo *DI = D->getTypeDeclaratorInfo(); 129 if (DI->getType()->isDependentType()) { 130 DI = SemaRef.SubstType(DI, TemplateArgs, 131 D->getLocation(), D->getDeclName()); 132 if (!DI) { 133 Invalid = true; 134 DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy); 135 } 136 } 137 138 // Create the new typedef 139 TypedefDecl *Typedef 140 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 141 D->getIdentifier(), DI); 142 if (Invalid) 143 Typedef->setInvalidDecl(); 144 145 Owner->addDecl(Typedef); 146 147 return Typedef; 148} 149 150Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 151 // Do substitution on the type of the declaration 152 DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(), 153 TemplateArgs, 154 D->getTypeSpecStartLoc(), 155 D->getDeclName()); 156 if (!DI) 157 return 0; 158 159 // Build the instantiated declaration 160 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 161 D->getLocation(), D->getIdentifier(), 162 DI->getType(), DI, 163 D->getStorageClass()); 164 Var->setThreadSpecified(D->isThreadSpecified()); 165 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 166 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 167 168 // If we are instantiating a static data member defined 169 // out-of-line, the instantiation will have the same lexical 170 // context (which will be a namespace scope) as the template. 171 if (D->isOutOfLine()) 172 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 173 174 // FIXME: In theory, we could have a previous declaration for variables that 175 // are not static data members. 176 bool Redeclaration = false; 177 // FIXME: having to fake up a LookupResult is dumb. 178 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(), 179 Sema::LookupOrdinaryName); 180 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration); 181 182 if (D->isOutOfLine()) { 183 D->getLexicalDeclContext()->addDecl(Var); 184 Owner->makeDeclVisibleInContext(Var); 185 } else { 186 Owner->addDecl(Var); 187 } 188 189 // Link instantiations of static data members back to the template from 190 // which they were instantiated. 191 if (Var->isStaticDataMember()) 192 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 193 TSK_ImplicitInstantiation); 194 195 if (D->getInit()) { 196 OwningExprResult Init 197 = SemaRef.SubstExpr(D->getInit(), TemplateArgs); 198 if (Init.isInvalid()) 199 Var->setInvalidDecl(); 200 else if (!D->getType()->isDependentType() && 201 !D->getInit()->isTypeDependent() && 202 !D->getInit()->isValueDependent()) { 203 // If neither the declaration's type nor its initializer are dependent, 204 // we don't want to redo all the checking, especially since the 205 // initializer might have been wrapped by a CXXConstructExpr since we did 206 // it the first time. 207 Var->setType(D->getType()); 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 TemplateArgumentListInfo InstTemplateArgs; // no angle locations 1157 for (unsigned I = 0; I != N; ++I) { 1158 TemplateArgumentLoc Loc; 1159 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs)) 1160 return true; 1161 InstTemplateArgs.addArgument(Loc); 1162 } 1163 1164 1165 // Check that the template argument list is well-formed for this 1166 // class template. 1167 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 1168 InstTemplateArgs.size()); 1169 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 1170 PartialSpec->getLocation(), 1171 InstTemplateArgs, 1172 false, 1173 Converted)) 1174 return true; 1175 1176 // Figure out where to insert this class template partial specialization 1177 // in the member template's set of class template partial specializations. 1178 llvm::FoldingSetNodeID ID; 1179 ClassTemplatePartialSpecializationDecl::Profile(ID, 1180 Converted.getFlatArguments(), 1181 Converted.flatSize(), 1182 SemaRef.Context); 1183 void *InsertPos = 0; 1184 ClassTemplateSpecializationDecl *PrevDecl 1185 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 1186 InsertPos); 1187 1188 // Build the canonical type that describes the converted template 1189 // arguments of the class template partial specialization. 1190 QualType CanonType 1191 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1192 Converted.getFlatArguments(), 1193 Converted.flatSize()); 1194 1195 // Build the fully-sugared type for this class template 1196 // specialization as the user wrote in the specialization 1197 // itself. This means that we'll pretty-print the type retrieved 1198 // from the specialization's declaration the way that the user 1199 // actually wrote the specialization, rather than formatting the 1200 // name based on the "canonical" representation used to store the 1201 // template arguments in the specialization. 1202 QualType WrittenTy 1203 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1204 InstTemplateArgs, 1205 CanonType); 1206 1207 if (PrevDecl) { 1208 // We've already seen a partial specialization with the same template 1209 // parameters and template arguments. This can happen, for example, when 1210 // substituting the outer template arguments ends up causing two 1211 // class template partial specializations of a member class template 1212 // to have identical forms, e.g., 1213 // 1214 // template<typename T, typename U> 1215 // struct Outer { 1216 // template<typename X, typename Y> struct Inner; 1217 // template<typename Y> struct Inner<T, Y>; 1218 // template<typename Y> struct Inner<U, Y>; 1219 // }; 1220 // 1221 // Outer<int, int> outer; // error: the partial specializations of Inner 1222 // // have the same signature. 1223 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 1224 << WrittenTy; 1225 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 1226 << SemaRef.Context.getTypeDeclType(PrevDecl); 1227 return true; 1228 } 1229 1230 1231 // Create the class template partial specialization declaration. 1232 ClassTemplatePartialSpecializationDecl *InstPartialSpec 1233 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner, 1234 PartialSpec->getLocation(), 1235 InstParams, 1236 ClassTemplate, 1237 Converted, 1238 InstTemplateArgs, 1239 0); 1240 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 1241 InstPartialSpec->setTypeAsWritten(WrittenTy); 1242 1243 // Add this partial specialization to the set of class template partial 1244 // specializations. 1245 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec, 1246 InsertPos); 1247 return false; 1248} 1249 1250/// \brief Does substitution on the type of the given function, including 1251/// all of the function parameters. 1252/// 1253/// \param D The function whose type will be the basis of the substitution 1254/// 1255/// \param Params the instantiated parameter declarations 1256 1257/// \returns the instantiated function's type if successful, a NULL 1258/// type if there was an error. 1259QualType 1260TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 1261 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 1262 bool InvalidDecl = false; 1263 1264 // Substitute all of the function's formal parameter types. 1265 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs); 1266 llvm::SmallVector<QualType, 4> ParamTys; 1267 for (FunctionDecl::param_iterator P = D->param_begin(), 1268 PEnd = D->param_end(); 1269 P != PEnd; ++P) { 1270 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { 1271 if (PInst->getType()->isVoidType()) { 1272 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); 1273 PInst->setInvalidDecl(); 1274 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), 1275 PInst->getType(), 1276 diag::err_abstract_type_in_decl, 1277 Sema::AbstractParamType)) 1278 PInst->setInvalidDecl(); 1279 1280 Params.push_back(PInst); 1281 ParamTys.push_back(PInst->getType()); 1282 1283 if (PInst->isInvalidDecl()) 1284 InvalidDecl = true; 1285 } else 1286 InvalidDecl = true; 1287 } 1288 1289 // FIXME: Deallocate dead declarations. 1290 if (InvalidDecl) 1291 return QualType(); 1292 1293 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>(); 1294 assert(Proto && "Missing prototype?"); 1295 QualType ResultType 1296 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs, 1297 D->getLocation(), D->getDeclName()); 1298 if (ResultType.isNull()) 1299 return QualType(); 1300 1301 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(), 1302 Proto->isVariadic(), Proto->getTypeQuals(), 1303 D->getLocation(), D->getDeclName()); 1304} 1305 1306/// \brief Initializes the common fields of an instantiation function 1307/// declaration (New) from the corresponding fields of its template (Tmpl). 1308/// 1309/// \returns true if there was an error 1310bool 1311TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 1312 FunctionDecl *Tmpl) { 1313 if (Tmpl->isDeleted()) 1314 New->setDeleted(); 1315 1316 // If we are performing substituting explicitly-specified template arguments 1317 // or deduced template arguments into a function template and we reach this 1318 // point, we are now past the point where SFINAE applies and have committed 1319 // to keeping the new function template specialization. We therefore 1320 // convert the active template instantiation for the function template 1321 // into a template instantiation for this specific function template 1322 // specialization, which is not a SFINAE context, so that we diagnose any 1323 // further errors in the declaration itself. 1324 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 1325 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 1326 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 1327 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 1328 if (FunctionTemplateDecl *FunTmpl 1329 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 1330 assert(FunTmpl->getTemplatedDecl() == Tmpl && 1331 "Deduction from the wrong function template?"); 1332 (void) FunTmpl; 1333 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 1334 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 1335 --SemaRef.NonInstantiationEntries; 1336 } 1337 } 1338 1339 return false; 1340} 1341 1342/// \brief Initializes common fields of an instantiated method 1343/// declaration (New) from the corresponding fields of its template 1344/// (Tmpl). 1345/// 1346/// \returns true if there was an error 1347bool 1348TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 1349 CXXMethodDecl *Tmpl) { 1350 if (InitFunctionInstantiation(New, Tmpl)) 1351 return true; 1352 1353 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 1354 New->setAccess(Tmpl->getAccess()); 1355 if (Tmpl->isVirtualAsWritten()) { 1356 New->setVirtualAsWritten(true); 1357 Record->setAggregate(false); 1358 Record->setPOD(false); 1359 Record->setEmpty(false); 1360 Record->setPolymorphic(true); 1361 } 1362 if (Tmpl->isPure()) { 1363 New->setPure(); 1364 Record->setAbstract(true); 1365 } 1366 1367 // FIXME: attributes 1368 // FIXME: New needs a pointer to Tmpl 1369 return false; 1370} 1371 1372/// \brief Instantiate the definition of the given function from its 1373/// template. 1374/// 1375/// \param PointOfInstantiation the point at which the instantiation was 1376/// required. Note that this is not precisely a "point of instantiation" 1377/// for the function, but it's close. 1378/// 1379/// \param Function the already-instantiated declaration of a 1380/// function template specialization or member function of a class template 1381/// specialization. 1382/// 1383/// \param Recursive if true, recursively instantiates any functions that 1384/// are required by this instantiation. 1385/// 1386/// \param DefinitionRequired if true, then we are performing an explicit 1387/// instantiation where the body of the function is required. Complain if 1388/// there is no such body. 1389void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 1390 FunctionDecl *Function, 1391 bool Recursive, 1392 bool DefinitionRequired) { 1393 if (Function->isInvalidDecl()) 1394 return; 1395 1396 assert(!Function->getBody() && "Already instantiated!"); 1397 1398 // Never instantiate an explicit specialization. 1399 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1400 return; 1401 1402 // Find the function body that we'll be substituting. 1403 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 1404 Stmt *Pattern = 0; 1405 if (PatternDecl) 1406 Pattern = PatternDecl->getBody(PatternDecl); 1407 1408 if (!Pattern) { 1409 if (DefinitionRequired) { 1410 if (Function->getPrimaryTemplate()) 1411 Diag(PointOfInstantiation, 1412 diag::err_explicit_instantiation_undefined_func_template) 1413 << Function->getPrimaryTemplate(); 1414 else 1415 Diag(PointOfInstantiation, 1416 diag::err_explicit_instantiation_undefined_member) 1417 << 1 << Function->getDeclName() << Function->getDeclContext(); 1418 1419 if (PatternDecl) 1420 Diag(PatternDecl->getLocation(), 1421 diag::note_explicit_instantiation_here); 1422 } 1423 1424 return; 1425 } 1426 1427 // C++0x [temp.explicit]p9: 1428 // Except for inline functions, other explicit instantiation declarations 1429 // have the effect of suppressing the implicit instantiation of the entity 1430 // to which they refer. 1431 if (Function->getTemplateSpecializationKind() 1432 == TSK_ExplicitInstantiationDeclaration && 1433 !PatternDecl->isInlined()) 1434 return; 1435 1436 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 1437 if (Inst) 1438 return; 1439 1440 // If we're performing recursive template instantiation, create our own 1441 // queue of pending implicit instantiations that we will instantiate later, 1442 // while we're still within our own instantiation context. 1443 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1444 if (Recursive) 1445 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1446 1447 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 1448 1449 // Introduce a new scope where local variable instantiations will be 1450 // recorded. 1451 LocalInstantiationScope Scope(*this); 1452 1453 // Introduce the instantiated function parameters into the local 1454 // instantiation scope. 1455 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 1456 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 1457 Function->getParamDecl(I)); 1458 1459 // Enter the scope of this instantiation. We don't use 1460 // PushDeclContext because we don't have a scope. 1461 DeclContext *PreviousContext = CurContext; 1462 CurContext = Function; 1463 1464 MultiLevelTemplateArgumentList TemplateArgs = 1465 getTemplateInstantiationArgs(Function); 1466 1467 // If this is a constructor, instantiate the member initializers. 1468 if (const CXXConstructorDecl *Ctor = 1469 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 1470 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 1471 TemplateArgs); 1472 } 1473 1474 // Instantiate the function body. 1475 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs); 1476 1477 if (Body.isInvalid()) 1478 Function->setInvalidDecl(); 1479 1480 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 1481 /*IsInstantiation=*/true); 1482 1483 CurContext = PreviousContext; 1484 1485 DeclGroupRef DG(Function); 1486 Consumer.HandleTopLevelDecl(DG); 1487 1488 if (Recursive) { 1489 // Instantiate any pending implicit instantiations found during the 1490 // instantiation of this template. 1491 PerformPendingImplicitInstantiations(); 1492 1493 // Restore the set of pending implicit instantiations. 1494 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1495 } 1496} 1497 1498/// \brief Instantiate the definition of the given variable from its 1499/// template. 1500/// 1501/// \param PointOfInstantiation the point at which the instantiation was 1502/// required. Note that this is not precisely a "point of instantiation" 1503/// for the function, but it's close. 1504/// 1505/// \param Var the already-instantiated declaration of a static member 1506/// variable of a class template specialization. 1507/// 1508/// \param Recursive if true, recursively instantiates any functions that 1509/// are required by this instantiation. 1510/// 1511/// \param DefinitionRequired if true, then we are performing an explicit 1512/// instantiation where an out-of-line definition of the member variable 1513/// is required. Complain if there is no such definition. 1514void Sema::InstantiateStaticDataMemberDefinition( 1515 SourceLocation PointOfInstantiation, 1516 VarDecl *Var, 1517 bool Recursive, 1518 bool DefinitionRequired) { 1519 if (Var->isInvalidDecl()) 1520 return; 1521 1522 // Find the out-of-line definition of this static data member. 1523 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 1524 assert(Def && "This data member was not instantiated from a template?"); 1525 assert(Def->isStaticDataMember() && "Not a static data member?"); 1526 Def = Def->getOutOfLineDefinition(); 1527 1528 if (!Def) { 1529 // We did not find an out-of-line definition of this static data member, 1530 // so we won't perform any instantiation. Rather, we rely on the user to 1531 // instantiate this definition (or provide a specialization for it) in 1532 // another translation unit. 1533 if (DefinitionRequired) { 1534 Def = Var->getInstantiatedFromStaticDataMember(); 1535 Diag(PointOfInstantiation, 1536 diag::err_explicit_instantiation_undefined_member) 1537 << 2 << Var->getDeclName() << Var->getDeclContext(); 1538 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 1539 } 1540 1541 return; 1542 } 1543 1544 // Never instantiate an explicit specialization. 1545 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1546 return; 1547 1548 // C++0x [temp.explicit]p9: 1549 // Except for inline functions, other explicit instantiation declarations 1550 // have the effect of suppressing the implicit instantiation of the entity 1551 // to which they refer. 1552 if (Var->getTemplateSpecializationKind() 1553 == TSK_ExplicitInstantiationDeclaration) 1554 return; 1555 1556 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 1557 if (Inst) 1558 return; 1559 1560 // If we're performing recursive template instantiation, create our own 1561 // queue of pending implicit instantiations that we will instantiate later, 1562 // while we're still within our own instantiation context. 1563 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1564 if (Recursive) 1565 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1566 1567 // Enter the scope of this instantiation. We don't use 1568 // PushDeclContext because we don't have a scope. 1569 DeclContext *PreviousContext = CurContext; 1570 CurContext = Var->getDeclContext(); 1571 1572 VarDecl *OldVar = Var; 1573 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 1574 getTemplateInstantiationArgs(Var))); 1575 CurContext = PreviousContext; 1576 1577 if (Var) { 1578 Var->setPreviousDeclaration(OldVar); 1579 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 1580 assert(MSInfo && "Missing member specialization information?"); 1581 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 1582 MSInfo->getPointOfInstantiation()); 1583 DeclGroupRef DG(Var); 1584 Consumer.HandleTopLevelDecl(DG); 1585 } 1586 1587 if (Recursive) { 1588 // Instantiate any pending implicit instantiations found during the 1589 // instantiation of this template. 1590 PerformPendingImplicitInstantiations(); 1591 1592 // Restore the set of pending implicit instantiations. 1593 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1594 } 1595} 1596 1597void 1598Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 1599 const CXXConstructorDecl *Tmpl, 1600 const MultiLevelTemplateArgumentList &TemplateArgs) { 1601 1602 llvm::SmallVector<MemInitTy*, 4> NewInits; 1603 1604 // Instantiate all the initializers. 1605 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 1606 InitsEnd = Tmpl->init_end(); 1607 Inits != InitsEnd; ++Inits) { 1608 CXXBaseOrMemberInitializer *Init = *Inits; 1609 1610 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this); 1611 1612 // Instantiate all the arguments. 1613 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end(); 1614 Args != ArgsEnd; ++Args) { 1615 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs); 1616 1617 if (NewArg.isInvalid()) 1618 New->setInvalidDecl(); 1619 else 1620 NewArgs.push_back(NewArg.takeAs<Expr>()); 1621 } 1622 1623 MemInitResult NewInit; 1624 1625 if (Init->isBaseInitializer()) { 1626 QualType BaseType(Init->getBaseClass(), 0); 1627 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(), 1628 New->getDeclName()); 1629 1630 NewInit = BuildBaseInitializer(BaseType, 1631 (Expr **)NewArgs.data(), 1632 NewArgs.size(), 1633 Init->getSourceLocation(), 1634 Init->getRParenLoc(), 1635 New->getParent()); 1636 } else if (Init->isMemberInitializer()) { 1637 FieldDecl *Member; 1638 1639 // Is this an anonymous union? 1640 if (FieldDecl *UnionInit = Init->getAnonUnionMember()) 1641 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs)); 1642 else 1643 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(), 1644 TemplateArgs)); 1645 1646 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 1647 NewArgs.size(), 1648 Init->getSourceLocation(), 1649 Init->getRParenLoc()); 1650 } 1651 1652 if (NewInit.isInvalid()) 1653 New->setInvalidDecl(); 1654 else { 1655 // FIXME: It would be nice if ASTOwningVector had a release function. 1656 NewArgs.take(); 1657 1658 NewInits.push_back((MemInitTy *)NewInit.get()); 1659 } 1660 } 1661 1662 // Assign all the initializers to the new constructor. 1663 ActOnMemInitializers(DeclPtrTy::make(New), 1664 /*FIXME: ColonLoc */ 1665 SourceLocation(), 1666 NewInits.data(), NewInits.size()); 1667} 1668 1669// TODO: this could be templated if the various decl types used the 1670// same method name. 1671static bool isInstantiationOf(ClassTemplateDecl *Pattern, 1672 ClassTemplateDecl *Instance) { 1673 Pattern = Pattern->getCanonicalDecl(); 1674 1675 do { 1676 Instance = Instance->getCanonicalDecl(); 1677 if (Pattern == Instance) return true; 1678 Instance = Instance->getInstantiatedFromMemberTemplate(); 1679 } while (Instance); 1680 1681 return false; 1682} 1683 1684static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 1685 FunctionTemplateDecl *Instance) { 1686 Pattern = Pattern->getCanonicalDecl(); 1687 1688 do { 1689 Instance = Instance->getCanonicalDecl(); 1690 if (Pattern == Instance) return true; 1691 Instance = Instance->getInstantiatedFromMemberTemplate(); 1692 } while (Instance); 1693 1694 return false; 1695} 1696 1697static bool 1698isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 1699 ClassTemplatePartialSpecializationDecl *Instance) { 1700 Pattern 1701 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 1702 do { 1703 Instance = cast<ClassTemplatePartialSpecializationDecl>( 1704 Instance->getCanonicalDecl()); 1705 if (Pattern == Instance) 1706 return true; 1707 Instance = Instance->getInstantiatedFromMember(); 1708 } while (Instance); 1709 1710 return false; 1711} 1712 1713static bool isInstantiationOf(CXXRecordDecl *Pattern, 1714 CXXRecordDecl *Instance) { 1715 Pattern = Pattern->getCanonicalDecl(); 1716 1717 do { 1718 Instance = Instance->getCanonicalDecl(); 1719 if (Pattern == Instance) return true; 1720 Instance = Instance->getInstantiatedFromMemberClass(); 1721 } while (Instance); 1722 1723 return false; 1724} 1725 1726static bool isInstantiationOf(FunctionDecl *Pattern, 1727 FunctionDecl *Instance) { 1728 Pattern = Pattern->getCanonicalDecl(); 1729 1730 do { 1731 Instance = Instance->getCanonicalDecl(); 1732 if (Pattern == Instance) return true; 1733 Instance = Instance->getInstantiatedFromMemberFunction(); 1734 } while (Instance); 1735 1736 return false; 1737} 1738 1739static bool isInstantiationOf(EnumDecl *Pattern, 1740 EnumDecl *Instance) { 1741 Pattern = Pattern->getCanonicalDecl(); 1742 1743 do { 1744 Instance = Instance->getCanonicalDecl(); 1745 if (Pattern == Instance) return true; 1746 Instance = Instance->getInstantiatedFromMemberEnum(); 1747 } while (Instance); 1748 1749 return false; 1750} 1751 1752static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 1753 UsingDecl *Instance, 1754 ASTContext &C) { 1755 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern; 1756} 1757 1758static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 1759 UsingDecl *Instance, 1760 ASTContext &C) { 1761 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern; 1762} 1763 1764static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 1765 VarDecl *Instance) { 1766 assert(Instance->isStaticDataMember()); 1767 1768 Pattern = Pattern->getCanonicalDecl(); 1769 1770 do { 1771 Instance = Instance->getCanonicalDecl(); 1772 if (Pattern == Instance) return true; 1773 Instance = Instance->getInstantiatedFromStaticDataMember(); 1774 } while (Instance); 1775 1776 return false; 1777} 1778 1779static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 1780 if (D->getKind() != Other->getKind()) { 1781 if (UnresolvedUsingTypenameDecl *UUD 1782 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 1783 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 1784 return isInstantiationOf(UUD, UD, Ctx); 1785 } 1786 } 1787 1788 if (UnresolvedUsingValueDecl *UUD 1789 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 1790 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 1791 return isInstantiationOf(UUD, UD, Ctx); 1792 } 1793 } 1794 1795 return false; 1796 } 1797 1798 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 1799 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 1800 1801 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 1802 return isInstantiationOf(cast<FunctionDecl>(D), Function); 1803 1804 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 1805 return isInstantiationOf(cast<EnumDecl>(D), Enum); 1806 1807 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 1808 if (Var->isStaticDataMember()) 1809 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 1810 1811 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 1812 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 1813 1814 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 1815 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 1816 1817 if (ClassTemplatePartialSpecializationDecl *PartialSpec 1818 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 1819 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 1820 PartialSpec); 1821 1822 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 1823 if (!Field->getDeclName()) { 1824 // This is an unnamed field. 1825 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 1826 cast<FieldDecl>(D); 1827 } 1828 } 1829 1830 return D->getDeclName() && isa<NamedDecl>(Other) && 1831 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 1832} 1833 1834template<typename ForwardIterator> 1835static NamedDecl *findInstantiationOf(ASTContext &Ctx, 1836 NamedDecl *D, 1837 ForwardIterator first, 1838 ForwardIterator last) { 1839 for (; first != last; ++first) 1840 if (isInstantiationOf(Ctx, D, *first)) 1841 return cast<NamedDecl>(*first); 1842 1843 return 0; 1844} 1845 1846/// \brief Finds the instantiation of the given declaration context 1847/// within the current instantiation. 1848/// 1849/// \returns NULL if there was an error 1850DeclContext *Sema::FindInstantiatedContext(DeclContext* DC, 1851 const MultiLevelTemplateArgumentList &TemplateArgs) { 1852 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 1853 Decl* ID = FindInstantiatedDecl(D, TemplateArgs); 1854 return cast_or_null<DeclContext>(ID); 1855 } else return DC; 1856} 1857 1858/// \brief Find the instantiation of the given declaration within the 1859/// current instantiation. 1860/// 1861/// This routine is intended to be used when \p D is a declaration 1862/// referenced from within a template, that needs to mapped into the 1863/// corresponding declaration within an instantiation. For example, 1864/// given: 1865/// 1866/// \code 1867/// template<typename T> 1868/// struct X { 1869/// enum Kind { 1870/// KnownValue = sizeof(T) 1871/// }; 1872/// 1873/// bool getKind() const { return KnownValue; } 1874/// }; 1875/// 1876/// template struct X<int>; 1877/// \endcode 1878/// 1879/// In the instantiation of X<int>::getKind(), we need to map the 1880/// EnumConstantDecl for KnownValue (which refers to 1881/// X<T>::<Kind>::KnownValue) to its instantiation 1882/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 1883/// this mapping from within the instantiation of X<int>. 1884NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D, 1885 const MultiLevelTemplateArgumentList &TemplateArgs) { 1886 DeclContext *ParentDC = D->getDeclContext(); 1887 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 1888 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 1889 ParentDC->isFunctionOrMethod()) { 1890 // D is a local of some kind. Look into the map of local 1891 // declarations to their instantiations. 1892 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 1893 } 1894 1895 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 1896 if (!Record->isDependentContext()) 1897 return D; 1898 1899 // If the RecordDecl is actually the injected-class-name or a "templated" 1900 // declaration for a class template or class template partial 1901 // specialization, substitute into the injected-class-name of the 1902 // class template or partial specialization to find the new DeclContext. 1903 QualType T; 1904 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 1905 1906 if (ClassTemplate) { 1907 T = ClassTemplate->getInjectedClassNameType(Context); 1908 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 1909 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 1910 T = Context.getTypeDeclType(Record); 1911 ClassTemplate = PartialSpec->getSpecializedTemplate(); 1912 } 1913 1914 if (!T.isNull()) { 1915 // Substitute into the injected-class-name to get the type corresponding 1916 // to the instantiation we want. This substitution should never fail, 1917 // since we know we can instantiate the injected-class-name or we wouldn't 1918 // have gotten to the injected-class-name! 1919 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra 1920 // instantiation in the common case? 1921 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName()); 1922 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail."); 1923 1924 if (!T->isDependentType()) { 1925 assert(T->isRecordType() && "Instantiation must produce a record type"); 1926 return T->getAs<RecordType>()->getDecl(); 1927 } 1928 1929 // We are performing "partial" template instantiation to create the 1930 // member declarations for the members of a class template 1931 // specialization. Therefore, D is actually referring to something in 1932 // the current instantiation. Look through the current context, 1933 // which contains actual instantiations, to find the instantiation of 1934 // the "current instantiation" that D refers to. 1935 for (DeclContext *DC = CurContext; !DC->isFileContext(); 1936 DC = DC->getParent()) { 1937 if (ClassTemplateSpecializationDecl *Spec 1938 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 1939 if (isInstantiationOf(ClassTemplate, 1940 Spec->getSpecializedTemplate())) 1941 return Spec; 1942 } 1943 1944 assert(false && 1945 "Unable to find declaration for the current instantiation"); 1946 return Record; 1947 } 1948 1949 // Fall through to deal with other dependent record types (e.g., 1950 // anonymous unions in class templates). 1951 } 1952 1953 if (!ParentDC->isDependentContext()) 1954 return D; 1955 1956 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs); 1957 if (!ParentDC) 1958 return 0; 1959 1960 if (ParentDC != D->getDeclContext()) { 1961 // We performed some kind of instantiation in the parent context, 1962 // so now we need to look into the instantiated parent context to 1963 // find the instantiation of the declaration D. 1964 NamedDecl *Result = 0; 1965 if (D->getDeclName()) { 1966 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 1967 Result = findInstantiationOf(Context, D, Found.first, Found.second); 1968 } else { 1969 // Since we don't have a name for the entity we're looking for, 1970 // our only option is to walk through all of the declarations to 1971 // find that name. This will occur in a few cases: 1972 // 1973 // - anonymous struct/union within a template 1974 // - unnamed class/struct/union/enum within a template 1975 // 1976 // FIXME: Find a better way to find these instantiations! 1977 Result = findInstantiationOf(Context, D, 1978 ParentDC->decls_begin(), 1979 ParentDC->decls_end()); 1980 } 1981 1982 assert(Result && "Unable to find instantiation of declaration!"); 1983 D = Result; 1984 } 1985 1986 return D; 1987} 1988 1989/// \brief Performs template instantiation for all implicit template 1990/// instantiations we have seen until this point. 1991void Sema::PerformPendingImplicitInstantiations() { 1992 while (!PendingImplicitInstantiations.empty()) { 1993 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front(); 1994 PendingImplicitInstantiations.pop_front(); 1995 1996 // Instantiate function definitions 1997 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 1998 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function), 1999 Function->getLocation(), *this, 2000 Context.getSourceManager(), 2001 "instantiating function definition"); 2002 2003 if (!Function->getBody()) 2004 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 2005 continue; 2006 } 2007 2008 // Instantiate static data member definitions. 2009 VarDecl *Var = cast<VarDecl>(Inst.first); 2010 assert(Var->isStaticDataMember() && "Not a static data member?"); 2011 2012 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var), 2013 Var->getLocation(), *this, 2014 Context.getSourceManager(), 2015 "instantiating static data member " 2016 "definition"); 2017 2018 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 2019 } 2020} 2021