SemaTemplateInstantiateDecl.cpp revision e3129df6079a8e0028250d71a10b71dcf728d78a
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 "Lookup.h" 14#include "clang/AST/ASTConsumer.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/DeclTemplate.h" 17#include "clang/AST/DeclVisitor.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/Basic/PrettyStackTrace.h" 21#include "clang/Lex/Preprocessor.h" 22 23using namespace clang; 24 25namespace { 26 class TemplateDeclInstantiator 27 : public DeclVisitor<TemplateDeclInstantiator, Decl *> { 28 Sema &SemaRef; 29 DeclContext *Owner; 30 const MultiLevelTemplateArgumentList &TemplateArgs; 31 32 void InstantiateAttrs(Decl *Tmpl, Decl *New); 33 34 public: 35 typedef Sema::OwningExprResult OwningExprResult; 36 37 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, 38 const MultiLevelTemplateArgumentList &TemplateArgs) 39 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { } 40 41 // FIXME: Once we get closer to completion, replace these manually-written 42 // declarations with automatically-generated ones from 43 // clang/AST/DeclNodes.def. 44 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); 45 Decl *VisitNamespaceDecl(NamespaceDecl *D); 46 Decl *VisitTypedefDecl(TypedefDecl *D); 47 Decl *VisitVarDecl(VarDecl *D); 48 Decl *VisitFieldDecl(FieldDecl *D); 49 Decl *VisitStaticAssertDecl(StaticAssertDecl *D); 50 Decl *VisitEnumDecl(EnumDecl *D); 51 Decl *VisitEnumConstantDecl(EnumConstantDecl *D); 52 Decl *VisitFriendDecl(FriendDecl *D); 53 Decl *VisitFunctionDecl(FunctionDecl *D, 54 TemplateParameterList *TemplateParams = 0); 55 Decl *VisitCXXRecordDecl(CXXRecordDecl *D); 56 Decl *VisitCXXMethodDecl(CXXMethodDecl *D, 57 TemplateParameterList *TemplateParams = 0); 58 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 59 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 60 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 61 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 62 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D); 63 Decl *VisitClassTemplatePartialSpecializationDecl( 64 ClassTemplatePartialSpecializationDecl *D); 65 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 66 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 67 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 68 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 69 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 70 Decl *VisitUsingDecl(UsingDecl *D); 71 Decl *VisitUsingShadowDecl(UsingShadowDecl *D); 72 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 73 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 74 75 // Base case. FIXME: Remove once we can instantiate everything. 76 Decl *VisitDecl(Decl *D) { 77 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 78 Diagnostic::Error, 79 "cannot instantiate %0 yet"); 80 SemaRef.Diag(D->getLocation(), DiagID) 81 << D->getDeclKindName(); 82 83 return 0; 84 } 85 86 const LangOptions &getLangOptions() { 87 return SemaRef.getLangOptions(); 88 } 89 90 // Helper functions for instantiating methods. 91 QualType SubstFunctionType(FunctionDecl *D, 92 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 93 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl); 94 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 95 96 TemplateParameterList * 97 SubstTemplateParams(TemplateParameterList *List); 98 99 bool InstantiateClassTemplatePartialSpecialization( 100 ClassTemplateDecl *ClassTemplate, 101 ClassTemplatePartialSpecializationDecl *PartialSpec); 102 }; 103} 104 105// FIXME: Is this too simple? 106void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) { 107 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr; 108 TmplAttr = TmplAttr->getNext()) { 109 110 // FIXME: Is cloning correct for all attributes? 111 Attr *NewAttr = TmplAttr->clone(SemaRef.Context); 112 113 New->addAttr(NewAttr); 114 } 115} 116 117Decl * 118TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 119 assert(false && "Translation units cannot be instantiated"); 120 return D; 121} 122 123Decl * 124TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 125 assert(false && "Namespaces cannot be instantiated"); 126 return D; 127} 128 129Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 130 bool Invalid = false; 131 TypeSourceInfo *DI = D->getTypeSourceInfo(); 132 if (DI->getType()->isDependentType()) { 133 DI = SemaRef.SubstType(DI, TemplateArgs, 134 D->getLocation(), D->getDeclName()); 135 if (!DI) { 136 Invalid = true; 137 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 138 } 139 } 140 141 // Create the new typedef 142 TypedefDecl *Typedef 143 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 144 D->getIdentifier(), DI); 145 if (Invalid) 146 Typedef->setInvalidDecl(); 147 148 if (TypedefDecl *Prev = D->getPreviousDeclaration()) { 149 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(Prev, TemplateArgs); 150 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev)); 151 } 152 153 Typedef->setAccess(D->getAccess()); 154 Owner->addDecl(Typedef); 155 156 return Typedef; 157} 158 159/// \brief Instantiate the arguments provided as part of initialization. 160/// 161/// \returns true if an error occurred, false otherwise. 162static bool InstantiateInitializationArguments(Sema &SemaRef, 163 Expr **Args, unsigned NumArgs, 164 const MultiLevelTemplateArgumentList &TemplateArgs, 165 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs, 166 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) { 167 for (unsigned I = 0; I != NumArgs; ++I) { 168 // When we hit the first defaulted argument, break out of the loop: 169 // we don't pass those default arguments on. 170 if (Args[I]->isDefaultArgument()) 171 break; 172 173 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs); 174 if (Arg.isInvalid()) 175 return true; 176 177 Expr *ArgExpr = (Expr *)Arg.get(); 178 InitArgs.push_back(Arg.release()); 179 180 // FIXME: We're faking all of the comma locations. Do we need them? 181 FakeCommaLocs.push_back( 182 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd())); 183 } 184 185 return false; 186} 187 188Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 189 // Do substitution on the type of the declaration 190 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 191 TemplateArgs, 192 D->getTypeSpecStartLoc(), 193 D->getDeclName()); 194 if (!DI) 195 return 0; 196 197 // Build the instantiated declaration 198 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 199 D->getLocation(), D->getIdentifier(), 200 DI->getType(), DI, 201 D->getStorageClass()); 202 Var->setThreadSpecified(D->isThreadSpecified()); 203 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 204 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 205 206 // If we are instantiating a static data member defined 207 // out-of-line, the instantiation will have the same lexical 208 // context (which will be a namespace scope) as the template. 209 if (D->isOutOfLine()) 210 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 211 212 Var->setAccess(D->getAccess()); 213 214 // FIXME: In theory, we could have a previous declaration for variables that 215 // are not static data members. 216 bool Redeclaration = false; 217 // FIXME: having to fake up a LookupResult is dumb. 218 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(), 219 Sema::LookupOrdinaryName); 220 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration); 221 222 if (D->isOutOfLine()) { 223 D->getLexicalDeclContext()->addDecl(Var); 224 Owner->makeDeclVisibleInContext(Var); 225 } else { 226 Owner->addDecl(Var); 227 } 228 229 // Link instantiations of static data members back to the template from 230 // which they were instantiated. 231 if (Var->isStaticDataMember()) 232 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 233 TSK_ImplicitInstantiation); 234 235 if (D->getInit()) { 236 if (Var->isStaticDataMember() && !D->isOutOfLine()) 237 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated); 238 else 239 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 240 241 // Extract the initializer, skipping through any temporary-binding 242 // expressions and look at the subexpression as it was written. 243 Expr *DInit = D->getInit(); 244 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(DInit)) 245 DInit = Binder->getSubExpr(); 246 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(DInit)) 247 DInit = ICE->getSubExprAsWritten(); 248 249 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(DInit)) { 250 // The initializer is a parenthesized list of expressions that is 251 // type-dependent. Instantiate each of the expressions; we'll be 252 // performing direct initialization with them. 253 llvm::SmallVector<SourceLocation, 4> CommaLocs; 254 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef); 255 if (!InstantiateInitializationArguments(SemaRef, 256 PLE->getExprs(), 257 PLE->getNumExprs(), 258 TemplateArgs, 259 CommaLocs, InitArgs)) { 260 // Add the direct initializer to the declaration. 261 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var), 262 PLE->getLParenLoc(), 263 move_arg(InitArgs), 264 CommaLocs.data(), 265 PLE->getRParenLoc()); 266 } 267 } else if (CXXConstructExpr *Construct =dyn_cast<CXXConstructExpr>(DInit)) { 268 // The initializer resolved to a constructor. Instantiate the constructor 269 // arguments. 270 llvm::SmallVector<SourceLocation, 4> CommaLocs; 271 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef); 272 273 if (!InstantiateInitializationArguments(SemaRef, 274 Construct->getArgs(), 275 Construct->getNumArgs(), 276 TemplateArgs, 277 CommaLocs, InitArgs)) { 278 if (D->hasCXXDirectInitializer()) { 279 SourceLocation FakeLParenLoc = 280 SemaRef.PP.getLocForEndOfToken(D->getLocation()); 281 SourceLocation FakeRParenLoc = CommaLocs.empty()? FakeLParenLoc 282 : CommaLocs.back(); 283 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var), 284 FakeLParenLoc, 285 move_arg(InitArgs), 286 CommaLocs.data(), 287 FakeRParenLoc); 288 } else if (InitArgs.size() == 1) { 289 Expr *Init = (Expr*)(InitArgs.take()[0]); 290 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), 291 SemaRef.Owned(Init), 292 false); 293 } else { 294 assert(InitArgs.size() == 0); 295 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 296 } 297 } 298 } else { 299 OwningExprResult Init 300 = SemaRef.SubstExpr(D->getInit(), TemplateArgs); 301 302 // FIXME: Not happy about invalidating decls just because of a bad 303 // initializer, unless it affects the type. 304 if (Init.isInvalid()) 305 Var->setInvalidDecl(); 306 else 307 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init), 308 D->hasCXXDirectInitializer()); 309 } 310 311 SemaRef.PopExpressionEvaluationContext(); 312 } else if (!Var->isStaticDataMember() || Var->isOutOfLine()) 313 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 314 315 return Var; 316} 317 318Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 319 bool Invalid = false; 320 TypeSourceInfo *DI = D->getTypeSourceInfo(); 321 if (DI->getType()->isDependentType()) { 322 DI = SemaRef.SubstType(DI, TemplateArgs, 323 D->getLocation(), D->getDeclName()); 324 if (!DI) { 325 DI = D->getTypeSourceInfo(); 326 Invalid = true; 327 } else if (DI->getType()->isFunctionType()) { 328 // C++ [temp.arg.type]p3: 329 // If a declaration acquires a function type through a type 330 // dependent on a template-parameter and this causes a 331 // declaration that does not use the syntactic form of a 332 // function declarator to have function type, the program is 333 // ill-formed. 334 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 335 << DI->getType(); 336 Invalid = true; 337 } 338 } 339 340 Expr *BitWidth = D->getBitWidth(); 341 if (Invalid) 342 BitWidth = 0; 343 else if (BitWidth) { 344 // The bit-width expression is not potentially evaluated. 345 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 346 347 OwningExprResult InstantiatedBitWidth 348 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 349 if (InstantiatedBitWidth.isInvalid()) { 350 Invalid = true; 351 BitWidth = 0; 352 } else 353 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 354 } 355 356 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 357 DI->getType(), DI, 358 cast<RecordDecl>(Owner), 359 D->getLocation(), 360 D->isMutable(), 361 BitWidth, 362 D->getTypeSpecStartLoc(), 363 D->getAccess(), 364 0); 365 if (!Field) { 366 cast<Decl>(Owner)->setInvalidDecl(); 367 return 0; 368 } 369 370 InstantiateAttrs(D, Field); 371 372 if (Invalid) 373 Field->setInvalidDecl(); 374 375 if (!Field->getDeclName()) { 376 // Keep track of where this decl came from. 377 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 378 } 379 380 Field->setImplicit(D->isImplicit()); 381 Field->setAccess(D->getAccess()); 382 Owner->addDecl(Field); 383 384 return Field; 385} 386 387Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 388 FriendDecl::FriendUnion FU; 389 390 // Handle friend type expressions by simply substituting template 391 // parameters into the pattern type. 392 if (Type *Ty = D->getFriendType()) { 393 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs, 394 D->getLocation(), DeclarationName()); 395 if (T.isNull()) return 0; 396 397 assert(getLangOptions().CPlusPlus0x || T->isRecordType()); 398 FU = T.getTypePtr(); 399 400 // Handle everything else by appropriate substitution. 401 } else { 402 NamedDecl *ND = D->getFriendDecl(); 403 assert(ND && "friend decl must be a decl or a type!"); 404 405 // FIXME: We have a problem here, because the nested call to Visit(ND) 406 // will inject the thing that the friend references into the current 407 // owner, which is wrong. 408 Decl *NewND; 409 410 // Hack to make this work almost well pending a rewrite. 411 if (ND->getDeclContext()->isRecord()) 412 NewND = SemaRef.FindInstantiatedDecl(ND, TemplateArgs); 413 else if (D->wasSpecialization()) { 414 // Totally egregious hack to work around PR5866 415 return 0; 416 } else 417 NewND = Visit(ND); 418 if (!NewND) return 0; 419 420 FU = cast<NamedDecl>(NewND); 421 } 422 423 FriendDecl *FD = 424 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU, 425 D->getFriendLoc()); 426 FD->setAccess(AS_public); 427 Owner->addDecl(FD); 428 return FD; 429} 430 431Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 432 Expr *AssertExpr = D->getAssertExpr(); 433 434 // The expression in a static assertion is not potentially evaluated. 435 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 436 437 OwningExprResult InstantiatedAssertExpr 438 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 439 if (InstantiatedAssertExpr.isInvalid()) 440 return 0; 441 442 OwningExprResult Message(SemaRef, D->getMessage()); 443 D->getMessage()->Retain(); 444 Decl *StaticAssert 445 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 446 move(InstantiatedAssertExpr), 447 move(Message)).getAs<Decl>(); 448 return StaticAssert; 449} 450 451Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 452 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 453 D->getLocation(), D->getIdentifier(), 454 D->getTagKeywordLoc(), 455 /*PrevDecl=*/0); 456 Enum->setInstantiationOfMemberEnum(D); 457 Enum->setAccess(D->getAccess()); 458 Owner->addDecl(Enum); 459 Enum->startDefinition(); 460 461 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators; 462 463 EnumConstantDecl *LastEnumConst = 0; 464 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 465 ECEnd = D->enumerator_end(); 466 EC != ECEnd; ++EC) { 467 // The specified value for the enumerator. 468 OwningExprResult Value = SemaRef.Owned((Expr *)0); 469 if (Expr *UninstValue = EC->getInitExpr()) { 470 // The enumerator's value expression is not potentially evaluated. 471 EnterExpressionEvaluationContext Unevaluated(SemaRef, 472 Action::Unevaluated); 473 474 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 475 } 476 477 // Drop the initial value and continue. 478 bool isInvalid = false; 479 if (Value.isInvalid()) { 480 Value = SemaRef.Owned((Expr *)0); 481 isInvalid = true; 482 } 483 484 EnumConstantDecl *EnumConst 485 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 486 EC->getLocation(), EC->getIdentifier(), 487 move(Value)); 488 489 if (isInvalid) { 490 if (EnumConst) 491 EnumConst->setInvalidDecl(); 492 Enum->setInvalidDecl(); 493 } 494 495 if (EnumConst) { 496 EnumConst->setAccess(Enum->getAccess()); 497 Enum->addDecl(EnumConst); 498 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 499 LastEnumConst = EnumConst; 500 } 501 } 502 503 // FIXME: Fixup LBraceLoc and RBraceLoc 504 // FIXME: Empty Scope and AttributeList (required to handle attribute packed). 505 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 506 Sema::DeclPtrTy::make(Enum), 507 &Enumerators[0], Enumerators.size(), 508 0, 0); 509 510 return Enum; 511} 512 513Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 514 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 515 return 0; 516} 517 518namespace { 519 class SortDeclByLocation { 520 SourceManager &SourceMgr; 521 522 public: 523 explicit SortDeclByLocation(SourceManager &SourceMgr) 524 : SourceMgr(SourceMgr) { } 525 526 bool operator()(const Decl *X, const Decl *Y) const { 527 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(), 528 Y->getLocation()); 529 } 530 }; 531} 532 533Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 534 // Create a local instantiation scope for this class template, which 535 // will contain the instantiations of the template parameters. 536 Sema::LocalInstantiationScope Scope(SemaRef); 537 TemplateParameterList *TempParams = D->getTemplateParameters(); 538 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 539 if (!InstParams) 540 return NULL; 541 542 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 543 CXXRecordDecl *RecordInst 544 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner, 545 Pattern->getLocation(), Pattern->getIdentifier(), 546 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL, 547 /*DelayTypeCreation=*/true); 548 549 ClassTemplateDecl *Inst 550 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 551 D->getIdentifier(), InstParams, RecordInst, 0); 552 RecordInst->setDescribedClassTemplate(Inst); 553 if (D->getFriendObjectKind()) 554 Inst->setObjectOfFriendDecl(true); 555 else 556 Inst->setAccess(D->getAccess()); 557 Inst->setInstantiatedFromMemberTemplate(D); 558 559 // Trigger creation of the type for the instantiation. 560 SemaRef.Context.getTypeDeclType(RecordInst); 561 562 // Finish handling of friends. 563 if (Inst->getFriendObjectKind()) { 564 return Inst; 565 } 566 567 Inst->setAccess(D->getAccess()); 568 Owner->addDecl(Inst); 569 570 // First, we sort the partial specializations by location, so 571 // that we instantiate them in the order they were declared. 572 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 573 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 574 P = D->getPartialSpecializations().begin(), 575 PEnd = D->getPartialSpecializations().end(); 576 P != PEnd; ++P) 577 PartialSpecs.push_back(&*P); 578 std::sort(PartialSpecs.begin(), PartialSpecs.end(), 579 SortDeclByLocation(SemaRef.SourceMgr)); 580 581 // Instantiate all of the partial specializations of this member class 582 // template. 583 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 584 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]); 585 586 return Inst; 587} 588 589Decl * 590TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 591 ClassTemplatePartialSpecializationDecl *D) { 592 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 593 594 // Lookup the already-instantiated declaration in the instantiation 595 // of the class template and return that. 596 DeclContext::lookup_result Found 597 = Owner->lookup(ClassTemplate->getDeclName()); 598 if (Found.first == Found.second) 599 return 0; 600 601 ClassTemplateDecl *InstClassTemplate 602 = dyn_cast<ClassTemplateDecl>(*Found.first); 603 if (!InstClassTemplate) 604 return 0; 605 606 Decl *DCanon = D->getCanonicalDecl(); 607 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 608 P = InstClassTemplate->getPartialSpecializations().begin(), 609 PEnd = InstClassTemplate->getPartialSpecializations().end(); 610 P != PEnd; ++P) { 611 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon) 612 return &*P; 613 } 614 615 return 0; 616} 617 618Decl * 619TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 620 // Create a local instantiation scope for this function template, which 621 // will contain the instantiations of the template parameters and then get 622 // merged with the local instantiation scope for the function template 623 // itself. 624 Sema::LocalInstantiationScope Scope(SemaRef); 625 626 TemplateParameterList *TempParams = D->getTemplateParameters(); 627 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 628 if (!InstParams) 629 return NULL; 630 631 FunctionDecl *Instantiated = 0; 632 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 633 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 634 InstParams)); 635 else 636 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 637 D->getTemplatedDecl(), 638 InstParams)); 639 640 if (!Instantiated) 641 return 0; 642 643 Instantiated->setAccess(D->getAccess()); 644 645 // Link the instantiated function template declaration to the function 646 // template from which it was instantiated. 647 FunctionTemplateDecl *InstTemplate 648 = Instantiated->getDescribedFunctionTemplate(); 649 InstTemplate->setAccess(D->getAccess()); 650 assert(InstTemplate && 651 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 652 653 // Link the instantiation back to the pattern *unless* this is a 654 // non-definition friend declaration. 655 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 656 !(InstTemplate->getFriendObjectKind() && 657 !D->getTemplatedDecl()->isThisDeclarationADefinition())) 658 InstTemplate->setInstantiatedFromMemberTemplate(D); 659 660 // Add non-friends into the owner. 661 if (!InstTemplate->getFriendObjectKind()) 662 Owner->addDecl(InstTemplate); 663 return InstTemplate; 664} 665 666Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 667 CXXRecordDecl *PrevDecl = 0; 668 if (D->isInjectedClassName()) 669 PrevDecl = cast<CXXRecordDecl>(Owner); 670 else if (D->getPreviousDeclaration()) { 671 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getPreviousDeclaration(), 672 TemplateArgs); 673 if (!Prev) return 0; 674 PrevDecl = cast<CXXRecordDecl>(Prev); 675 } 676 677 CXXRecordDecl *Record 678 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 679 D->getLocation(), D->getIdentifier(), 680 D->getTagKeywordLoc(), PrevDecl); 681 Record->setImplicit(D->isImplicit()); 682 // FIXME: Check against AS_none is an ugly hack to work around the issue that 683 // the tag decls introduced by friend class declarations don't have an access 684 // specifier. Remove once this area of the code gets sorted out. 685 if (D->getAccess() != AS_none) 686 Record->setAccess(D->getAccess()); 687 if (!D->isInjectedClassName()) 688 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 689 690 // If the original function was part of a friend declaration, 691 // inherit its namespace state. 692 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 693 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 694 695 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion()); 696 697 Owner->addDecl(Record); 698 return Record; 699} 700 701/// Normal class members are of more specific types and therefore 702/// don't make it here. This function serves two purposes: 703/// 1) instantiating function templates 704/// 2) substituting friend declarations 705/// FIXME: preserve function definitions in case #2 706Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 707 TemplateParameterList *TemplateParams) { 708 // Check whether there is already a function template specialization for 709 // this declaration. 710 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 711 void *InsertPos = 0; 712 if (FunctionTemplate && !TemplateParams) { 713 llvm::FoldingSetNodeID ID; 714 FunctionTemplateSpecializationInfo::Profile(ID, 715 TemplateArgs.getInnermost().getFlatArgumentList(), 716 TemplateArgs.getInnermost().flat_size(), 717 SemaRef.Context); 718 719 FunctionTemplateSpecializationInfo *Info 720 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 721 InsertPos); 722 723 // If we already have a function template specialization, return it. 724 if (Info) 725 return Info->Function; 726 } 727 728 bool MergeWithParentScope = (TemplateParams != 0) || 729 !(isa<Decl>(Owner) && 730 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 731 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 732 733 llvm::SmallVector<ParmVarDecl *, 4> Params; 734 QualType T = SubstFunctionType(D, Params); 735 if (T.isNull()) 736 return 0; 737 738 // Build the instantiated method declaration. 739 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(), 740 TemplateArgs); 741 FunctionDecl *Function = 742 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(), 743 D->getDeclName(), T, D->getTypeSourceInfo(), 744 D->getStorageClass(), 745 D->isInlineSpecified(), D->hasWrittenPrototype()); 746 Function->setLexicalDeclContext(Owner); 747 748 // Attach the parameters 749 for (unsigned P = 0; P < Params.size(); ++P) 750 Params[P]->setOwningFunction(Function); 751 Function->setParams(SemaRef.Context, Params.data(), Params.size()); 752 753 if (TemplateParams) { 754 // Our resulting instantiation is actually a function template, since we 755 // are substituting only the outer template parameters. For example, given 756 // 757 // template<typename T> 758 // struct X { 759 // template<typename U> friend void f(T, U); 760 // }; 761 // 762 // X<int> x; 763 // 764 // We are instantiating the friend function template "f" within X<int>, 765 // which means substituting int for T, but leaving "f" as a friend function 766 // template. 767 // Build the function template itself. 768 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner, 769 Function->getLocation(), 770 Function->getDeclName(), 771 TemplateParams, Function); 772 Function->setDescribedFunctionTemplate(FunctionTemplate); 773 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 774 } else if (FunctionTemplate) { 775 // Record this function template specialization. 776 Function->setFunctionTemplateSpecialization(SemaRef.Context, 777 FunctionTemplate, 778 &TemplateArgs.getInnermost(), 779 InsertPos); 780 } 781 782 if (InitFunctionInstantiation(Function, D)) 783 Function->setInvalidDecl(); 784 785 bool Redeclaration = false; 786 bool OverloadableAttrRequired = false; 787 788 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(), 789 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 790 791 if (TemplateParams || !FunctionTemplate) { 792 // Look only into the namespace where the friend would be declared to 793 // find a previous declaration. This is the innermost enclosing namespace, 794 // as described in ActOnFriendFunctionDecl. 795 SemaRef.LookupQualifiedName(Previous, DC); 796 797 // In C++, the previous declaration we find might be a tag type 798 // (class or enum). In this case, the new declaration will hide the 799 // tag type. Note that this does does not apply if we're declaring a 800 // typedef (C++ [dcl.typedef]p4). 801 if (Previous.isSingleTagDecl()) 802 Previous.clear(); 803 } 804 805 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 806 false, Redeclaration, 807 /*FIXME:*/OverloadableAttrRequired); 808 809 // If the original function was part of a friend declaration, 810 // inherit its namespace state and add it to the owner. 811 NamedDecl *FromFriendD 812 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D; 813 if (FromFriendD->getFriendObjectKind()) { 814 NamedDecl *ToFriendD = 0; 815 NamedDecl *PrevDecl; 816 if (TemplateParams) { 817 ToFriendD = cast<NamedDecl>(FunctionTemplate); 818 PrevDecl = FunctionTemplate->getPreviousDeclaration(); 819 } else { 820 ToFriendD = Function; 821 PrevDecl = Function->getPreviousDeclaration(); 822 } 823 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL); 824 if (!Owner->isDependentContext() && !PrevDecl) 825 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false); 826 827 if (!TemplateParams) 828 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 829 } 830 831 return Function; 832} 833 834Decl * 835TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 836 TemplateParameterList *TemplateParams) { 837 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 838 void *InsertPos = 0; 839 if (FunctionTemplate && !TemplateParams) { 840 // We are creating a function template specialization from a function 841 // template. Check whether there is already a function template 842 // specialization for this particular set of template arguments. 843 llvm::FoldingSetNodeID ID; 844 FunctionTemplateSpecializationInfo::Profile(ID, 845 TemplateArgs.getInnermost().getFlatArgumentList(), 846 TemplateArgs.getInnermost().flat_size(), 847 SemaRef.Context); 848 849 FunctionTemplateSpecializationInfo *Info 850 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 851 InsertPos); 852 853 // If we already have a function template specialization, return it. 854 if (Info) 855 return Info->Function; 856 } 857 858 bool MergeWithParentScope = (TemplateParams != 0) || 859 !(isa<Decl>(Owner) && 860 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 861 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 862 863 llvm::SmallVector<ParmVarDecl *, 4> Params; 864 QualType T = SubstFunctionType(D, Params); 865 if (T.isNull()) 866 return 0; 867 868 // Build the instantiated method declaration. 869 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 870 CXXMethodDecl *Method = 0; 871 872 DeclarationName Name = D->getDeclName(); 873 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 874 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 875 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName( 876 SemaRef.Context.getCanonicalType(ClassTy)); 877 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 878 Constructor->getLocation(), 879 Name, T, 880 Constructor->getTypeSourceInfo(), 881 Constructor->isExplicit(), 882 Constructor->isInlineSpecified(), false); 883 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 884 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 885 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName( 886 SemaRef.Context.getCanonicalType(ClassTy)); 887 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 888 Destructor->getLocation(), Name, 889 T, Destructor->isInlineSpecified(), false); 890 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 891 CanQualType ConvTy 892 = SemaRef.Context.getCanonicalType( 893 T->getAs<FunctionType>()->getResultType()); 894 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName( 895 ConvTy); 896 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 897 Conversion->getLocation(), Name, 898 T, Conversion->getTypeSourceInfo(), 899 Conversion->isInlineSpecified(), 900 Conversion->isExplicit()); 901 } else { 902 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 903 D->getDeclName(), T, D->getTypeSourceInfo(), 904 D->isStatic(), D->isInlineSpecified()); 905 } 906 907 if (TemplateParams) { 908 // Our resulting instantiation is actually a function template, since we 909 // are substituting only the outer template parameters. For example, given 910 // 911 // template<typename T> 912 // struct X { 913 // template<typename U> void f(T, U); 914 // }; 915 // 916 // X<int> x; 917 // 918 // We are instantiating the member template "f" within X<int>, which means 919 // substituting int for T, but leaving "f" as a member function template. 920 // Build the function template itself. 921 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 922 Method->getLocation(), 923 Method->getDeclName(), 924 TemplateParams, Method); 925 if (D->isOutOfLine()) 926 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 927 Method->setDescribedFunctionTemplate(FunctionTemplate); 928 } else if (FunctionTemplate) { 929 // Record this function template specialization. 930 Method->setFunctionTemplateSpecialization(SemaRef.Context, 931 FunctionTemplate, 932 &TemplateArgs.getInnermost(), 933 InsertPos); 934 } else { 935 // Record that this is an instantiation of a member function. 936 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 937 } 938 939 // If we are instantiating a member function defined 940 // out-of-line, the instantiation will have the same lexical 941 // context (which will be a namespace scope) as the template. 942 if (D->isOutOfLine()) 943 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 944 945 // Attach the parameters 946 for (unsigned P = 0; P < Params.size(); ++P) 947 Params[P]->setOwningFunction(Method); 948 Method->setParams(SemaRef.Context, Params.data(), Params.size()); 949 950 if (InitMethodInstantiation(Method, D)) 951 Method->setInvalidDecl(); 952 953 LookupResult Previous(SemaRef, Name, SourceLocation(), 954 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 955 956 if (!FunctionTemplate || TemplateParams) { 957 SemaRef.LookupQualifiedName(Previous, Owner); 958 959 // In C++, the previous declaration we find might be a tag type 960 // (class or enum). In this case, the new declaration will hide the 961 // tag type. Note that this does does not apply if we're declaring a 962 // typedef (C++ [dcl.typedef]p4). 963 if (Previous.isSingleTagDecl()) 964 Previous.clear(); 965 } 966 967 bool Redeclaration = false; 968 bool OverloadableAttrRequired = false; 969 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration, 970 /*FIXME:*/OverloadableAttrRequired); 971 972 if (D->isPure()) 973 SemaRef.CheckPureMethod(Method, SourceRange()); 974 975 Method->setAccess(D->getAccess()); 976 977 if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) && 978 !Method->getFriendObjectKind()) 979 Owner->addDecl(Method); 980 981 return Method; 982} 983 984Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 985 return VisitCXXMethodDecl(D); 986} 987 988Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 989 return VisitCXXMethodDecl(D); 990} 991 992Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 993 return VisitCXXMethodDecl(D); 994} 995 996ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 997 QualType T; 998 TypeSourceInfo *DI = D->getTypeSourceInfo(); 999 if (DI) { 1000 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 1001 D->getDeclName()); 1002 if (DI) T = DI->getType(); 1003 } else { 1004 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 1005 D->getDeclName()); 1006 DI = 0; 1007 } 1008 1009 if (T.isNull()) 1010 return 0; 1011 1012 T = SemaRef.adjustParameterType(T); 1013 1014 // Allocate the parameter 1015 ParmVarDecl *Param 1016 = ParmVarDecl::Create(SemaRef.Context, 1017 SemaRef.Context.getTranslationUnitDecl(), 1018 D->getLocation(), 1019 D->getIdentifier(), T, DI, D->getStorageClass(), 0); 1020 1021 // Mark the default argument as being uninstantiated. 1022 if (D->hasUninstantiatedDefaultArg()) 1023 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg()); 1024 else if (Expr *Arg = D->getDefaultArg()) 1025 Param->setUninstantiatedDefaultArg(Arg); 1026 1027 // Note: we don't try to instantiate function parameters until after 1028 // we've instantiated the function's type. Therefore, we don't have 1029 // to check for 'void' parameter types here. 1030 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1031 return Param; 1032} 1033 1034Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1035 TemplateTypeParmDecl *D) { 1036 // TODO: don't always clone when decls are refcounted. 1037 const Type* T = D->getTypeForDecl(); 1038 assert(T->isTemplateTypeParmType()); 1039 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>(); 1040 1041 TemplateTypeParmDecl *Inst = 1042 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1043 TTPT->getDepth() - 1, TTPT->getIndex(), 1044 TTPT->getName(), 1045 D->wasDeclaredWithTypename(), 1046 D->isParameterPack()); 1047 1048 if (D->hasDefaultArgument()) 1049 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 1050 1051 // Introduce this template parameter's instantiation into the instantiation 1052 // scope. 1053 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1054 1055 return Inst; 1056} 1057 1058Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1059 NonTypeTemplateParmDecl *D) { 1060 // Substitute into the type of the non-type template parameter. 1061 QualType T; 1062 TypeSourceInfo *DI = D->getTypeSourceInfo(); 1063 if (DI) { 1064 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 1065 D->getDeclName()); 1066 if (DI) T = DI->getType(); 1067 } else { 1068 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 1069 D->getDeclName()); 1070 DI = 0; 1071 } 1072 if (T.isNull()) 1073 return 0; 1074 1075 // Check that this type is acceptable for a non-type template parameter. 1076 bool Invalid = false; 1077 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation()); 1078 if (T.isNull()) { 1079 T = SemaRef.Context.IntTy; 1080 Invalid = true; 1081 } 1082 1083 NonTypeTemplateParmDecl *Param 1084 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1085 D->getDepth() - 1, D->getPosition(), 1086 D->getIdentifier(), T, DI); 1087 if (Invalid) 1088 Param->setInvalidDecl(); 1089 1090 Param->setDefaultArgument(D->getDefaultArgument()); 1091 1092 // Introduce this template parameter's instantiation into the instantiation 1093 // scope. 1094 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1095 return Param; 1096} 1097 1098Decl * 1099TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1100 TemplateTemplateParmDecl *D) { 1101 // Instantiate the template parameter list of the template template parameter. 1102 TemplateParameterList *TempParams = D->getTemplateParameters(); 1103 TemplateParameterList *InstParams; 1104 { 1105 // Perform the actual substitution of template parameters within a new, 1106 // local instantiation scope. 1107 Sema::LocalInstantiationScope Scope(SemaRef); 1108 InstParams = SubstTemplateParams(TempParams); 1109 if (!InstParams) 1110 return NULL; 1111 } 1112 1113 // Build the template template parameter. 1114 TemplateTemplateParmDecl *Param 1115 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1116 D->getDepth() - 1, D->getPosition(), 1117 D->getIdentifier(), InstParams); 1118 Param->setDefaultArgument(D->getDefaultArgument()); 1119 1120 // Introduce this template parameter's instantiation into the instantiation 1121 // scope. 1122 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1123 1124 return Param; 1125} 1126 1127Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1128 // Using directives are never dependent, so they require no explicit 1129 1130 UsingDirectiveDecl *Inst 1131 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1132 D->getNamespaceKeyLocation(), 1133 D->getQualifierRange(), D->getQualifier(), 1134 D->getIdentLocation(), 1135 D->getNominatedNamespace(), 1136 D->getCommonAncestor()); 1137 Owner->addDecl(Inst); 1138 return Inst; 1139} 1140 1141Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 1142 // The nested name specifier is non-dependent, so no transformation 1143 // is required. 1144 1145 // We only need to do redeclaration lookups if we're in a class 1146 // scope (in fact, it's not really even possible in non-class 1147 // scopes). 1148 bool CheckRedeclaration = Owner->isRecord(); 1149 1150 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(), 1151 Sema::LookupUsingDeclName, Sema::ForRedeclaration); 1152 1153 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 1154 D->getLocation(), 1155 D->getNestedNameRange(), 1156 D->getUsingLocation(), 1157 D->getTargetNestedNameDecl(), 1158 D->getDeclName(), 1159 D->isTypeName()); 1160 1161 CXXScopeSpec SS; 1162 SS.setScopeRep(D->getTargetNestedNameDecl()); 1163 SS.setRange(D->getNestedNameRange()); 1164 1165 if (CheckRedeclaration) { 1166 Prev.setHideTags(false); 1167 SemaRef.LookupQualifiedName(Prev, Owner); 1168 1169 // Check for invalid redeclarations. 1170 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(), 1171 D->isTypeName(), SS, 1172 D->getLocation(), Prev)) 1173 NewUD->setInvalidDecl(); 1174 1175 } 1176 1177 if (!NewUD->isInvalidDecl() && 1178 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS, 1179 D->getLocation())) 1180 NewUD->setInvalidDecl(); 1181 1182 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 1183 NewUD->setAccess(D->getAccess()); 1184 Owner->addDecl(NewUD); 1185 1186 // Don't process the shadow decls for an invalid decl. 1187 if (NewUD->isInvalidDecl()) 1188 return NewUD; 1189 1190 bool isFunctionScope = Owner->isFunctionOrMethod(); 1191 1192 // Process the shadow decls. 1193 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 1194 I != E; ++I) { 1195 UsingShadowDecl *Shadow = *I; 1196 NamedDecl *InstTarget = 1197 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getTargetDecl(), 1198 TemplateArgs)); 1199 1200 if (CheckRedeclaration && 1201 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev)) 1202 continue; 1203 1204 UsingShadowDecl *InstShadow 1205 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget); 1206 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 1207 1208 if (isFunctionScope) 1209 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 1210 } 1211 1212 return NewUD; 1213} 1214 1215Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 1216 // Ignore these; we handle them in bulk when processing the UsingDecl. 1217 return 0; 1218} 1219 1220Decl * TemplateDeclInstantiator 1221 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 1222 NestedNameSpecifier *NNS = 1223 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1224 D->getTargetNestedNameRange(), 1225 TemplateArgs); 1226 if (!NNS) 1227 return 0; 1228 1229 CXXScopeSpec SS; 1230 SS.setRange(D->getTargetNestedNameRange()); 1231 SS.setScopeRep(NNS); 1232 1233 NamedDecl *UD = 1234 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1235 D->getUsingLoc(), SS, D->getLocation(), 1236 D->getDeclName(), 0, 1237 /*instantiation*/ true, 1238 /*typename*/ true, D->getTypenameLoc()); 1239 if (UD) 1240 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1241 1242 return UD; 1243} 1244 1245Decl * TemplateDeclInstantiator 1246 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1247 NestedNameSpecifier *NNS = 1248 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1249 D->getTargetNestedNameRange(), 1250 TemplateArgs); 1251 if (!NNS) 1252 return 0; 1253 1254 CXXScopeSpec SS; 1255 SS.setRange(D->getTargetNestedNameRange()); 1256 SS.setScopeRep(NNS); 1257 1258 NamedDecl *UD = 1259 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1260 D->getUsingLoc(), SS, D->getLocation(), 1261 D->getDeclName(), 0, 1262 /*instantiation*/ true, 1263 /*typename*/ false, SourceLocation()); 1264 if (UD) 1265 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1266 1267 return UD; 1268} 1269 1270Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 1271 const MultiLevelTemplateArgumentList &TemplateArgs) { 1272 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 1273 return Instantiator.Visit(D); 1274} 1275 1276/// \brief Instantiates a nested template parameter list in the current 1277/// instantiation context. 1278/// 1279/// \param L The parameter list to instantiate 1280/// 1281/// \returns NULL if there was an error 1282TemplateParameterList * 1283TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 1284 // Get errors for all the parameters before bailing out. 1285 bool Invalid = false; 1286 1287 unsigned N = L->size(); 1288 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector; 1289 ParamVector Params; 1290 Params.reserve(N); 1291 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 1292 PI != PE; ++PI) { 1293 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 1294 Params.push_back(D); 1295 Invalid = Invalid || !D || D->isInvalidDecl(); 1296 } 1297 1298 // Clean up if we had an error. 1299 if (Invalid) { 1300 for (ParamVector::iterator PI = Params.begin(), PE = Params.end(); 1301 PI != PE; ++PI) 1302 if (*PI) 1303 (*PI)->Destroy(SemaRef.Context); 1304 return NULL; 1305 } 1306 1307 TemplateParameterList *InstL 1308 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 1309 L->getLAngleLoc(), &Params.front(), N, 1310 L->getRAngleLoc()); 1311 return InstL; 1312} 1313 1314/// \brief Instantiate the declaration of a class template partial 1315/// specialization. 1316/// 1317/// \param ClassTemplate the (instantiated) class template that is partially 1318// specialized by the instantiation of \p PartialSpec. 1319/// 1320/// \param PartialSpec the (uninstantiated) class template partial 1321/// specialization that we are instantiating. 1322/// 1323/// \returns true if there was an error, false otherwise. 1324bool 1325TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 1326 ClassTemplateDecl *ClassTemplate, 1327 ClassTemplatePartialSpecializationDecl *PartialSpec) { 1328 // Create a local instantiation scope for this class template partial 1329 // specialization, which will contain the instantiations of the template 1330 // parameters. 1331 Sema::LocalInstantiationScope Scope(SemaRef); 1332 1333 // Substitute into the template parameters of the class template partial 1334 // specialization. 1335 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 1336 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1337 if (!InstParams) 1338 return true; 1339 1340 // Substitute into the template arguments of the class template partial 1341 // specialization. 1342 const TemplateArgumentLoc *PartialSpecTemplateArgs 1343 = PartialSpec->getTemplateArgsAsWritten(); 1344 unsigned N = PartialSpec->getNumTemplateArgsAsWritten(); 1345 1346 TemplateArgumentListInfo InstTemplateArgs; // no angle locations 1347 for (unsigned I = 0; I != N; ++I) { 1348 TemplateArgumentLoc Loc; 1349 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs)) 1350 return true; 1351 InstTemplateArgs.addArgument(Loc); 1352 } 1353 1354 1355 // Check that the template argument list is well-formed for this 1356 // class template. 1357 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 1358 InstTemplateArgs.size()); 1359 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 1360 PartialSpec->getLocation(), 1361 InstTemplateArgs, 1362 false, 1363 Converted)) 1364 return true; 1365 1366 // Figure out where to insert this class template partial specialization 1367 // in the member template's set of class template partial specializations. 1368 llvm::FoldingSetNodeID ID; 1369 ClassTemplatePartialSpecializationDecl::Profile(ID, 1370 Converted.getFlatArguments(), 1371 Converted.flatSize(), 1372 SemaRef.Context); 1373 void *InsertPos = 0; 1374 ClassTemplateSpecializationDecl *PrevDecl 1375 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 1376 InsertPos); 1377 1378 // Build the canonical type that describes the converted template 1379 // arguments of the class template partial specialization. 1380 QualType CanonType 1381 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1382 Converted.getFlatArguments(), 1383 Converted.flatSize()); 1384 1385 // Build the fully-sugared type for this class template 1386 // specialization as the user wrote in the specialization 1387 // itself. This means that we'll pretty-print the type retrieved 1388 // from the specialization's declaration the way that the user 1389 // actually wrote the specialization, rather than formatting the 1390 // name based on the "canonical" representation used to store the 1391 // template arguments in the specialization. 1392 QualType WrittenTy 1393 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1394 InstTemplateArgs, 1395 CanonType); 1396 1397 if (PrevDecl) { 1398 // We've already seen a partial specialization with the same template 1399 // parameters and template arguments. This can happen, for example, when 1400 // substituting the outer template arguments ends up causing two 1401 // class template partial specializations of a member class template 1402 // to have identical forms, e.g., 1403 // 1404 // template<typename T, typename U> 1405 // struct Outer { 1406 // template<typename X, typename Y> struct Inner; 1407 // template<typename Y> struct Inner<T, Y>; 1408 // template<typename Y> struct Inner<U, Y>; 1409 // }; 1410 // 1411 // Outer<int, int> outer; // error: the partial specializations of Inner 1412 // // have the same signature. 1413 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 1414 << WrittenTy; 1415 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 1416 << SemaRef.Context.getTypeDeclType(PrevDecl); 1417 return true; 1418 } 1419 1420 1421 // Create the class template partial specialization declaration. 1422 ClassTemplatePartialSpecializationDecl *InstPartialSpec 1423 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner, 1424 PartialSpec->getLocation(), 1425 InstParams, 1426 ClassTemplate, 1427 Converted, 1428 InstTemplateArgs, 1429 0); 1430 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 1431 InstPartialSpec->setTypeAsWritten(WrittenTy); 1432 1433 // Add this partial specialization to the set of class template partial 1434 // specializations. 1435 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec, 1436 InsertPos); 1437 return false; 1438} 1439 1440/// \brief Does substitution on the type of the given function, including 1441/// all of the function parameters. 1442/// 1443/// \param D The function whose type will be the basis of the substitution 1444/// 1445/// \param Params the instantiated parameter declarations 1446 1447/// \returns the instantiated function's type if successful, a NULL 1448/// type if there was an error. 1449QualType 1450TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 1451 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 1452 bool InvalidDecl = false; 1453 1454 // Substitute all of the function's formal parameter types. 1455 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs); 1456 llvm::SmallVector<QualType, 4> ParamTys; 1457 for (FunctionDecl::param_iterator P = D->param_begin(), 1458 PEnd = D->param_end(); 1459 P != PEnd; ++P) { 1460 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { 1461 if (PInst->getType()->isVoidType()) { 1462 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); 1463 PInst->setInvalidDecl(); 1464 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), 1465 PInst->getType(), 1466 diag::err_abstract_type_in_decl, 1467 Sema::AbstractParamType)) 1468 PInst->setInvalidDecl(); 1469 1470 Params.push_back(PInst); 1471 ParamTys.push_back(PInst->getType()); 1472 1473 if (PInst->isInvalidDecl()) 1474 InvalidDecl = true; 1475 } else 1476 InvalidDecl = true; 1477 } 1478 1479 // FIXME: Deallocate dead declarations. 1480 if (InvalidDecl) 1481 return QualType(); 1482 1483 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>(); 1484 assert(Proto && "Missing prototype?"); 1485 QualType ResultType 1486 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs, 1487 D->getLocation(), D->getDeclName()); 1488 if (ResultType.isNull()) 1489 return QualType(); 1490 1491 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(), 1492 Proto->isVariadic(), Proto->getTypeQuals(), 1493 D->getLocation(), D->getDeclName()); 1494} 1495 1496/// \brief Initializes the common fields of an instantiation function 1497/// declaration (New) from the corresponding fields of its template (Tmpl). 1498/// 1499/// \returns true if there was an error 1500bool 1501TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 1502 FunctionDecl *Tmpl) { 1503 if (Tmpl->isDeleted()) 1504 New->setDeleted(); 1505 1506 // If we are performing substituting explicitly-specified template arguments 1507 // or deduced template arguments into a function template and we reach this 1508 // point, we are now past the point where SFINAE applies and have committed 1509 // to keeping the new function template specialization. We therefore 1510 // convert the active template instantiation for the function template 1511 // into a template instantiation for this specific function template 1512 // specialization, which is not a SFINAE context, so that we diagnose any 1513 // further errors in the declaration itself. 1514 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 1515 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 1516 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 1517 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 1518 if (FunctionTemplateDecl *FunTmpl 1519 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 1520 assert(FunTmpl->getTemplatedDecl() == Tmpl && 1521 "Deduction from the wrong function template?"); 1522 (void) FunTmpl; 1523 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 1524 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 1525 --SemaRef.NonInstantiationEntries; 1526 } 1527 } 1528 1529 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 1530 assert(Proto && "Function template without prototype?"); 1531 1532 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() || 1533 Proto->getNoReturnAttr()) { 1534 // The function has an exception specification or a "noreturn" 1535 // attribute. Substitute into each of the exception types. 1536 llvm::SmallVector<QualType, 4> Exceptions; 1537 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 1538 // FIXME: Poor location information! 1539 QualType T 1540 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 1541 New->getLocation(), New->getDeclName()); 1542 if (T.isNull() || 1543 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 1544 continue; 1545 1546 Exceptions.push_back(T); 1547 } 1548 1549 // Rebuild the function type 1550 1551 const FunctionProtoType *NewProto 1552 = New->getType()->getAs<FunctionProtoType>(); 1553 assert(NewProto && "Template instantiation without function prototype?"); 1554 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 1555 NewProto->arg_type_begin(), 1556 NewProto->getNumArgs(), 1557 NewProto->isVariadic(), 1558 NewProto->getTypeQuals(), 1559 Proto->hasExceptionSpec(), 1560 Proto->hasAnyExceptionSpec(), 1561 Exceptions.size(), 1562 Exceptions.data(), 1563 Proto->getNoReturnAttr(), 1564 Proto->getCallConv())); 1565 } 1566 1567 return false; 1568} 1569 1570/// \brief Initializes common fields of an instantiated method 1571/// declaration (New) from the corresponding fields of its template 1572/// (Tmpl). 1573/// 1574/// \returns true if there was an error 1575bool 1576TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 1577 CXXMethodDecl *Tmpl) { 1578 if (InitFunctionInstantiation(New, Tmpl)) 1579 return true; 1580 1581 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 1582 New->setAccess(Tmpl->getAccess()); 1583 if (Tmpl->isVirtualAsWritten()) 1584 Record->setMethodAsVirtual(New); 1585 1586 // FIXME: attributes 1587 // FIXME: New needs a pointer to Tmpl 1588 return false; 1589} 1590 1591/// \brief Instantiate the definition of the given function from its 1592/// template. 1593/// 1594/// \param PointOfInstantiation the point at which the instantiation was 1595/// required. Note that this is not precisely a "point of instantiation" 1596/// for the function, but it's close. 1597/// 1598/// \param Function the already-instantiated declaration of a 1599/// function template specialization or member function of a class template 1600/// specialization. 1601/// 1602/// \param Recursive if true, recursively instantiates any functions that 1603/// are required by this instantiation. 1604/// 1605/// \param DefinitionRequired if true, then we are performing an explicit 1606/// instantiation where the body of the function is required. Complain if 1607/// there is no such body. 1608void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 1609 FunctionDecl *Function, 1610 bool Recursive, 1611 bool DefinitionRequired) { 1612 if (Function->isInvalidDecl()) 1613 return; 1614 1615 assert(!Function->getBody() && "Already instantiated!"); 1616 1617 // Never instantiate an explicit specialization. 1618 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1619 return; 1620 1621 // Find the function body that we'll be substituting. 1622 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 1623 Stmt *Pattern = 0; 1624 if (PatternDecl) 1625 Pattern = PatternDecl->getBody(PatternDecl); 1626 1627 if (!Pattern) { 1628 if (DefinitionRequired) { 1629 if (Function->getPrimaryTemplate()) 1630 Diag(PointOfInstantiation, 1631 diag::err_explicit_instantiation_undefined_func_template) 1632 << Function->getPrimaryTemplate(); 1633 else 1634 Diag(PointOfInstantiation, 1635 diag::err_explicit_instantiation_undefined_member) 1636 << 1 << Function->getDeclName() << Function->getDeclContext(); 1637 1638 if (PatternDecl) 1639 Diag(PatternDecl->getLocation(), 1640 diag::note_explicit_instantiation_here); 1641 } 1642 1643 return; 1644 } 1645 1646 // C++0x [temp.explicit]p9: 1647 // Except for inline functions, other explicit instantiation declarations 1648 // have the effect of suppressing the implicit instantiation of the entity 1649 // to which they refer. 1650 if (Function->getTemplateSpecializationKind() 1651 == TSK_ExplicitInstantiationDeclaration && 1652 !PatternDecl->isInlined()) 1653 return; 1654 1655 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 1656 if (Inst) 1657 return; 1658 1659 // If we're performing recursive template instantiation, create our own 1660 // queue of pending implicit instantiations that we will instantiate later, 1661 // while we're still within our own instantiation context. 1662 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1663 if (Recursive) 1664 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1665 1666 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 1667 1668 // Introduce a new scope where local variable instantiations will be 1669 // recorded, unless we're actually a member function within a local 1670 // class, in which case we need to merge our results with the parent 1671 // scope (of the enclosing function). 1672 bool MergeWithParentScope = false; 1673 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 1674 MergeWithParentScope = Rec->isLocalClass(); 1675 1676 LocalInstantiationScope Scope(*this, MergeWithParentScope); 1677 1678 // Introduce the instantiated function parameters into the local 1679 // instantiation scope. 1680 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 1681 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 1682 Function->getParamDecl(I)); 1683 1684 // Enter the scope of this instantiation. We don't use 1685 // PushDeclContext because we don't have a scope. 1686 DeclContext *PreviousContext = CurContext; 1687 CurContext = Function; 1688 1689 MultiLevelTemplateArgumentList TemplateArgs = 1690 getTemplateInstantiationArgs(Function); 1691 1692 // If this is a constructor, instantiate the member initializers. 1693 if (const CXXConstructorDecl *Ctor = 1694 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 1695 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 1696 TemplateArgs); 1697 } 1698 1699 // Instantiate the function body. 1700 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs); 1701 1702 if (Body.isInvalid()) 1703 Function->setInvalidDecl(); 1704 1705 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 1706 /*IsInstantiation=*/true); 1707 1708 CurContext = PreviousContext; 1709 1710 DeclGroupRef DG(Function); 1711 Consumer.HandleTopLevelDecl(DG); 1712 1713 // This class may have local implicit instantiations that need to be 1714 // instantiation within this scope. 1715 PerformPendingImplicitInstantiations(/*LocalOnly=*/true); 1716 Scope.Exit(); 1717 1718 if (Recursive) { 1719 // Instantiate any pending implicit instantiations found during the 1720 // instantiation of this template. 1721 PerformPendingImplicitInstantiations(); 1722 1723 // Restore the set of pending implicit instantiations. 1724 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1725 } 1726} 1727 1728/// \brief Instantiate the definition of the given variable from its 1729/// template. 1730/// 1731/// \param PointOfInstantiation the point at which the instantiation was 1732/// required. Note that this is not precisely a "point of instantiation" 1733/// for the function, but it's close. 1734/// 1735/// \param Var the already-instantiated declaration of a static member 1736/// variable of a class template specialization. 1737/// 1738/// \param Recursive if true, recursively instantiates any functions that 1739/// are required by this instantiation. 1740/// 1741/// \param DefinitionRequired if true, then we are performing an explicit 1742/// instantiation where an out-of-line definition of the member variable 1743/// is required. Complain if there is no such definition. 1744void Sema::InstantiateStaticDataMemberDefinition( 1745 SourceLocation PointOfInstantiation, 1746 VarDecl *Var, 1747 bool Recursive, 1748 bool DefinitionRequired) { 1749 if (Var->isInvalidDecl()) 1750 return; 1751 1752 // Find the out-of-line definition of this static data member. 1753 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 1754 assert(Def && "This data member was not instantiated from a template?"); 1755 assert(Def->isStaticDataMember() && "Not a static data member?"); 1756 Def = Def->getOutOfLineDefinition(); 1757 1758 if (!Def) { 1759 // We did not find an out-of-line definition of this static data member, 1760 // so we won't perform any instantiation. Rather, we rely on the user to 1761 // instantiate this definition (or provide a specialization for it) in 1762 // another translation unit. 1763 if (DefinitionRequired) { 1764 Def = Var->getInstantiatedFromStaticDataMember(); 1765 Diag(PointOfInstantiation, 1766 diag::err_explicit_instantiation_undefined_member) 1767 << 2 << Var->getDeclName() << Var->getDeclContext(); 1768 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 1769 } 1770 1771 return; 1772 } 1773 1774 // Never instantiate an explicit specialization. 1775 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1776 return; 1777 1778 // C++0x [temp.explicit]p9: 1779 // Except for inline functions, other explicit instantiation declarations 1780 // have the effect of suppressing the implicit instantiation of the entity 1781 // to which they refer. 1782 if (Var->getTemplateSpecializationKind() 1783 == TSK_ExplicitInstantiationDeclaration) 1784 return; 1785 1786 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 1787 if (Inst) 1788 return; 1789 1790 // If we're performing recursive template instantiation, create our own 1791 // queue of pending implicit instantiations that we will instantiate later, 1792 // while we're still within our own instantiation context. 1793 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1794 if (Recursive) 1795 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1796 1797 // Enter the scope of this instantiation. We don't use 1798 // PushDeclContext because we don't have a scope. 1799 DeclContext *PreviousContext = CurContext; 1800 CurContext = Var->getDeclContext(); 1801 1802 VarDecl *OldVar = Var; 1803 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 1804 getTemplateInstantiationArgs(Var))); 1805 CurContext = PreviousContext; 1806 1807 if (Var) { 1808 Var->setPreviousDeclaration(OldVar); 1809 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 1810 assert(MSInfo && "Missing member specialization information?"); 1811 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 1812 MSInfo->getPointOfInstantiation()); 1813 DeclGroupRef DG(Var); 1814 Consumer.HandleTopLevelDecl(DG); 1815 } 1816 1817 if (Recursive) { 1818 // Instantiate any pending implicit instantiations found during the 1819 // instantiation of this template. 1820 PerformPendingImplicitInstantiations(); 1821 1822 // Restore the set of pending implicit instantiations. 1823 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1824 } 1825} 1826 1827void 1828Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 1829 const CXXConstructorDecl *Tmpl, 1830 const MultiLevelTemplateArgumentList &TemplateArgs) { 1831 1832 llvm::SmallVector<MemInitTy*, 4> NewInits; 1833 bool AnyErrors = false; 1834 1835 // Instantiate all the initializers. 1836 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 1837 InitsEnd = Tmpl->init_end(); 1838 Inits != InitsEnd; ++Inits) { 1839 CXXBaseOrMemberInitializer *Init = *Inits; 1840 1841 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this); 1842 llvm::SmallVector<SourceLocation, 4> CommaLocs; 1843 1844 // Instantiate all the arguments. 1845 Expr *InitE = Init->getInit(); 1846 if (!InitE) { 1847 // Nothing to instantiate; 1848 } else if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(InitE)) { 1849 if (InstantiateInitializationArguments(*this, ParenList->getExprs(), 1850 ParenList->getNumExprs(), 1851 TemplateArgs, CommaLocs, 1852 NewArgs)) { 1853 AnyErrors = true; 1854 continue; 1855 } 1856 } else { 1857 OwningExprResult InitArg = SubstExpr(InitE, TemplateArgs); 1858 if (InitArg.isInvalid()) { 1859 AnyErrors = true; 1860 continue; 1861 } 1862 1863 NewArgs.push_back(InitArg.release()); 1864 } 1865 1866 MemInitResult NewInit; 1867 if (Init->isBaseInitializer()) { 1868 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(), 1869 TemplateArgs, 1870 Init->getSourceLocation(), 1871 New->getDeclName()); 1872 if (!BaseTInfo) { 1873 AnyErrors = true; 1874 New->setInvalidDecl(); 1875 continue; 1876 } 1877 1878 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo, 1879 (Expr **)NewArgs.data(), 1880 NewArgs.size(), 1881 Init->getLParenLoc(), 1882 Init->getRParenLoc(), 1883 New->getParent()); 1884 } else if (Init->isMemberInitializer()) { 1885 FieldDecl *Member; 1886 1887 // Is this an anonymous union? 1888 if (FieldDecl *UnionInit = Init->getAnonUnionMember()) 1889 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs)); 1890 else 1891 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(), 1892 TemplateArgs)); 1893 1894 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 1895 NewArgs.size(), 1896 Init->getSourceLocation(), 1897 Init->getLParenLoc(), 1898 Init->getRParenLoc()); 1899 } 1900 1901 if (NewInit.isInvalid()) { 1902 AnyErrors = true; 1903 New->setInvalidDecl(); 1904 } else { 1905 // FIXME: It would be nice if ASTOwningVector had a release function. 1906 NewArgs.take(); 1907 1908 NewInits.push_back((MemInitTy *)NewInit.get()); 1909 } 1910 } 1911 1912 // Assign all the initializers to the new constructor. 1913 ActOnMemInitializers(DeclPtrTy::make(New), 1914 /*FIXME: ColonLoc */ 1915 SourceLocation(), 1916 NewInits.data(), NewInits.size(), 1917 AnyErrors); 1918} 1919 1920// TODO: this could be templated if the various decl types used the 1921// same method name. 1922static bool isInstantiationOf(ClassTemplateDecl *Pattern, 1923 ClassTemplateDecl *Instance) { 1924 Pattern = Pattern->getCanonicalDecl(); 1925 1926 do { 1927 Instance = Instance->getCanonicalDecl(); 1928 if (Pattern == Instance) return true; 1929 Instance = Instance->getInstantiatedFromMemberTemplate(); 1930 } while (Instance); 1931 1932 return false; 1933} 1934 1935static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 1936 FunctionTemplateDecl *Instance) { 1937 Pattern = Pattern->getCanonicalDecl(); 1938 1939 do { 1940 Instance = Instance->getCanonicalDecl(); 1941 if (Pattern == Instance) return true; 1942 Instance = Instance->getInstantiatedFromMemberTemplate(); 1943 } while (Instance); 1944 1945 return false; 1946} 1947 1948static bool 1949isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 1950 ClassTemplatePartialSpecializationDecl *Instance) { 1951 Pattern 1952 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 1953 do { 1954 Instance = cast<ClassTemplatePartialSpecializationDecl>( 1955 Instance->getCanonicalDecl()); 1956 if (Pattern == Instance) 1957 return true; 1958 Instance = Instance->getInstantiatedFromMember(); 1959 } while (Instance); 1960 1961 return false; 1962} 1963 1964static bool isInstantiationOf(CXXRecordDecl *Pattern, 1965 CXXRecordDecl *Instance) { 1966 Pattern = Pattern->getCanonicalDecl(); 1967 1968 do { 1969 Instance = Instance->getCanonicalDecl(); 1970 if (Pattern == Instance) return true; 1971 Instance = Instance->getInstantiatedFromMemberClass(); 1972 } while (Instance); 1973 1974 return false; 1975} 1976 1977static bool isInstantiationOf(FunctionDecl *Pattern, 1978 FunctionDecl *Instance) { 1979 Pattern = Pattern->getCanonicalDecl(); 1980 1981 do { 1982 Instance = Instance->getCanonicalDecl(); 1983 if (Pattern == Instance) return true; 1984 Instance = Instance->getInstantiatedFromMemberFunction(); 1985 } while (Instance); 1986 1987 return false; 1988} 1989 1990static bool isInstantiationOf(EnumDecl *Pattern, 1991 EnumDecl *Instance) { 1992 Pattern = Pattern->getCanonicalDecl(); 1993 1994 do { 1995 Instance = Instance->getCanonicalDecl(); 1996 if (Pattern == Instance) return true; 1997 Instance = Instance->getInstantiatedFromMemberEnum(); 1998 } while (Instance); 1999 2000 return false; 2001} 2002 2003static bool isInstantiationOf(UsingShadowDecl *Pattern, 2004 UsingShadowDecl *Instance, 2005 ASTContext &C) { 2006 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 2007} 2008 2009static bool isInstantiationOf(UsingDecl *Pattern, 2010 UsingDecl *Instance, 2011 ASTContext &C) { 2012 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2013} 2014 2015static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 2016 UsingDecl *Instance, 2017 ASTContext &C) { 2018 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2019} 2020 2021static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 2022 UsingDecl *Instance, 2023 ASTContext &C) { 2024 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2025} 2026 2027static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 2028 VarDecl *Instance) { 2029 assert(Instance->isStaticDataMember()); 2030 2031 Pattern = Pattern->getCanonicalDecl(); 2032 2033 do { 2034 Instance = Instance->getCanonicalDecl(); 2035 if (Pattern == Instance) return true; 2036 Instance = Instance->getInstantiatedFromStaticDataMember(); 2037 } while (Instance); 2038 2039 return false; 2040} 2041 2042// Other is the prospective instantiation 2043// D is the prospective pattern 2044static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 2045 if (D->getKind() != Other->getKind()) { 2046 if (UnresolvedUsingTypenameDecl *UUD 2047 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 2048 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2049 return isInstantiationOf(UUD, UD, Ctx); 2050 } 2051 } 2052 2053 if (UnresolvedUsingValueDecl *UUD 2054 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 2055 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2056 return isInstantiationOf(UUD, UD, Ctx); 2057 } 2058 } 2059 2060 return false; 2061 } 2062 2063 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 2064 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 2065 2066 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 2067 return isInstantiationOf(cast<FunctionDecl>(D), Function); 2068 2069 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 2070 return isInstantiationOf(cast<EnumDecl>(D), Enum); 2071 2072 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 2073 if (Var->isStaticDataMember()) 2074 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 2075 2076 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 2077 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 2078 2079 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 2080 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 2081 2082 if (ClassTemplatePartialSpecializationDecl *PartialSpec 2083 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 2084 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 2085 PartialSpec); 2086 2087 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 2088 if (!Field->getDeclName()) { 2089 // This is an unnamed field. 2090 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 2091 cast<FieldDecl>(D); 2092 } 2093 } 2094 2095 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 2096 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 2097 2098 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 2099 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 2100 2101 return D->getDeclName() && isa<NamedDecl>(Other) && 2102 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 2103} 2104 2105template<typename ForwardIterator> 2106static NamedDecl *findInstantiationOf(ASTContext &Ctx, 2107 NamedDecl *D, 2108 ForwardIterator first, 2109 ForwardIterator last) { 2110 for (; first != last; ++first) 2111 if (isInstantiationOf(Ctx, D, *first)) 2112 return cast<NamedDecl>(*first); 2113 2114 return 0; 2115} 2116 2117/// \brief Finds the instantiation of the given declaration context 2118/// within the current instantiation. 2119/// 2120/// \returns NULL if there was an error 2121DeclContext *Sema::FindInstantiatedContext(DeclContext* DC, 2122 const MultiLevelTemplateArgumentList &TemplateArgs) { 2123 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 2124 Decl* ID = FindInstantiatedDecl(D, TemplateArgs); 2125 return cast_or_null<DeclContext>(ID); 2126 } else return DC; 2127} 2128 2129/// \brief Find the instantiation of the given declaration within the 2130/// current instantiation. 2131/// 2132/// This routine is intended to be used when \p D is a declaration 2133/// referenced from within a template, that needs to mapped into the 2134/// corresponding declaration within an instantiation. For example, 2135/// given: 2136/// 2137/// \code 2138/// template<typename T> 2139/// struct X { 2140/// enum Kind { 2141/// KnownValue = sizeof(T) 2142/// }; 2143/// 2144/// bool getKind() const { return KnownValue; } 2145/// }; 2146/// 2147/// template struct X<int>; 2148/// \endcode 2149/// 2150/// In the instantiation of X<int>::getKind(), we need to map the 2151/// EnumConstantDecl for KnownValue (which refers to 2152/// X<T>::<Kind>::KnownValue) to its instantiation 2153/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 2154/// this mapping from within the instantiation of X<int>. 2155NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D, 2156 const MultiLevelTemplateArgumentList &TemplateArgs) { 2157 DeclContext *ParentDC = D->getDeclContext(); 2158 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 2159 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 2160 ParentDC->isFunctionOrMethod()) { 2161 // D is a local of some kind. Look into the map of local 2162 // declarations to their instantiations. 2163 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 2164 } 2165 2166 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 2167 if (!Record->isDependentContext()) 2168 return D; 2169 2170 // If the RecordDecl is actually the injected-class-name or a "templated" 2171 // declaration for a class template or class template partial 2172 // specialization, substitute into the injected-class-name of the 2173 // class template or partial specialization to find the new DeclContext. 2174 QualType T; 2175 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 2176 2177 if (ClassTemplate) { 2178 T = ClassTemplate->getInjectedClassNameType(Context); 2179 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2180 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 2181 T = Context.getTypeDeclType(Record); 2182 ClassTemplate = PartialSpec->getSpecializedTemplate(); 2183 } 2184 2185 if (!T.isNull()) { 2186 // Substitute into the injected-class-name to get the type corresponding 2187 // to the instantiation we want. This substitution should never fail, 2188 // since we know we can instantiate the injected-class-name or we wouldn't 2189 // have gotten to the injected-class-name! 2190 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra 2191 // instantiation in the common case? 2192 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName()); 2193 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail."); 2194 2195 if (!T->isDependentType()) { 2196 assert(T->isRecordType() && "Instantiation must produce a record type"); 2197 return T->getAs<RecordType>()->getDecl(); 2198 } 2199 2200 // We are performing "partial" template instantiation to create the 2201 // member declarations for the members of a class template 2202 // specialization. Therefore, D is actually referring to something in 2203 // the current instantiation. Look through the current context, 2204 // which contains actual instantiations, to find the instantiation of 2205 // the "current instantiation" that D refers to. 2206 for (DeclContext *DC = CurContext; !DC->isFileContext(); 2207 DC = DC->getParent()) { 2208 if (ClassTemplateSpecializationDecl *Spec 2209 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 2210 if (isInstantiationOf(ClassTemplate, 2211 Spec->getSpecializedTemplate())) 2212 return Spec; 2213 } 2214 2215 assert(false && 2216 "Unable to find declaration for the current instantiation"); 2217 return Record; 2218 } 2219 2220 // Fall through to deal with other dependent record types (e.g., 2221 // anonymous unions in class templates). 2222 } 2223 2224 if (!ParentDC->isDependentContext()) 2225 return D; 2226 2227 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs); 2228 if (!ParentDC) 2229 return 0; 2230 2231 if (ParentDC != D->getDeclContext()) { 2232 // We performed some kind of instantiation in the parent context, 2233 // so now we need to look into the instantiated parent context to 2234 // find the instantiation of the declaration D. 2235 NamedDecl *Result = 0; 2236 if (D->getDeclName()) { 2237 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 2238 Result = findInstantiationOf(Context, D, Found.first, Found.second); 2239 } else { 2240 // Since we don't have a name for the entity we're looking for, 2241 // our only option is to walk through all of the declarations to 2242 // find that name. This will occur in a few cases: 2243 // 2244 // - anonymous struct/union within a template 2245 // - unnamed class/struct/union/enum within a template 2246 // 2247 // FIXME: Find a better way to find these instantiations! 2248 Result = findInstantiationOf(Context, D, 2249 ParentDC->decls_begin(), 2250 ParentDC->decls_end()); 2251 } 2252 2253 // UsingShadowDecls can instantiate to nothing because of using hiding. 2254 assert((Result || isa<UsingShadowDecl>(D)) 2255 && "Unable to find instantiation of declaration!"); 2256 2257 D = Result; 2258 } 2259 2260 return D; 2261} 2262 2263/// \brief Performs template instantiation for all implicit template 2264/// instantiations we have seen until this point. 2265void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) { 2266 while (!PendingLocalImplicitInstantiations.empty() || 2267 (!LocalOnly && !PendingImplicitInstantiations.empty())) { 2268 PendingImplicitInstantiation Inst; 2269 2270 if (PendingLocalImplicitInstantiations.empty()) { 2271 Inst = PendingImplicitInstantiations.front(); 2272 PendingImplicitInstantiations.pop_front(); 2273 } else { 2274 Inst = PendingLocalImplicitInstantiations.front(); 2275 PendingLocalImplicitInstantiations.pop_front(); 2276 } 2277 2278 // Instantiate function definitions 2279 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 2280 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function), 2281 Function->getLocation(), *this, 2282 Context.getSourceManager(), 2283 "instantiating function definition"); 2284 2285 if (!Function->getBody()) 2286 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 2287 continue; 2288 } 2289 2290 // Instantiate static data member definitions. 2291 VarDecl *Var = cast<VarDecl>(Inst.first); 2292 assert(Var->isStaticDataMember() && "Not a static data member?"); 2293 2294 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var), 2295 Var->getLocation(), *this, 2296 Context.getSourceManager(), 2297 "instantiating static data member " 2298 "definition"); 2299 2300 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 2301 } 2302} 2303