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