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