SemaTemplateInstantiateDecl.cpp revision 8dbc3c64965f99e48830885835b7d2fc26ec3cf5
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 *VisitCXXRecordDecl(CXXRecordDecl *D); 48 Decl *VisitCXXMethodDecl(CXXMethodDecl *D); 49 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 50 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 51 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 52 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 53 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D); 54 55 // Base case. FIXME: Remove once we can instantiate everything. 56 Decl *VisitDecl(Decl *) { 57 assert(false && "Template instantiation of unknown declaration kind!"); 58 return 0; 59 } 60 61 // Helper functions for instantiating methods. 62 QualType InstantiateFunctionType(FunctionDecl *D, 63 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 64 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 65 }; 66} 67 68Decl * 69TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 70 assert(false && "Translation units cannot be instantiated"); 71 return D; 72} 73 74Decl * 75TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 76 assert(false && "Namespaces cannot be instantiated"); 77 return D; 78} 79 80Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 81 bool Invalid = false; 82 QualType T = D->getUnderlyingType(); 83 if (T->isDependentType()) { 84 T = SemaRef.InstantiateType(T, TemplateArgs, 85 D->getLocation(), D->getDeclName()); 86 if (T.isNull()) { 87 Invalid = true; 88 T = SemaRef.Context.IntTy; 89 } 90 } 91 92 // Create the new typedef 93 TypedefDecl *Typedef 94 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 95 D->getIdentifier(), T); 96 if (Invalid) 97 Typedef->setInvalidDecl(); 98 99 Owner->addDecl(SemaRef.Context, Typedef); 100 return Typedef; 101} 102 103Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 104 // Instantiate the type of the declaration 105 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs, 106 D->getTypeSpecStartLoc(), 107 D->getDeclName()); 108 if (T.isNull()) 109 return 0; 110 111 // Build the instantiated declaration 112 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 113 D->getLocation(), D->getIdentifier(), 114 T, D->getStorageClass(), 115 D->getTypeSpecStartLoc()); 116 Var->setThreadSpecified(D->isThreadSpecified()); 117 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 118 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 119 120 // FIXME: In theory, we could have a previous declaration for variables that 121 // are not static data members. 122 bool Redeclaration = false; 123 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration); 124 Owner->addDecl(SemaRef.Context, Var); 125 126 if (D->getInit()) { 127 OwningExprResult Init 128 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs); 129 if (Init.isInvalid()) 130 Var->setInvalidDecl(); 131 else 132 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init), 133 D->hasCXXDirectInitializer()); 134 } else { 135 // FIXME: Call ActOnUninitializedDecl? (Not always) 136 } 137 138 return Var; 139} 140 141Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 142 bool Invalid = false; 143 QualType T = D->getType(); 144 if (T->isDependentType()) { 145 T = SemaRef.InstantiateType(T, TemplateArgs, 146 D->getLocation(), D->getDeclName()); 147 if (!T.isNull() && T->isFunctionType()) { 148 // C++ [temp.arg.type]p3: 149 // If a declaration acquires a function type through a type 150 // dependent on a template-parameter and this causes a 151 // declaration that does not use the syntactic form of a 152 // function declarator to have function type, the program is 153 // ill-formed. 154 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 155 << T; 156 T = QualType(); 157 Invalid = true; 158 } 159 } 160 161 Expr *BitWidth = D->getBitWidth(); 162 if (Invalid) 163 BitWidth = 0; 164 else if (BitWidth) { 165 OwningExprResult InstantiatedBitWidth 166 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs); 167 if (InstantiatedBitWidth.isInvalid()) { 168 Invalid = true; 169 BitWidth = 0; 170 } else 171 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 172 } 173 174 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T, 175 cast<RecordDecl>(Owner), 176 D->getLocation(), 177 D->isMutable(), 178 BitWidth, 179 D->getAccess(), 180 0); 181 if (Field) { 182 if (Invalid) 183 Field->setInvalidDecl(); 184 185 Owner->addDecl(SemaRef.Context, Field); 186 } 187 188 return Field; 189} 190 191Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 192 Expr *AssertExpr = D->getAssertExpr(); 193 194 OwningExprResult InstantiatedAssertExpr 195 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs); 196 if (InstantiatedAssertExpr.isInvalid()) 197 return 0; 198 199 OwningExprResult Message = SemaRef.Clone(D->getMessage()); 200 Decl *StaticAssert 201 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 202 move(InstantiatedAssertExpr), 203 move(Message)).getAs<Decl>(); 204 return StaticAssert; 205} 206 207Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 208 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 209 D->getLocation(), D->getIdentifier(), 210 /*PrevDecl=*/0); 211 Enum->setInstantiationOfMemberEnum(D); 212 Enum->setAccess(D->getAccess()); 213 Owner->addDecl(SemaRef.Context, Enum); 214 Enum->startDefinition(); 215 216 llvm::SmallVector<Sema::DeclPtrTy, 16> Enumerators; 217 218 EnumConstantDecl *LastEnumConst = 0; 219 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(SemaRef.Context), 220 ECEnd = D->enumerator_end(SemaRef.Context); 221 EC != ECEnd; ++EC) { 222 // The specified value for the enumerator. 223 OwningExprResult Value = SemaRef.Owned((Expr *)0); 224 if (Expr *UninstValue = EC->getInitExpr()) 225 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs); 226 227 // Drop the initial value and continue. 228 bool isInvalid = false; 229 if (Value.isInvalid()) { 230 Value = SemaRef.Owned((Expr *)0); 231 isInvalid = true; 232 } 233 234 EnumConstantDecl *EnumConst 235 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 236 EC->getLocation(), EC->getIdentifier(), 237 move(Value)); 238 239 if (isInvalid) { 240 if (EnumConst) 241 EnumConst->setInvalidDecl(); 242 Enum->setInvalidDecl(); 243 } 244 245 if (EnumConst) { 246 Enum->addDecl(SemaRef.Context, EnumConst); 247 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 248 LastEnumConst = EnumConst; 249 } 250 } 251 252 // FIXME: Fixup LBraceLoc and RBraceLoc 253 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 254 Sema::DeclPtrTy::make(Enum), 255 &Enumerators[0], Enumerators.size()); 256 257 return Enum; 258} 259 260Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 261 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 262 return 0; 263} 264 265Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 266 CXXRecordDecl *PrevDecl = 0; 267 if (D->isInjectedClassName()) 268 PrevDecl = cast<CXXRecordDecl>(Owner); 269 270 CXXRecordDecl *Record 271 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 272 D->getLocation(), D->getIdentifier(), PrevDecl); 273 Record->setImplicit(D->isImplicit()); 274 Record->setAccess(D->getAccess()); 275 if (!D->isInjectedClassName()) 276 Record->setInstantiationOfMemberClass(D); 277 278 Owner->addDecl(SemaRef.Context, Record); 279 return Record; 280} 281 282Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 283 // Only handle actual methods; we'll deal with constructors, 284 // destructors, etc. separately. 285 if (D->getKind() != Decl::CXXMethod) 286 return 0; 287 288 Sema::LocalInstantiationScope Scope(SemaRef); 289 290 llvm::SmallVector<ParmVarDecl *, 16> Params; 291 QualType T = InstantiateFunctionType(D, Params); 292 if (T.isNull()) 293 return 0; 294 295 // Build the instantiated method declaration. 296 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 297 CXXMethodDecl *Method 298 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 299 D->getDeclName(), T, D->isStatic(), 300 D->isInline()); 301 Method->setInstantiationOfMemberFunction(D); 302 303 // Attach the parameters 304 for (unsigned P = 0; P < Params.size(); ++P) 305 Params[P]->setOwningFunction(Method); 306 Method->setParams(SemaRef.Context, Params.data(), Params.size()); 307 308 if (InitMethodInstantiation(Method, D)) 309 Method->setInvalidDecl(); 310 311 NamedDecl *PrevDecl 312 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(), 313 Sema::LookupOrdinaryName, true); 314 // In C++, the previous declaration we find might be a tag type 315 // (class or enum). In this case, the new declaration will hide the 316 // tag type. Note that this does does not apply if we're declaring a 317 // typedef (C++ [dcl.typedef]p4). 318 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 319 PrevDecl = 0; 320 bool Redeclaration = false; 321 bool OverloadableAttrRequired = false; 322 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration, 323 /*FIXME:*/OverloadableAttrRequired); 324 325 if (!Method->isInvalidDecl() || !PrevDecl) 326 Owner->addDecl(SemaRef.Context, Method); 327 return Method; 328} 329 330Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 331 Sema::LocalInstantiationScope Scope(SemaRef); 332 333 llvm::SmallVector<ParmVarDecl *, 16> Params; 334 QualType T = InstantiateFunctionType(D, Params); 335 if (T.isNull()) 336 return 0; 337 338 // Build the instantiated method declaration. 339 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 340 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 341 DeclarationName Name 342 = SemaRef.Context.DeclarationNames.getCXXConstructorName( 343 SemaRef.Context.getCanonicalType(ClassTy)); 344 CXXConstructorDecl *Constructor 345 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(), 346 Name, T, D->isExplicit(), D->isInline(), 347 false); 348 Constructor->setInstantiationOfMemberFunction(D); 349 350 // Attach the parameters 351 for (unsigned P = 0; P < Params.size(); ++P) 352 Params[P]->setOwningFunction(Constructor); 353 Constructor->setParams(SemaRef.Context, Params.data(), Params.size()); 354 355 if (InitMethodInstantiation(Constructor, D)) 356 Constructor->setInvalidDecl(); 357 358 NamedDecl *PrevDecl 359 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true); 360 361 // In C++, the previous declaration we find might be a tag type 362 // (class or enum). In this case, the new declaration will hide the 363 // tag type. Note that this does does not apply if we're declaring a 364 // typedef (C++ [dcl.typedef]p4). 365 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 366 PrevDecl = 0; 367 bool Redeclaration = false; 368 bool OverloadableAttrRequired = false; 369 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration, 370 /*FIXME:*/OverloadableAttrRequired); 371 372 Record->addedConstructor(SemaRef.Context, Constructor); 373 Owner->addDecl(SemaRef.Context, Constructor); 374 return Constructor; 375} 376 377Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 378 Sema::LocalInstantiationScope Scope(SemaRef); 379 380 llvm::SmallVector<ParmVarDecl *, 16> Params; 381 QualType T = InstantiateFunctionType(D, Params); 382 if (T.isNull()) 383 return 0; 384 assert(Params.size() == 0 && "Destructor with parameters?"); 385 386 // Build the instantiated destructor declaration. 387 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 388 QualType ClassTy = 389 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record)); 390 CXXDestructorDecl *Destructor 391 = CXXDestructorDecl::Create(SemaRef.Context, Record, 392 D->getLocation(), 393 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy), 394 T, D->isInline(), false); 395 Destructor->setInstantiationOfMemberFunction(D); 396 if (InitMethodInstantiation(Destructor, D)) 397 Destructor->setInvalidDecl(); 398 399 bool Redeclaration = false; 400 bool OverloadableAttrRequired = false; 401 NamedDecl *PrevDecl = 0; 402 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration, 403 /*FIXME:*/OverloadableAttrRequired); 404 Owner->addDecl(SemaRef.Context, Destructor); 405 return Destructor; 406} 407 408Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 409 Sema::LocalInstantiationScope Scope(SemaRef); 410 411 llvm::SmallVector<ParmVarDecl *, 16> Params; 412 QualType T = InstantiateFunctionType(D, Params); 413 if (T.isNull()) 414 return 0; 415 assert(Params.size() == 0 && "Destructor with parameters?"); 416 417 // Build the instantiated conversion declaration. 418 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 419 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 420 QualType ConvTy 421 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType()); 422 CXXConversionDecl *Conversion 423 = CXXConversionDecl::Create(SemaRef.Context, Record, 424 D->getLocation(), 425 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy), 426 T, D->isInline(), D->isExplicit()); 427 Conversion->setInstantiationOfMemberFunction(D); 428 if (InitMethodInstantiation(Conversion, D)) 429 Conversion->setInvalidDecl(); 430 431 bool Redeclaration = false; 432 bool OverloadableAttrRequired = false; 433 NamedDecl *PrevDecl = 0; 434 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration, 435 /*FIXME:*/OverloadableAttrRequired); 436 Owner->addDecl(SemaRef.Context, Conversion); 437 return Conversion; 438} 439 440ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 441 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs, 442 D->getLocation(), D->getDeclName()); 443 if (OrigT.isNull()) 444 return 0; 445 446 QualType T = SemaRef.adjustParameterType(OrigT); 447 448 if (D->getDefaultArg()) { 449 // FIXME: Leave a marker for "uninstantiated" default 450 // arguments. They only get instantiated on demand at the call 451 // site. 452 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning, 453 "sorry, dropping default argument during template instantiation"); 454 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID) 455 << D->getDefaultArg()->getSourceRange(); 456 } 457 458 // Allocate the parameter 459 ParmVarDecl *Param = 0; 460 if (T == OrigT) 461 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(), 462 D->getIdentifier(), T, D->getStorageClass(), 463 0); 464 else 465 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner, 466 D->getLocation(), D->getIdentifier(), 467 T, OrigT, D->getStorageClass(), 0); 468 469 // Note: we don't try to instantiate function parameters until after 470 // we've instantiated the function's type. Therefore, we don't have 471 // to check for 'void' parameter types here. 472 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 473 return Param; 474} 475 476Decl * 477TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) { 478 // Since parameter types can decay either before or after 479 // instantiation, we simply treat OriginalParmVarDecls as 480 // ParmVarDecls the same way, and create one or the other depending 481 // on what happens after template instantiation. 482 return VisitParmVarDecl(D); 483} 484 485Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner, 486 const TemplateArgumentList &TemplateArgs) { 487 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 488 return Instantiator.Visit(D); 489} 490 491/// \brief Instantiates the type of the given function, including 492/// instantiating all of the function parameters. 493/// 494/// \param D The function that we will be instantiated 495/// 496/// \param Params the instantiated parameter declarations 497 498/// \returns the instantiated function's type if successfull, a NULL 499/// type if there was an error. 500QualType 501TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D, 502 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 503 bool InvalidDecl = false; 504 505 // Instantiate the function parameters 506 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs); 507 llvm::SmallVector<QualType, 16> ParamTys; 508 for (FunctionDecl::param_iterator P = D->param_begin(), 509 PEnd = D->param_end(); 510 P != PEnd; ++P) { 511 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { 512 if (PInst->getType()->isVoidType()) { 513 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); 514 PInst->setInvalidDecl(); 515 } 516 else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), 517 PInst->getType(), 518 diag::err_abstract_type_in_decl, 519 Sema::AbstractParamType)) 520 PInst->setInvalidDecl(); 521 522 Params.push_back(PInst); 523 ParamTys.push_back(PInst->getType()); 524 525 if (PInst->isInvalidDecl()) 526 InvalidDecl = true; 527 } else 528 InvalidDecl = true; 529 } 530 531 // FIXME: Deallocate dead declarations. 532 if (InvalidDecl) 533 return QualType(); 534 535 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType(); 536 assert(Proto && "Missing prototype?"); 537 QualType ResultType 538 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs, 539 D->getLocation(), D->getDeclName()); 540 if (ResultType.isNull()) 541 return QualType(); 542 543 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(), 544 Proto->isVariadic(), Proto->getTypeQuals(), 545 D->getLocation(), D->getDeclName()); 546} 547 548/// \brief Initializes common fields of an instantiated method 549/// declaration (New) from the corresponding fields of its template 550/// (Tmpl). 551/// 552/// \returns true if there was an error 553bool 554TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 555 CXXMethodDecl *Tmpl) { 556 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 557 New->setAccess(Tmpl->getAccess()); 558 if (Tmpl->isVirtualAsWritten()) { 559 New->setVirtualAsWritten(true); 560 Record->setAggregate(false); 561 Record->setPOD(false); 562 Record->setPolymorphic(true); 563 } 564 if (Tmpl->isDeleted()) 565 New->setDeleted(); 566 if (Tmpl->isPure()) { 567 New->setPure(); 568 Record->setAbstract(true); 569 } 570 571 // FIXME: attributes 572 // FIXME: New needs a pointer to Tmpl 573 return false; 574} 575 576/// \brief Instantiate the definition of the given function from its 577/// template. 578/// 579/// \param Function the already-instantiated declaration of a 580/// function. 581void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 582 FunctionDecl *Function) { 583 // FIXME: make this work for function template specializations, too. 584 585 if (Function->isInvalidDecl()) 586 return; 587 588 // Find the function body that we'll be substituting. 589 const FunctionDecl *PatternDecl 590 = Function->getInstantiatedFromMemberFunction(); 591 Stmt *Pattern = 0; 592 if (PatternDecl) 593 Pattern = PatternDecl->getBody(Context, PatternDecl); 594 595 if (!Pattern) 596 return; 597 598 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 599 if (Inst) 600 return; 601 602 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 603 604 // Introduce a new scope where local variable instantiations will be 605 // recorded. 606 LocalInstantiationScope Scope(*this); 607 608 // Introduce the instantiated function parameters into the local 609 // instantiation scope. 610 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 611 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 612 Function->getParamDecl(I)); 613 614 // Enter the scope of this instantiation. We don't use 615 // PushDeclContext because we don't have a scope. 616 DeclContext *PreviousContext = CurContext; 617 CurContext = Function; 618 619 // Instantiate the function body. 620 OwningStmtResult Body 621 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function)); 622 623 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 624 /*IsInstantiation=*/true); 625 626 CurContext = PreviousContext; 627 628 DeclGroupRef DG(Function); 629 Consumer.HandleTopLevelDecl(DG); 630} 631 632/// \brief Instantiate the definition of the given variable from its 633/// template. 634/// 635/// \param Var the already-instantiated declaration of a variable. 636void Sema::InstantiateVariableDefinition(VarDecl *Var) { 637 // FIXME: Implement this! 638} 639 640static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 641 if (D->getKind() != Other->getKind()) 642 return false; 643 644 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 645 return Ctx.getCanonicalDecl(Record->getInstantiatedFromMemberClass()) 646 == Ctx.getCanonicalDecl(D); 647 648 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 649 return Ctx.getCanonicalDecl(Function->getInstantiatedFromMemberFunction()) 650 == Ctx.getCanonicalDecl(D); 651 652 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 653 return Ctx.getCanonicalDecl(Enum->getInstantiatedFromMemberEnum()) 654 == Ctx.getCanonicalDecl(D); 655 656 // FIXME: How can we find instantiations of anonymous unions? 657 658 return D->getDeclName() && isa<NamedDecl>(Other) && 659 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 660} 661 662template<typename ForwardIterator> 663static NamedDecl *findInstantiationOf(ASTContext &Ctx, 664 NamedDecl *D, 665 ForwardIterator first, 666 ForwardIterator last) { 667 for (; first != last; ++first) 668 if (isInstantiationOf(Ctx, D, *first)) 669 return cast<NamedDecl>(*first); 670 671 return 0; 672} 673 674/// \brief Find the instantiation of the given declaration with the 675/// given template arguments. 676/// 677/// This routine is intended to be used when \p D is a declaration 678/// referenced from within a template, that needs to mapped into the 679/// corresponding declaration within an instantiation. For example, 680/// given: 681/// 682/// \code 683/// template<typename T> 684/// struct X { 685/// enum Kind { 686/// KnownValue = sizeof(T) 687/// }; 688/// 689/// bool getKind() const { return KnownValue; } 690/// }; 691/// 692/// template struct X<int>; 693/// \endcode 694/// 695/// In the instantiation of X<int>::getKind(), we need to map the 696/// EnumConstantDecl for KnownValue (which refers to 697/// X<T>::<Kind>::KnownValue) to its instantiation 698/// (X<int>::<Kind>::KnownValue). InstantiateDeclRef() performs this 699/// mapping, given the template arguments 'int'. 700NamedDecl * 701Sema::InstantiateDeclRef(NamedDecl *D, const TemplateArgumentList &TemplateArgs) { 702 DeclContext *ParentDC = D->getDeclContext(); 703 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) { 704 // D is a local of some kind. Look into the map of local 705 // declarations to their instantiations. 706 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 707 } 708 709 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) { 710 ParentDecl = InstantiateDeclRef(ParentDecl, TemplateArgs); 711 if (!ParentDecl) 712 return 0; 713 714 ParentDC = cast<DeclContext>(ParentDecl); 715 } 716 717 if (ParentDC != D->getDeclContext()) { 718 // We performed some kind of instantiation in the parent context, 719 // so now we need to look into the instantiated parent context to 720 // find the instantiation of the declaration D. 721 NamedDecl *Result = 0; 722 if (D->getDeclName()) { 723 DeclContext::lookup_result Found 724 = ParentDC->lookup(Context, D->getDeclName()); 725 Result = findInstantiationOf(Context, D, Found.first, Found.second); 726 } else { 727 // Since we don't have a name for the entity we're looking for, 728 // our only option is to walk through all of the declarations to 729 // find that name. This will occur in a few cases: 730 // 731 // - anonymous struct/union within a template 732 // - unnamed class/struct/union/enum within a template 733 // 734 // FIXME: Find a better way to find these instantiations! 735 Result = findInstantiationOf(Context, D, 736 ParentDC->decls_begin(Context), 737 ParentDC->decls_end(Context)); 738 } 739 assert(Result && "Unable to find instantiation of declaration!"); 740 D = Result; 741 } 742 743 // D itself might be a class template that we need to instantiate 744 // with the given template arguments. 745 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 746 if (ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate()) { 747 QualType InjectedClassName 748 = ClassTemplate->getInjectedClassNameType(Context); 749 QualType InstantiatedType = InstantiateType(InjectedClassName, 750 TemplateArgs, 751 Record->getLocation(), 752 Record->getDeclName()); 753 if (InstantiatedType.isNull()) 754 return 0; 755 if (const RecordType *RT = InstantiatedType->getAsRecordType()) 756 D = RT->getDecl(); 757 } 758 759 return D; 760} 761