SemaTemplateInstantiateDecl.cpp revision 72f6d678c8de9f3a770e8ae5fc4979abf3940668
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 "clang/Basic/PrettyStackTrace.h" 19#include "clang/Lex/Preprocessor.h" 20#include "llvm/Support/Compiler.h" 21 22using namespace clang; 23 24namespace { 25 class VISIBILITY_HIDDEN TemplateDeclInstantiator 26 : public DeclVisitor<TemplateDeclInstantiator, Decl *> { 27 Sema &SemaRef; 28 DeclContext *Owner; 29 const MultiLevelTemplateArgumentList &TemplateArgs; 30 31 public: 32 typedef Sema::OwningExprResult OwningExprResult; 33 34 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, 35 const MultiLevelTemplateArgumentList &TemplateArgs) 36 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { } 37 38 // FIXME: Once we get closer to completion, replace these manually-written 39 // declarations with automatically-generated ones from 40 // clang/AST/DeclNodes.def. 41 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); 42 Decl *VisitNamespaceDecl(NamespaceDecl *D); 43 Decl *VisitTypedefDecl(TypedefDecl *D); 44 Decl *VisitVarDecl(VarDecl *D); 45 Decl *VisitFieldDecl(FieldDecl *D); 46 Decl *VisitStaticAssertDecl(StaticAssertDecl *D); 47 Decl *VisitEnumDecl(EnumDecl *D); 48 Decl *VisitEnumConstantDecl(EnumConstantDecl *D); 49 Decl *VisitFriendDecl(FriendDecl *D); 50 Decl *VisitFunctionDecl(FunctionDecl *D); 51 Decl *VisitCXXRecordDecl(CXXRecordDecl *D); 52 Decl *VisitCXXMethodDecl(CXXMethodDecl *D, 53 TemplateParameterList *TemplateParams = 0); 54 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 55 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 56 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 57 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 58 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D); 59 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D); 60 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 61 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 62 Decl *VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D); 63 64 // Base case. FIXME: Remove once we can instantiate everything. 65 Decl *VisitDecl(Decl *) { 66 assert(false && "Template instantiation of unknown declaration kind!"); 67 return 0; 68 } 69 70 const LangOptions &getLangOptions() { 71 return SemaRef.getLangOptions(); 72 } 73 74 // Helper functions for instantiating methods. 75 QualType SubstFunctionType(FunctionDecl *D, 76 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 77 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl); 78 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 79 80 TemplateParameterList * 81 SubstTemplateParams(TemplateParameterList *List); 82 }; 83} 84 85Decl * 86TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 87 assert(false && "Translation units cannot be instantiated"); 88 return D; 89} 90 91Decl * 92TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 93 assert(false && "Namespaces cannot be instantiated"); 94 return D; 95} 96 97Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 98 bool Invalid = false; 99 QualType T = D->getUnderlyingType(); 100 if (T->isDependentType()) { 101 T = SemaRef.SubstType(T, TemplateArgs, 102 D->getLocation(), D->getDeclName()); 103 if (T.isNull()) { 104 Invalid = true; 105 T = SemaRef.Context.IntTy; 106 } 107 } 108 109 // Create the new typedef 110 TypedefDecl *Typedef 111 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 112 D->getIdentifier(), T); 113 if (Invalid) 114 Typedef->setInvalidDecl(); 115 116 Owner->addDecl(Typedef); 117 118 return Typedef; 119} 120 121Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 122 // Do substitution on the type of the declaration 123 QualType T = SemaRef.SubstType(D->getType(), TemplateArgs, 124 D->getTypeSpecStartLoc(), 125 D->getDeclName()); 126 if (T.isNull()) 127 return 0; 128 129 // Build the instantiated declaration 130 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 131 D->getLocation(), D->getIdentifier(), 132 T, D->getDeclaratorInfo(), 133 D->getStorageClass()); 134 Var->setThreadSpecified(D->isThreadSpecified()); 135 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 136 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 137 138 // If we are instantiating a static data member defined 139 // out-of-line, the instantiation will have the same lexical 140 // context (which will be a namespace scope) as the template. 141 if (D->isOutOfLine()) 142 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 143 144 // FIXME: In theory, we could have a previous declaration for variables that 145 // are not static data members. 146 bool Redeclaration = false; 147 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration); 148 149 if (D->isOutOfLine()) { 150 D->getLexicalDeclContext()->addDecl(Var); 151 Owner->makeDeclVisibleInContext(Var); 152 } else { 153 Owner->addDecl(Var); 154 } 155 156 if (D->getInit()) { 157 OwningExprResult Init 158 = SemaRef.SubstExpr(D->getInit(), TemplateArgs); 159 if (Init.isInvalid()) 160 Var->setInvalidDecl(); 161 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) { 162 // FIXME: We're faking all of the comma locations, which is suboptimal. 163 // Do we even need these comma locations? 164 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs; 165 if (PLE->getNumExprs() > 0) { 166 FakeCommaLocs.reserve(PLE->getNumExprs() - 1); 167 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) { 168 Expr *E = PLE->getExpr(I)->Retain(); 169 FakeCommaLocs.push_back( 170 SemaRef.PP.getLocForEndOfToken(E->getLocEnd())); 171 } 172 PLE->getExpr(PLE->getNumExprs() - 1)->Retain(); 173 } 174 175 // Add the direct initializer to the declaration. 176 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var), 177 PLE->getLParenLoc(), 178 Sema::MultiExprArg(SemaRef, 179 (void**)PLE->getExprs(), 180 PLE->getNumExprs()), 181 FakeCommaLocs.data(), 182 PLE->getRParenLoc()); 183 184 // When Init is destroyed, it will destroy the instantiated ParenListExpr; 185 // we've explicitly retained all of its subexpressions already. 186 } else 187 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init), 188 D->hasCXXDirectInitializer()); 189 } else if (!Var->isStaticDataMember() || Var->isOutOfLine()) 190 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 191 192 // Link instantiations of static data members back to the template from 193 // which they were instantiated. 194 if (Var->isStaticDataMember()) 195 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D); 196 197 return Var; 198} 199 200Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 201 bool Invalid = false; 202 QualType T = D->getType(); 203 if (T->isDependentType()) { 204 T = SemaRef.SubstType(T, TemplateArgs, 205 D->getLocation(), D->getDeclName()); 206 if (!T.isNull() && T->isFunctionType()) { 207 // C++ [temp.arg.type]p3: 208 // If a declaration acquires a function type through a type 209 // dependent on a template-parameter and this causes a 210 // declaration that does not use the syntactic form of a 211 // function declarator to have function type, the program is 212 // ill-formed. 213 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 214 << T; 215 T = QualType(); 216 Invalid = true; 217 } 218 } 219 220 Expr *BitWidth = D->getBitWidth(); 221 if (Invalid) 222 BitWidth = 0; 223 else if (BitWidth) { 224 // The bit-width expression is not potentially evaluated. 225 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 226 227 OwningExprResult InstantiatedBitWidth 228 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 229 if (InstantiatedBitWidth.isInvalid()) { 230 Invalid = true; 231 BitWidth = 0; 232 } else 233 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 234 } 235 236 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T, 237 D->getDeclaratorInfo(), 238 cast<RecordDecl>(Owner), 239 D->getLocation(), 240 D->isMutable(), 241 BitWidth, 242 D->getTypeSpecStartLoc(), 243 D->getAccess(), 244 0); 245 if (Field) { 246 if (Invalid) 247 Field->setInvalidDecl(); 248 249 if (!Field->getDeclName()) { 250 // Keep track of where this decl came from. 251 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 252 } 253 254 Owner->addDecl(Field); 255 } 256 257 return Field; 258} 259 260Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 261 FriendDecl::FriendUnion FU; 262 263 // Handle friend type expressions by simply substituting template 264 // parameters into the pattern type. 265 if (Type *Ty = D->getFriendType()) { 266 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs, 267 D->getLocation(), DeclarationName()); 268 if (T.isNull()) return 0; 269 270 assert(getLangOptions().CPlusPlus0x || T->isRecordType()); 271 FU = T.getTypePtr(); 272 273 // Handle everything else by appropriate substitution. 274 } else { 275 NamedDecl *ND = D->getFriendDecl(); 276 assert(ND && "friend decl must be a decl or a type!"); 277 278 Decl *NewND = Visit(ND); 279 if (!NewND) return 0; 280 281 FU = cast<NamedDecl>(NewND); 282 } 283 284 FriendDecl *FD = 285 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU, 286 D->getFriendLoc()); 287 FD->setAccess(AS_public); 288 Owner->addDecl(FD); 289 return FD; 290} 291 292Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 293 Expr *AssertExpr = D->getAssertExpr(); 294 295 // The expression in a static assertion is not potentially evaluated. 296 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 297 298 OwningExprResult InstantiatedAssertExpr 299 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 300 if (InstantiatedAssertExpr.isInvalid()) 301 return 0; 302 303 OwningExprResult Message(SemaRef, D->getMessage()); 304 D->getMessage()->Retain(); 305 Decl *StaticAssert 306 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 307 move(InstantiatedAssertExpr), 308 move(Message)).getAs<Decl>(); 309 return StaticAssert; 310} 311 312Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 313 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 314 D->getLocation(), D->getIdentifier(), 315 D->getTagKeywordLoc(), 316 /*PrevDecl=*/0); 317 Enum->setInstantiationOfMemberEnum(D); 318 Enum->setAccess(D->getAccess()); 319 Owner->addDecl(Enum); 320 Enum->startDefinition(); 321 322 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators; 323 324 EnumConstantDecl *LastEnumConst = 0; 325 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 326 ECEnd = D->enumerator_end(); 327 EC != ECEnd; ++EC) { 328 // The specified value for the enumerator. 329 OwningExprResult Value = SemaRef.Owned((Expr *)0); 330 if (Expr *UninstValue = EC->getInitExpr()) { 331 // The enumerator's value expression is not potentially evaluated. 332 EnterExpressionEvaluationContext Unevaluated(SemaRef, 333 Action::Unevaluated); 334 335 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 336 } 337 338 // Drop the initial value and continue. 339 bool isInvalid = false; 340 if (Value.isInvalid()) { 341 Value = SemaRef.Owned((Expr *)0); 342 isInvalid = true; 343 } 344 345 EnumConstantDecl *EnumConst 346 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 347 EC->getLocation(), EC->getIdentifier(), 348 move(Value)); 349 350 if (isInvalid) { 351 if (EnumConst) 352 EnumConst->setInvalidDecl(); 353 Enum->setInvalidDecl(); 354 } 355 356 if (EnumConst) { 357 Enum->addDecl(EnumConst); 358 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 359 LastEnumConst = EnumConst; 360 } 361 } 362 363 // FIXME: Fixup LBraceLoc and RBraceLoc 364 // FIXME: Empty Scope and AttributeList (required to handle attribute packed). 365 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 366 Sema::DeclPtrTy::make(Enum), 367 &Enumerators[0], Enumerators.size(), 368 0, 0); 369 370 return Enum; 371} 372 373Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 374 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 375 return 0; 376} 377 378Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 379 TemplateParameterList *TempParams = D->getTemplateParameters(); 380 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 381 if (!InstParams) 382 return NULL; 383 384 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 385 CXXRecordDecl *RecordInst 386 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner, 387 Pattern->getLocation(), Pattern->getIdentifier(), 388 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL); 389 390 ClassTemplateDecl *Inst 391 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 392 D->getIdentifier(), InstParams, RecordInst, 0); 393 RecordInst->setDescribedClassTemplate(Inst); 394 Inst->setAccess(D->getAccess()); 395 Inst->setInstantiatedFromMemberTemplate(D); 396 397 Owner->addDecl(Inst); 398 return Inst; 399} 400 401Decl * 402TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 403 TemplateParameterList *TempParams = D->getTemplateParameters(); 404 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 405 if (!InstParams) 406 return NULL; 407 408 // FIXME: Handle instantiation of nested function templates that aren't 409 // member function templates. This could happen inside a FriendDecl. 410 assert(isa<CXXMethodDecl>(D->getTemplatedDecl())); 411 CXXMethodDecl *InstMethod 412 = cast_or_null<CXXMethodDecl>( 413 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()), 414 InstParams)); 415 if (!InstMethod) 416 return 0; 417 418 // Link the instantiated function template declaration to the function 419 // template from which it was instantiated. 420 FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate(); 421 assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!"); 422 InstTemplate->setInstantiatedFromMemberTemplate(D); 423 Owner->addDecl(InstTemplate); 424 return InstTemplate; 425} 426 427Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 428 CXXRecordDecl *PrevDecl = 0; 429 if (D->isInjectedClassName()) 430 PrevDecl = cast<CXXRecordDecl>(Owner); 431 432 CXXRecordDecl *Record 433 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 434 D->getLocation(), D->getIdentifier(), 435 D->getTagKeywordLoc(), PrevDecl); 436 Record->setImplicit(D->isImplicit()); 437 // FIXME: Check against AS_none is an ugly hack to work around the issue that 438 // the tag decls introduced by friend class declarations don't have an access 439 // specifier. Remove once this area of the code gets sorted out. 440 if (D->getAccess() != AS_none) 441 Record->setAccess(D->getAccess()); 442 if (!D->isInjectedClassName()) 443 Record->setInstantiationOfMemberClass(D); 444 445 // If the original function was part of a friend declaration, 446 // inherit its namespace state. 447 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 448 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 449 450 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion()); 451 452 Owner->addDecl(Record); 453 return Record; 454} 455 456/// Normal class members are of more specific types and therefore 457/// don't make it here. This function serves two purposes: 458/// 1) instantiating function templates 459/// 2) substituting friend declarations 460/// FIXME: preserve function definitions in case #2 461Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 462 // Check whether there is already a function template specialization for 463 // this declaration. 464 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 465 void *InsertPos = 0; 466 if (FunctionTemplate) { 467 llvm::FoldingSetNodeID ID; 468 FunctionTemplateSpecializationInfo::Profile(ID, 469 TemplateArgs.getInnermost().getFlatArgumentList(), 470 TemplateArgs.getInnermost().flat_size(), 471 SemaRef.Context); 472 473 FunctionTemplateSpecializationInfo *Info 474 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 475 InsertPos); 476 477 // If we already have a function template specialization, return it. 478 if (Info) 479 return Info->Function; 480 } 481 482 Sema::LocalInstantiationScope Scope(SemaRef); 483 484 llvm::SmallVector<ParmVarDecl *, 4> Params; 485 QualType T = SubstFunctionType(D, Params); 486 if (T.isNull()) 487 return 0; 488 489 // Build the instantiated method declaration. 490 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext()); 491 FunctionDecl *Function = 492 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(), 493 D->getDeclName(), T, D->getDeclaratorInfo(), 494 D->getStorageClass(), 495 D->isInline(), D->hasWrittenPrototype()); 496 Function->setLexicalDeclContext(Owner); 497 498 // Attach the parameters 499 for (unsigned P = 0; P < Params.size(); ++P) 500 Params[P]->setOwningFunction(Function); 501 Function->setParams(SemaRef.Context, Params.data(), Params.size()); 502 503 // If the original function was part of a friend declaration, 504 // inherit its namespace state and add it to the owner. 505 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) { 506 bool WasDeclared = (FOK == Decl::FOK_Declared); 507 Function->setObjectOfFriendDecl(WasDeclared); 508 if (!Owner->isDependentContext()) 509 DC->makeDeclVisibleInContext(Function, /* Recoverable = */ false); 510 511 Function->setInstantiationOfMemberFunction(D); 512 } 513 514 if (InitFunctionInstantiation(Function, D)) 515 Function->setInvalidDecl(); 516 517 bool Redeclaration = false; 518 bool OverloadableAttrRequired = false; 519 NamedDecl *PrevDecl = 0; 520 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration, 521 /*FIXME:*/OverloadableAttrRequired); 522 523 if (FunctionTemplate) { 524 // Record this function template specialization. 525 Function->setFunctionTemplateSpecialization(SemaRef.Context, 526 FunctionTemplate, 527 &TemplateArgs.getInnermost(), 528 InsertPos); 529 } 530 531 return Function; 532} 533 534Decl * 535TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 536 TemplateParameterList *TemplateParams) { 537 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 538 void *InsertPos = 0; 539 if (FunctionTemplate && !TemplateParams) { 540 // We are creating a function template specialization from a function 541 // template. Check whether there is already a function template 542 // specialization for this particular set of template arguments. 543 llvm::FoldingSetNodeID ID; 544 FunctionTemplateSpecializationInfo::Profile(ID, 545 TemplateArgs.getInnermost().getFlatArgumentList(), 546 TemplateArgs.getInnermost().flat_size(), 547 SemaRef.Context); 548 549 FunctionTemplateSpecializationInfo *Info 550 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 551 InsertPos); 552 553 // If we already have a function template specialization, return it. 554 if (Info) 555 return Info->Function; 556 } 557 558 Sema::LocalInstantiationScope Scope(SemaRef); 559 560 llvm::SmallVector<ParmVarDecl *, 4> Params; 561 QualType T = SubstFunctionType(D, Params); 562 if (T.isNull()) 563 return 0; 564 565 // Build the instantiated method declaration. 566 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 567 CXXMethodDecl *Method = 0; 568 569 DeclarationName Name = D->getDeclName(); 570 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 571 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 572 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName( 573 SemaRef.Context.getCanonicalType(ClassTy)); 574 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 575 Constructor->getLocation(), 576 Name, T, 577 Constructor->getDeclaratorInfo(), 578 Constructor->isExplicit(), 579 Constructor->isInline(), false); 580 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 581 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 582 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName( 583 SemaRef.Context.getCanonicalType(ClassTy)); 584 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 585 Destructor->getLocation(), Name, 586 T, Destructor->isInline(), false); 587 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 588 CanQualType ConvTy 589 = SemaRef.Context.getCanonicalType( 590 T->getAsFunctionType()->getResultType()); 591 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName( 592 ConvTy); 593 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 594 Conversion->getLocation(), Name, 595 T, Conversion->getDeclaratorInfo(), 596 Conversion->isInline(), 597 Conversion->isExplicit()); 598 } else { 599 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 600 D->getDeclName(), T, D->getDeclaratorInfo(), 601 D->isStatic(), D->isInline()); 602 } 603 604 if (TemplateParams) { 605 // Our resulting instantiation is actually a function template, since we 606 // are substituting only the outer template parameters. For example, given 607 // 608 // template<typename T> 609 // struct X { 610 // template<typename U> void f(T, U); 611 // }; 612 // 613 // X<int> x; 614 // 615 // We are instantiating the member template "f" within X<int>, which means 616 // substituting int for T, but leaving "f" as a member function template. 617 // Build the function template itself. 618 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 619 Method->getLocation(), 620 Method->getDeclName(), 621 TemplateParams, Method); 622 if (D->isOutOfLine()) 623 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 624 Method->setDescribedFunctionTemplate(FunctionTemplate); 625 } else if (!FunctionTemplate) 626 Method->setInstantiationOfMemberFunction(D); 627 628 // If we are instantiating a member function defined 629 // out-of-line, the instantiation will have the same lexical 630 // context (which will be a namespace scope) as the template. 631 if (D->isOutOfLine()) 632 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 633 634 // Attach the parameters 635 for (unsigned P = 0; P < Params.size(); ++P) 636 Params[P]->setOwningFunction(Method); 637 Method->setParams(SemaRef.Context, Params.data(), Params.size()); 638 639 if (InitMethodInstantiation(Method, D)) 640 Method->setInvalidDecl(); 641 642 NamedDecl *PrevDecl = 0; 643 644 if (!FunctionTemplate || TemplateParams) { 645 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name, 646 Sema::LookupOrdinaryName, true); 647 648 // In C++, the previous declaration we find might be a tag type 649 // (class or enum). In this case, the new declaration will hide the 650 // tag type. Note that this does does not apply if we're declaring a 651 // typedef (C++ [dcl.typedef]p4). 652 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 653 PrevDecl = 0; 654 } 655 656 if (FunctionTemplate && !TemplateParams) 657 // Record this function template specialization. 658 Method->setFunctionTemplateSpecialization(SemaRef.Context, 659 FunctionTemplate, 660 &TemplateArgs.getInnermost(), 661 InsertPos); 662 663 bool Redeclaration = false; 664 bool OverloadableAttrRequired = false; 665 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration, 666 /*FIXME:*/OverloadableAttrRequired); 667 668 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl)) 669 Owner->addDecl(Method); 670 671 return Method; 672} 673 674Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 675 return VisitCXXMethodDecl(D); 676} 677 678Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 679 return VisitCXXMethodDecl(D); 680} 681 682Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 683 return VisitCXXMethodDecl(D); 684} 685 686ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 687 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs, 688 D->getLocation(), D->getDeclName()); 689 if (OrigT.isNull()) 690 return 0; 691 692 QualType T = SemaRef.adjustParameterType(OrigT); 693 694 // Allocate the parameter 695 ParmVarDecl *Param = 0; 696 if (T == OrigT) 697 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(), 698 D->getIdentifier(), T, D->getDeclaratorInfo(), 699 D->getStorageClass(), 0); 700 else 701 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner, 702 D->getLocation(), D->getIdentifier(), 703 T, D->getDeclaratorInfo(), OrigT, 704 D->getStorageClass(), 0); 705 706 // Mark the default argument as being uninstantiated. 707 if (Expr *Arg = D->getDefaultArg()) 708 Param->setUninstantiatedDefaultArg(Arg); 709 710 // Note: we don't try to instantiate function parameters until after 711 // we've instantiated the function's type. Therefore, we don't have 712 // to check for 'void' parameter types here. 713 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 714 return Param; 715} 716 717Decl * 718TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) { 719 // Since parameter types can decay either before or after 720 // instantiation, we simply treat OriginalParmVarDecls as 721 // ParmVarDecls the same way, and create one or the other depending 722 // on what happens after template instantiation. 723 return VisitParmVarDecl(D); 724} 725 726Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 727 TemplateTypeParmDecl *D) { 728 // TODO: don't always clone when decls are refcounted. 729 const Type* T = D->getTypeForDecl(); 730 assert(T->isTemplateTypeParmType()); 731 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>(); 732 733 TemplateTypeParmDecl *Inst = 734 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 735 TTPT->getDepth(), TTPT->getIndex(), 736 TTPT->getName(), 737 D->wasDeclaredWithTypename(), 738 D->isParameterPack()); 739 740 if (D->hasDefaultArgument()) { 741 QualType DefaultPattern = D->getDefaultArgument(); 742 QualType DefaultInst 743 = SemaRef.SubstType(DefaultPattern, TemplateArgs, 744 D->getDefaultArgumentLoc(), 745 D->getDeclName()); 746 747 Inst->setDefaultArgument(DefaultInst, 748 D->getDefaultArgumentLoc(), 749 D->defaultArgumentWasInherited() /* preserve? */); 750 } 751 752 return Inst; 753} 754 755Decl * 756TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) { 757 NestedNameSpecifier *NNS = 758 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 759 D->getTargetNestedNameRange(), 760 TemplateArgs); 761 if (!NNS) 762 return 0; 763 764 CXXScopeSpec SS; 765 SS.setRange(D->getTargetNestedNameRange()); 766 SS.setScopeRep(NNS); 767 768 NamedDecl *UD = 769 SemaRef.BuildUsingDeclaration(D->getLocation(), SS, 770 D->getTargetNameLocation(), 771 D->getTargetName(), 0, D->isTypeName()); 772 if (UD) 773 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD), 774 D); 775 return UD; 776} 777 778Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 779 const MultiLevelTemplateArgumentList &TemplateArgs) { 780 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 781 return Instantiator.Visit(D); 782} 783 784/// \brief Instantiates a nested template parameter list in the current 785/// instantiation context. 786/// 787/// \param L The parameter list to instantiate 788/// 789/// \returns NULL if there was an error 790TemplateParameterList * 791TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 792 // Get errors for all the parameters before bailing out. 793 bool Invalid = false; 794 795 unsigned N = L->size(); 796 typedef llvm::SmallVector<Decl*,8> ParamVector; 797 ParamVector Params; 798 Params.reserve(N); 799 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 800 PI != PE; ++PI) { 801 Decl *D = Visit(*PI); 802 Params.push_back(D); 803 Invalid = Invalid || !D; 804 } 805 806 // Clean up if we had an error. 807 if (Invalid) { 808 for (ParamVector::iterator PI = Params.begin(), PE = Params.end(); 809 PI != PE; ++PI) 810 if (*PI) 811 (*PI)->Destroy(SemaRef.Context); 812 return NULL; 813 } 814 815 TemplateParameterList *InstL 816 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 817 L->getLAngleLoc(), &Params.front(), N, 818 L->getRAngleLoc()); 819 return InstL; 820} 821 822/// \brief Does substitution on the type of the given function, including 823/// all of the function parameters. 824/// 825/// \param D The function whose type will be the basis of the substitution 826/// 827/// \param Params the instantiated parameter declarations 828 829/// \returns the instantiated function's type if successful, a NULL 830/// type if there was an error. 831QualType 832TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 833 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 834 bool InvalidDecl = false; 835 836 // Substitute all of the function's formal parameter types. 837 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs); 838 llvm::SmallVector<QualType, 4> ParamTys; 839 for (FunctionDecl::param_iterator P = D->param_begin(), 840 PEnd = D->param_end(); 841 P != PEnd; ++P) { 842 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { 843 if (PInst->getType()->isVoidType()) { 844 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); 845 PInst->setInvalidDecl(); 846 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), 847 PInst->getType(), 848 diag::err_abstract_type_in_decl, 849 Sema::AbstractParamType)) 850 PInst->setInvalidDecl(); 851 852 Params.push_back(PInst); 853 ParamTys.push_back(PInst->getType()); 854 855 if (PInst->isInvalidDecl()) 856 InvalidDecl = true; 857 } else 858 InvalidDecl = true; 859 } 860 861 // FIXME: Deallocate dead declarations. 862 if (InvalidDecl) 863 return QualType(); 864 865 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType(); 866 assert(Proto && "Missing prototype?"); 867 QualType ResultType 868 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs, 869 D->getLocation(), D->getDeclName()); 870 if (ResultType.isNull()) 871 return QualType(); 872 873 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(), 874 Proto->isVariadic(), Proto->getTypeQuals(), 875 D->getLocation(), D->getDeclName()); 876} 877 878/// \brief Initializes the common fields of an instantiation function 879/// declaration (New) from the corresponding fields of its template (Tmpl). 880/// 881/// \returns true if there was an error 882bool 883TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 884 FunctionDecl *Tmpl) { 885 if (Tmpl->isDeleted()) 886 New->setDeleted(); 887 888 // If we are performing substituting explicitly-specified template arguments 889 // or deduced template arguments into a function template and we reach this 890 // point, we are now past the point where SFINAE applies and have committed 891 // to keeping the new function template specialization. We therefore 892 // convert the active template instantiation for the function template 893 // into a template instantiation for this specific function template 894 // specialization, which is not a SFINAE context, so that we diagnose any 895 // further errors in the declaration itself. 896 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 897 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 898 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 899 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 900 if (FunctionTemplateDecl *FunTmpl 901 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 902 assert(FunTmpl->getTemplatedDecl() == Tmpl && 903 "Deduction from the wrong function template?"); 904 (void) FunTmpl; 905 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 906 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 907 } 908 } 909 910 return false; 911} 912 913/// \brief Initializes common fields of an instantiated method 914/// declaration (New) from the corresponding fields of its template 915/// (Tmpl). 916/// 917/// \returns true if there was an error 918bool 919TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 920 CXXMethodDecl *Tmpl) { 921 if (InitFunctionInstantiation(New, Tmpl)) 922 return true; 923 924 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 925 New->setAccess(Tmpl->getAccess()); 926 if (Tmpl->isVirtualAsWritten()) { 927 New->setVirtualAsWritten(true); 928 Record->setAggregate(false); 929 Record->setPOD(false); 930 Record->setEmpty(false); 931 Record->setPolymorphic(true); 932 } 933 if (Tmpl->isPure()) { 934 New->setPure(); 935 Record->setAbstract(true); 936 } 937 938 // FIXME: attributes 939 // FIXME: New needs a pointer to Tmpl 940 return false; 941} 942 943/// \brief Instantiate the definition of the given function from its 944/// template. 945/// 946/// \param PointOfInstantiation the point at which the instantiation was 947/// required. Note that this is not precisely a "point of instantiation" 948/// for the function, but it's close. 949/// 950/// \param Function the already-instantiated declaration of a 951/// function template specialization or member function of a class template 952/// specialization. 953/// 954/// \param Recursive if true, recursively instantiates any functions that 955/// are required by this instantiation. 956void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 957 FunctionDecl *Function, 958 bool Recursive) { 959 if (Function->isInvalidDecl()) 960 return; 961 962 assert(!Function->getBody() && "Already instantiated!"); 963 964 // Find the function body that we'll be substituting. 965 const FunctionDecl *PatternDecl = 0; 966 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) { 967 while (Primary->getInstantiatedFromMemberTemplate()) 968 Primary = Primary->getInstantiatedFromMemberTemplate(); 969 970 PatternDecl = Primary->getTemplatedDecl(); 971 } else 972 PatternDecl = Function->getInstantiatedFromMemberFunction(); 973 Stmt *Pattern = 0; 974 if (PatternDecl) 975 Pattern = PatternDecl->getBody(PatternDecl); 976 977 if (!Pattern) 978 return; 979 980 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 981 if (Inst) 982 return; 983 984 // If we're performing recursive template instantiation, create our own 985 // queue of pending implicit instantiations that we will instantiate later, 986 // while we're still within our own instantiation context. 987 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 988 if (Recursive) 989 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 990 991 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 992 993 // Introduce a new scope where local variable instantiations will be 994 // recorded. 995 LocalInstantiationScope Scope(*this); 996 997 // Introduce the instantiated function parameters into the local 998 // instantiation scope. 999 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 1000 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 1001 Function->getParamDecl(I)); 1002 1003 // Enter the scope of this instantiation. We don't use 1004 // PushDeclContext because we don't have a scope. 1005 DeclContext *PreviousContext = CurContext; 1006 CurContext = Function; 1007 1008 MultiLevelTemplateArgumentList TemplateArgs = 1009 getTemplateInstantiationArgs(Function); 1010 1011 // If this is a constructor, instantiate the member initializers. 1012 if (const CXXConstructorDecl *Ctor = 1013 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 1014 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 1015 TemplateArgs); 1016 } 1017 1018 // Instantiate the function body. 1019 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs); 1020 1021 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 1022 /*IsInstantiation=*/true); 1023 1024 CurContext = PreviousContext; 1025 1026 DeclGroupRef DG(Function); 1027 Consumer.HandleTopLevelDecl(DG); 1028 1029 if (Recursive) { 1030 // Instantiate any pending implicit instantiations found during the 1031 // instantiation of this template. 1032 PerformPendingImplicitInstantiations(); 1033 1034 // Restore the set of pending implicit instantiations. 1035 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1036 } 1037} 1038 1039/// \brief Instantiate the definition of the given variable from its 1040/// template. 1041/// 1042/// \param PointOfInstantiation the point at which the instantiation was 1043/// required. Note that this is not precisely a "point of instantiation" 1044/// for the function, but it's close. 1045/// 1046/// \param Var the already-instantiated declaration of a static member 1047/// variable of a class template specialization. 1048/// 1049/// \param Recursive if true, recursively instantiates any functions that 1050/// are required by this instantiation. 1051void Sema::InstantiateStaticDataMemberDefinition( 1052 SourceLocation PointOfInstantiation, 1053 VarDecl *Var, 1054 bool Recursive) { 1055 if (Var->isInvalidDecl()) 1056 return; 1057 1058 // Find the out-of-line definition of this static data member. 1059 // FIXME: Do we have to look for specializations separately? 1060 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 1061 bool FoundOutOfLineDef = false; 1062 assert(Def && "This data member was not instantiated from a template?"); 1063 assert(Def->isStaticDataMember() && "Not a static data member?"); 1064 for (VarDecl::redecl_iterator RD = Def->redecls_begin(), 1065 RDEnd = Def->redecls_end(); 1066 RD != RDEnd; ++RD) { 1067 if (RD->getLexicalDeclContext()->isFileContext()) { 1068 Def = *RD; 1069 FoundOutOfLineDef = true; 1070 } 1071 } 1072 1073 if (!FoundOutOfLineDef) { 1074 // We did not find an out-of-line definition of this static data member, 1075 // so we won't perform any instantiation. Rather, we rely on the user to 1076 // instantiate this definition (or provide a specialization for it) in 1077 // another translation unit. 1078 return; 1079 } 1080 1081 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 1082 if (Inst) 1083 return; 1084 1085 // If we're performing recursive template instantiation, create our own 1086 // queue of pending implicit instantiations that we will instantiate later, 1087 // while we're still within our own instantiation context. 1088 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1089 if (Recursive) 1090 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1091 1092 // Enter the scope of this instantiation. We don't use 1093 // PushDeclContext because we don't have a scope. 1094 DeclContext *PreviousContext = CurContext; 1095 CurContext = Var->getDeclContext(); 1096 1097 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 1098 getTemplateInstantiationArgs(Var))); 1099 1100 CurContext = PreviousContext; 1101 1102 if (Var) { 1103 DeclGroupRef DG(Var); 1104 Consumer.HandleTopLevelDecl(DG); 1105 } 1106 1107 if (Recursive) { 1108 // Instantiate any pending implicit instantiations found during the 1109 // instantiation of this template. 1110 PerformPendingImplicitInstantiations(); 1111 1112 // Restore the set of pending implicit instantiations. 1113 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1114 } 1115} 1116 1117void 1118Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 1119 const CXXConstructorDecl *Tmpl, 1120 const MultiLevelTemplateArgumentList &TemplateArgs) { 1121 1122 llvm::SmallVector<MemInitTy*, 4> NewInits; 1123 1124 // Instantiate all the initializers. 1125 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 1126 InitsEnd = Tmpl->init_end(); 1127 Inits != InitsEnd; ++Inits) { 1128 CXXBaseOrMemberInitializer *Init = *Inits; 1129 1130 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this); 1131 1132 // Instantiate all the arguments. 1133 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end(); 1134 Args != ArgsEnd; ++Args) { 1135 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs); 1136 1137 if (NewArg.isInvalid()) 1138 New->setInvalidDecl(); 1139 else 1140 NewArgs.push_back(NewArg.takeAs<Expr>()); 1141 } 1142 1143 MemInitResult NewInit; 1144 1145 if (Init->isBaseInitializer()) { 1146 QualType BaseType(Init->getBaseClass(), 0); 1147 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(), 1148 New->getDeclName()); 1149 1150 NewInit = BuildBaseInitializer(BaseType, 1151 (Expr **)NewArgs.data(), 1152 NewArgs.size(), 1153 Init->getSourceLocation(), 1154 Init->getRParenLoc(), 1155 New->getParent()); 1156 } else if (Init->isMemberInitializer()) { 1157 FieldDecl *Member; 1158 1159 // Is this an anonymous union? 1160 if (FieldDecl *UnionInit = Init->getAnonUnionMember()) 1161 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit)); 1162 else 1163 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember())); 1164 1165 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 1166 NewArgs.size(), 1167 Init->getSourceLocation(), 1168 Init->getRParenLoc()); 1169 } 1170 1171 if (NewInit.isInvalid()) 1172 New->setInvalidDecl(); 1173 else { 1174 // FIXME: It would be nice if ASTOwningVector had a release function. 1175 NewArgs.take(); 1176 1177 NewInits.push_back((MemInitTy *)NewInit.get()); 1178 } 1179 } 1180 1181 // Assign all the initializers to the new constructor. 1182 ActOnMemInitializers(DeclPtrTy::make(New), 1183 /*FIXME: ColonLoc */ 1184 SourceLocation(), 1185 NewInits.data(), NewInits.size()); 1186} 1187 1188// TODO: this could be templated if the various decl types used the 1189// same method name. 1190static bool isInstantiationOf(ClassTemplateDecl *Pattern, 1191 ClassTemplateDecl *Instance) { 1192 Pattern = Pattern->getCanonicalDecl(); 1193 1194 do { 1195 Instance = Instance->getCanonicalDecl(); 1196 if (Pattern == Instance) return true; 1197 Instance = Instance->getInstantiatedFromMemberTemplate(); 1198 } while (Instance); 1199 1200 return false; 1201} 1202 1203static bool isInstantiationOf(CXXRecordDecl *Pattern, 1204 CXXRecordDecl *Instance) { 1205 Pattern = Pattern->getCanonicalDecl(); 1206 1207 do { 1208 Instance = Instance->getCanonicalDecl(); 1209 if (Pattern == Instance) return true; 1210 Instance = Instance->getInstantiatedFromMemberClass(); 1211 } while (Instance); 1212 1213 return false; 1214} 1215 1216static bool isInstantiationOf(FunctionDecl *Pattern, 1217 FunctionDecl *Instance) { 1218 Pattern = Pattern->getCanonicalDecl(); 1219 1220 do { 1221 Instance = Instance->getCanonicalDecl(); 1222 if (Pattern == Instance) return true; 1223 Instance = Instance->getInstantiatedFromMemberFunction(); 1224 } while (Instance); 1225 1226 return false; 1227} 1228 1229static bool isInstantiationOf(EnumDecl *Pattern, 1230 EnumDecl *Instance) { 1231 Pattern = Pattern->getCanonicalDecl(); 1232 1233 do { 1234 Instance = Instance->getCanonicalDecl(); 1235 if (Pattern == Instance) return true; 1236 Instance = Instance->getInstantiatedFromMemberEnum(); 1237 } while (Instance); 1238 1239 return false; 1240} 1241 1242static bool isInstantiationOf(UnresolvedUsingDecl *Pattern, 1243 UsingDecl *Instance, 1244 ASTContext &C) { 1245 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern; 1246} 1247 1248static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 1249 VarDecl *Instance) { 1250 assert(Instance->isStaticDataMember()); 1251 1252 Pattern = Pattern->getCanonicalDecl(); 1253 1254 do { 1255 Instance = Instance->getCanonicalDecl(); 1256 if (Pattern == Instance) return true; 1257 Instance = Instance->getInstantiatedFromStaticDataMember(); 1258 } while (Instance); 1259 1260 return false; 1261} 1262 1263static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 1264 if (D->getKind() != Other->getKind()) { 1265 if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) { 1266 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 1267 return isInstantiationOf(UUD, UD, Ctx); 1268 } 1269 } 1270 1271 return false; 1272 } 1273 1274 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 1275 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 1276 1277 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 1278 return isInstantiationOf(cast<FunctionDecl>(D), Function); 1279 1280 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 1281 return isInstantiationOf(cast<EnumDecl>(D), Enum); 1282 1283 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 1284 if (Var->isStaticDataMember()) 1285 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 1286 1287 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 1288 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 1289 1290 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 1291 if (!Field->getDeclName()) { 1292 // This is an unnamed field. 1293 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 1294 cast<FieldDecl>(D); 1295 } 1296 } 1297 1298 return D->getDeclName() && isa<NamedDecl>(Other) && 1299 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 1300} 1301 1302template<typename ForwardIterator> 1303static NamedDecl *findInstantiationOf(ASTContext &Ctx, 1304 NamedDecl *D, 1305 ForwardIterator first, 1306 ForwardIterator last) { 1307 for (; first != last; ++first) 1308 if (isInstantiationOf(Ctx, D, *first)) 1309 return cast<NamedDecl>(*first); 1310 1311 return 0; 1312} 1313 1314/// \brief Finds the instantiation of the given declaration context 1315/// within the current instantiation. 1316/// 1317/// \returns NULL if there was an error 1318DeclContext *Sema::FindInstantiatedContext(DeclContext* DC) { 1319 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 1320 Decl* ID = FindInstantiatedDecl(D); 1321 return cast_or_null<DeclContext>(ID); 1322 } else return DC; 1323} 1324 1325/// \brief Find the instantiation of the given declaration within the 1326/// current instantiation. 1327/// 1328/// This routine is intended to be used when \p D is a declaration 1329/// referenced from within a template, that needs to mapped into the 1330/// corresponding declaration within an instantiation. For example, 1331/// given: 1332/// 1333/// \code 1334/// template<typename T> 1335/// struct X { 1336/// enum Kind { 1337/// KnownValue = sizeof(T) 1338/// }; 1339/// 1340/// bool getKind() const { return KnownValue; } 1341/// }; 1342/// 1343/// template struct X<int>; 1344/// \endcode 1345/// 1346/// In the instantiation of X<int>::getKind(), we need to map the 1347/// EnumConstantDecl for KnownValue (which refers to 1348/// X<T>::<Kind>::KnownValue) to its instantiation 1349/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 1350/// this mapping from within the instantiation of X<int>. 1351NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D) { 1352 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) { 1353 // Transform all of the elements of the overloaded function set. 1354 OverloadedFunctionDecl *Result 1355 = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName()); 1356 1357 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 1358 FEnd = Ovl->function_end(); 1359 F != FEnd; ++F) { 1360 Result->addOverload( 1361 AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F))); 1362 } 1363 1364 return Result; 1365 } 1366 1367 DeclContext *ParentDC = D->getDeclContext(); 1368 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) { 1369 // D is a local of some kind. Look into the map of local 1370 // declarations to their instantiations. 1371 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 1372 } 1373 1374 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 1375 if (ClassTemplateDecl *ClassTemplate 1376 = Record->getDescribedClassTemplate()) { 1377 // When the declaration D was parsed, it referred to the current 1378 // instantiation. Therefore, look through the current context, 1379 // which contains actual instantiations, to find the 1380 // instantiation of the "current instantiation" that D refers 1381 // to. Alternatively, we could just instantiate the 1382 // injected-class-name with the current template arguments, but 1383 // such an instantiation is far more expensive. 1384 for (DeclContext *DC = CurContext; !DC->isFileContext(); 1385 DC = DC->getParent()) { 1386 if (ClassTemplateSpecializationDecl *Spec 1387 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 1388 if (isInstantiationOf(ClassTemplate, Spec->getSpecializedTemplate())) 1389 return Spec; 1390 } 1391 1392 assert(false && 1393 "Unable to find declaration for the current instantiation"); 1394 } 1395 1396 ParentDC = FindInstantiatedContext(ParentDC); 1397 if (!ParentDC) 1398 return 0; 1399 1400 if (ParentDC != D->getDeclContext()) { 1401 // We performed some kind of instantiation in the parent context, 1402 // so now we need to look into the instantiated parent context to 1403 // find the instantiation of the declaration D. 1404 NamedDecl *Result = 0; 1405 if (D->getDeclName()) { 1406 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 1407 Result = findInstantiationOf(Context, D, Found.first, Found.second); 1408 } else { 1409 // Since we don't have a name for the entity we're looking for, 1410 // our only option is to walk through all of the declarations to 1411 // find that name. This will occur in a few cases: 1412 // 1413 // - anonymous struct/union within a template 1414 // - unnamed class/struct/union/enum within a template 1415 // 1416 // FIXME: Find a better way to find these instantiations! 1417 Result = findInstantiationOf(Context, D, 1418 ParentDC->decls_begin(), 1419 ParentDC->decls_end()); 1420 } 1421 1422 assert(Result && "Unable to find instantiation of declaration!"); 1423 D = Result; 1424 } 1425 1426 return D; 1427} 1428 1429/// \brief Performs template instantiation for all implicit template 1430/// instantiations we have seen until this point. 1431void Sema::PerformPendingImplicitInstantiations() { 1432 while (!PendingImplicitInstantiations.empty()) { 1433 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front(); 1434 PendingImplicitInstantiations.pop_front(); 1435 1436 // Instantiate function definitions 1437 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 1438 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function), 1439 Function->getLocation(), *this, 1440 Context.getSourceManager(), 1441 "instantiating function definition"); 1442 1443 if (!Function->getBody()) 1444 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 1445 continue; 1446 } 1447 1448 // Instantiate static data member definitions. 1449 VarDecl *Var = cast<VarDecl>(Inst.first); 1450 assert(Var->isStaticDataMember() && "Not a static data member?"); 1451 1452 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var), 1453 Var->getLocation(), *this, 1454 Context.getSourceManager(), 1455 "instantiating static data member " 1456 "definition"); 1457 1458 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 1459 } 1460} 1461