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