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