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