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