SemaTemplateInstantiateDecl.cpp revision e6975e9b0985ad7f7ff9187e38d95bfe9ac4181b
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 "clang/Sema/SemaInternal.h" 13#include "clang/Sema/Lookup.h" 14#include "clang/Sema/PrettyDeclStackTrace.h" 15#include "clang/Sema/Template.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/AST/DeclVisitor.h" 20#include "clang/AST/DependentDiagnostic.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/TypeLoc.h" 24#include "clang/Lex/Preprocessor.h" 25 26using namespace clang; 27 28bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 29 DeclaratorDecl *NewDecl) { 30 if (!OldDecl->getQualifierLoc()) 31 return false; 32 33 NestedNameSpecifierLoc NewQualifierLoc 34 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 35 TemplateArgs); 36 37 if (!NewQualifierLoc) 38 return true; 39 40 NewDecl->setQualifierInfo(NewQualifierLoc); 41 return false; 42} 43 44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 45 TagDecl *NewDecl) { 46 if (!OldDecl->getQualifierLoc()) 47 return false; 48 49 NestedNameSpecifierLoc NewQualifierLoc 50 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 51 TemplateArgs); 52 53 if (!NewQualifierLoc) 54 return true; 55 56 NewDecl->setQualifierInfo(NewQualifierLoc); 57 return false; 58} 59 60// Include attribute instantiation code. 61#include "clang/Sema/AttrTemplateInstantiate.inc" 62 63void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 64 const Decl *Tmpl, Decl *New, 65 LateInstantiatedAttrVec *LateAttrs, 66 LocalInstantiationScope *OuterMostScope) { 67 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end(); 68 i != e; ++i) { 69 const Attr *TmplAttr = *i; 70 71 // FIXME: This should be generalized to more than just the AlignedAttr. 72 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) { 73 if (Aligned->isAlignmentDependent()) { 74 if (Aligned->isAlignmentExpr()) { 75 // The alignment expression is a constant expression. 76 EnterExpressionEvaluationContext Unevaluated(*this, 77 Sema::ConstantEvaluated); 78 79 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(), 80 TemplateArgs); 81 if (!Result.isInvalid()) 82 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>()); 83 } else { 84 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(), 85 TemplateArgs, 86 Aligned->getLocation(), 87 DeclarationName()); 88 if (Result) 89 AddAlignedAttr(Aligned->getLocation(), New, Result); 90 } 91 continue; 92 } 93 } 94 95 if (TmplAttr->isLateParsed() && LateAttrs) { 96 // Late parsed attributes must be instantiated and attached after the 97 // enclosing class has been instantiated. See Sema::InstantiateClass. 98 LocalInstantiationScope *Saved = 0; 99 if (CurrentInstantiationScope) 100 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); 101 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); 102 } else { 103 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, 104 *this, TemplateArgs); 105 New->addAttr(NewAttr); 106 } 107 } 108} 109 110Decl * 111TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 112 llvm_unreachable("Translation units cannot be instantiated"); 113} 114 115Decl * 116TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 117 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 118 D->getIdentifier()); 119 Owner->addDecl(Inst); 120 return Inst; 121} 122 123Decl * 124TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 125 llvm_unreachable("Namespaces cannot be instantiated"); 126} 127 128Decl * 129TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 130 NamespaceAliasDecl *Inst 131 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 132 D->getNamespaceLoc(), 133 D->getAliasLoc(), 134 D->getIdentifier(), 135 D->getQualifierLoc(), 136 D->getTargetNameLoc(), 137 D->getNamespace()); 138 Owner->addDecl(Inst); 139 return Inst; 140} 141 142Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 143 bool IsTypeAlias) { 144 bool Invalid = false; 145 TypeSourceInfo *DI = D->getTypeSourceInfo(); 146 if (DI->getType()->isInstantiationDependentType() || 147 DI->getType()->isVariablyModifiedType()) { 148 DI = SemaRef.SubstType(DI, TemplateArgs, 149 D->getLocation(), D->getDeclName()); 150 if (!DI) { 151 Invalid = true; 152 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 153 } 154 } else { 155 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 156 } 157 158 // Create the new typedef 159 TypedefNameDecl *Typedef; 160 if (IsTypeAlias) 161 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 162 D->getLocation(), D->getIdentifier(), DI); 163 else 164 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 165 D->getLocation(), D->getIdentifier(), DI); 166 if (Invalid) 167 Typedef->setInvalidDecl(); 168 169 // If the old typedef was the name for linkage purposes of an anonymous 170 // tag decl, re-establish that relationship for the new typedef. 171 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 172 TagDecl *oldTag = oldTagType->getDecl(); 173 if (oldTag->getTypedefNameForAnonDecl() == D) { 174 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 175 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl()); 176 newTag->setTypedefNameForAnonDecl(Typedef); 177 } 178 } 179 180 if (TypedefNameDecl *Prev = D->getPreviousDecl()) { 181 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 182 TemplateArgs); 183 if (!InstPrev) 184 return 0; 185 186 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev); 187 188 // If the typedef types are not identical, reject them. 189 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); 190 191 Typedef->setPreviousDeclaration(InstPrevTypedef); 192 } 193 194 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); 195 196 Typedef->setAccess(D->getAccess()); 197 198 return Typedef; 199} 200 201Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 202 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); 203 Owner->addDecl(Typedef); 204 return Typedef; 205} 206 207Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { 208 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); 209 Owner->addDecl(Typedef); 210 return Typedef; 211} 212 213Decl * 214TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 215 // Create a local instantiation scope for this type alias template, which 216 // will contain the instantiations of the template parameters. 217 LocalInstantiationScope Scope(SemaRef); 218 219 TemplateParameterList *TempParams = D->getTemplateParameters(); 220 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 221 if (!InstParams) 222 return 0; 223 224 TypeAliasDecl *Pattern = D->getTemplatedDecl(); 225 226 TypeAliasTemplateDecl *PrevAliasTemplate = 0; 227 if (Pattern->getPreviousDecl()) { 228 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 229 if (Found.first != Found.second) { 230 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first); 231 } 232 } 233 234 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( 235 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); 236 if (!AliasInst) 237 return 0; 238 239 TypeAliasTemplateDecl *Inst 240 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 241 D->getDeclName(), InstParams, AliasInst); 242 if (PrevAliasTemplate) 243 Inst->setPreviousDeclaration(PrevAliasTemplate); 244 245 Inst->setAccess(D->getAccess()); 246 247 if (!PrevAliasTemplate) 248 Inst->setInstantiatedFromMemberTemplate(D); 249 250 Owner->addDecl(Inst); 251 252 return Inst; 253} 254 255Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 256 // If this is the variable for an anonymous struct or union, 257 // instantiate the anonymous struct/union type first. 258 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 259 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 260 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 261 return 0; 262 263 // Do substitution on the type of the declaration 264 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 265 TemplateArgs, 266 D->getTypeSpecStartLoc(), 267 D->getDeclName()); 268 if (!DI) 269 return 0; 270 271 if (DI->getType()->isFunctionType()) { 272 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 273 << D->isStaticDataMember() << DI->getType(); 274 return 0; 275 } 276 277 // Build the instantiated declaration 278 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 279 D->getInnerLocStart(), 280 D->getLocation(), D->getIdentifier(), 281 DI->getType(), DI, 282 D->getStorageClass(), 283 D->getStorageClassAsWritten()); 284 Var->setThreadSpecified(D->isThreadSpecified()); 285 Var->setInitStyle(D->getInitStyle()); 286 Var->setCXXForRangeDecl(D->isCXXForRangeDecl()); 287 Var->setConstexpr(D->isConstexpr()); 288 289 // Substitute the nested name specifier, if any. 290 if (SubstQualifier(D, Var)) 291 return 0; 292 293 // If we are instantiating a static data member defined 294 // out-of-line, the instantiation will have the same lexical 295 // context (which will be a namespace scope) as the template. 296 if (D->isOutOfLine()) 297 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 298 299 Var->setAccess(D->getAccess()); 300 301 if (!D->isStaticDataMember()) { 302 Var->setUsed(D->isUsed(false)); 303 Var->setReferenced(D->isReferenced()); 304 } 305 306 // FIXME: In theory, we could have a previous declaration for variables that 307 // are not static data members. 308 // FIXME: having to fake up a LookupResult is dumb. 309 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(), 310 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 311 if (D->isStaticDataMember()) 312 SemaRef.LookupQualifiedName(Previous, Owner, false); 313 314 // In ARC, infer 'retaining' for variables of retainable type. 315 if (SemaRef.getLangOpts().ObjCAutoRefCount && 316 SemaRef.inferObjCARCLifetime(Var)) 317 Var->setInvalidDecl(); 318 319 SemaRef.CheckVariableDeclaration(Var, Previous); 320 321 if (D->isOutOfLine()) { 322 D->getLexicalDeclContext()->addDecl(Var); 323 Owner->makeDeclVisibleInContext(Var); 324 } else { 325 Owner->addDecl(Var); 326 if (Owner->isFunctionOrMethod()) 327 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var); 328 } 329 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope); 330 331 // Link instantiations of static data members back to the template from 332 // which they were instantiated. 333 if (Var->isStaticDataMember()) 334 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 335 TSK_ImplicitInstantiation); 336 337 if (Var->getAnyInitializer()) { 338 // We already have an initializer in the class. 339 } else if (D->getInit()) { 340 if (Var->isStaticDataMember() && !D->isOutOfLine()) 341 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated); 342 else 343 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 344 345 // Instantiate the initializer. 346 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs, 347 D->getInitStyle() == VarDecl::CallInit); 348 if (!Init.isInvalid()) { 349 bool TypeMayContainAuto = true; 350 if (Init.get()) { 351 bool DirectInit = D->isDirectInit(); 352 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit, 353 TypeMayContainAuto); 354 } else 355 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto); 356 } else { 357 // FIXME: Not too happy about invalidating the declaration 358 // because of a bogus initializer. 359 Var->setInvalidDecl(); 360 } 361 362 SemaRef.PopExpressionEvaluationContext(); 363 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) && 364 !Var->isCXXForRangeDecl()) 365 SemaRef.ActOnUninitializedDecl(Var, false); 366 367 // Diagnose unused local variables with dependent types, where the diagnostic 368 // will have been deferred. 369 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() && 370 D->getType()->isDependentType()) 371 SemaRef.DiagnoseUnusedDecl(Var); 372 373 return Var; 374} 375 376Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { 377 AccessSpecDecl* AD 378 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner, 379 D->getAccessSpecifierLoc(), D->getColonLoc()); 380 Owner->addHiddenDecl(AD); 381 return AD; 382} 383 384Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 385 bool Invalid = false; 386 TypeSourceInfo *DI = D->getTypeSourceInfo(); 387 if (DI->getType()->isInstantiationDependentType() || 388 DI->getType()->isVariablyModifiedType()) { 389 DI = SemaRef.SubstType(DI, TemplateArgs, 390 D->getLocation(), D->getDeclName()); 391 if (!DI) { 392 DI = D->getTypeSourceInfo(); 393 Invalid = true; 394 } else if (DI->getType()->isFunctionType()) { 395 // C++ [temp.arg.type]p3: 396 // If a declaration acquires a function type through a type 397 // dependent on a template-parameter and this causes a 398 // declaration that does not use the syntactic form of a 399 // function declarator to have function type, the program is 400 // ill-formed. 401 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 402 << DI->getType(); 403 Invalid = true; 404 } 405 } else { 406 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 407 } 408 409 Expr *BitWidth = D->getBitWidth(); 410 if (Invalid) 411 BitWidth = 0; 412 else if (BitWidth) { 413 // The bit-width expression is a constant expression. 414 EnterExpressionEvaluationContext Unevaluated(SemaRef, 415 Sema::ConstantEvaluated); 416 417 ExprResult InstantiatedBitWidth 418 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 419 if (InstantiatedBitWidth.isInvalid()) { 420 Invalid = true; 421 BitWidth = 0; 422 } else 423 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 424 } 425 426 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 427 DI->getType(), DI, 428 cast<RecordDecl>(Owner), 429 D->getLocation(), 430 D->isMutable(), 431 BitWidth, 432 D->hasInClassInitializer(), 433 D->getTypeSpecStartLoc(), 434 D->getAccess(), 435 0); 436 if (!Field) { 437 cast<Decl>(Owner)->setInvalidDecl(); 438 return 0; 439 } 440 441 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope); 442 443 if (Invalid) 444 Field->setInvalidDecl(); 445 446 if (!Field->getDeclName()) { 447 // Keep track of where this decl came from. 448 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 449 } 450 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 451 if (Parent->isAnonymousStructOrUnion() && 452 Parent->getRedeclContext()->isFunctionOrMethod()) 453 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 454 } 455 456 Field->setImplicit(D->isImplicit()); 457 Field->setAccess(D->getAccess()); 458 Owner->addDecl(Field); 459 460 return Field; 461} 462 463Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 464 NamedDecl **NamedChain = 465 new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; 466 467 int i = 0; 468 for (IndirectFieldDecl::chain_iterator PI = 469 D->chain_begin(), PE = D->chain_end(); 470 PI != PE; ++PI) { 471 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI, 472 TemplateArgs); 473 if (!Next) 474 return 0; 475 476 NamedChain[i++] = Next; 477 } 478 479 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType(); 480 IndirectFieldDecl* IndirectField 481 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(), 482 D->getIdentifier(), T, 483 NamedChain, D->getChainingSize()); 484 485 486 IndirectField->setImplicit(D->isImplicit()); 487 IndirectField->setAccess(D->getAccess()); 488 Owner->addDecl(IndirectField); 489 return IndirectField; 490} 491 492Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 493 // Handle friend type expressions by simply substituting template 494 // parameters into the pattern type and checking the result. 495 if (TypeSourceInfo *Ty = D->getFriendType()) { 496 TypeSourceInfo *InstTy; 497 // If this is an unsupported friend, don't bother substituting template 498 // arguments into it. The actual type referred to won't be used by any 499 // parts of Clang, and may not be valid for instantiating. Just use the 500 // same info for the instantiated friend. 501 if (D->isUnsupportedFriend()) { 502 InstTy = Ty; 503 } else { 504 InstTy = SemaRef.SubstType(Ty, TemplateArgs, 505 D->getLocation(), DeclarationName()); 506 } 507 if (!InstTy) 508 return 0; 509 510 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(), 511 D->getFriendLoc(), InstTy); 512 if (!FD) 513 return 0; 514 515 FD->setAccess(AS_public); 516 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 517 Owner->addDecl(FD); 518 return FD; 519 } 520 521 NamedDecl *ND = D->getFriendDecl(); 522 assert(ND && "friend decl must be a decl or a type!"); 523 524 // All of the Visit implementations for the various potential friend 525 // declarations have to be carefully written to work for friend 526 // objects, with the most important detail being that the target 527 // decl should almost certainly not be placed in Owner. 528 Decl *NewND = Visit(ND); 529 if (!NewND) return 0; 530 531 FriendDecl *FD = 532 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 533 cast<NamedDecl>(NewND), D->getFriendLoc()); 534 FD->setAccess(AS_public); 535 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 536 Owner->addDecl(FD); 537 return FD; 538} 539 540Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 541 Expr *AssertExpr = D->getAssertExpr(); 542 543 // The expression in a static assertion is a constant expression. 544 EnterExpressionEvaluationContext Unevaluated(SemaRef, 545 Sema::ConstantEvaluated); 546 547 ExprResult InstantiatedAssertExpr 548 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 549 if (InstantiatedAssertExpr.isInvalid()) 550 return 0; 551 552 ExprResult Message(D->getMessage()); 553 D->getMessage(); 554 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 555 InstantiatedAssertExpr.get(), 556 Message.get(), 557 D->getRParenLoc()); 558} 559 560Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 561 EnumDecl *PrevDecl = 0; 562 if (D->getPreviousDecl()) { 563 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 564 D->getPreviousDecl(), 565 TemplateArgs); 566 if (!Prev) return 0; 567 PrevDecl = cast<EnumDecl>(Prev); 568 } 569 570 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 571 D->getLocation(), D->getIdentifier(), 572 PrevDecl, D->isScoped(), 573 D->isScopedUsingClassTag(), D->isFixed()); 574 if (D->isFixed()) { 575 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { 576 // If we have type source information for the underlying type, it means it 577 // has been explicitly set by the user. Perform substitution on it before 578 // moving on. 579 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 580 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc, 581 DeclarationName()); 582 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI)) 583 Enum->setIntegerType(SemaRef.Context.IntTy); 584 else 585 Enum->setIntegerTypeSourceInfo(NewTI); 586 } else { 587 assert(!D->getIntegerType()->isDependentType() 588 && "Dependent type without type source info"); 589 Enum->setIntegerType(D->getIntegerType()); 590 } 591 } 592 593 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); 594 595 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation); 596 Enum->setAccess(D->getAccess()); 597 if (SubstQualifier(D, Enum)) return 0; 598 Owner->addDecl(Enum); 599 600 EnumDecl *Def = D->getDefinition(); 601 if (Def && Def != D) { 602 // If this is an out-of-line definition of an enum member template, check 603 // that the underlying types match in the instantiation of both 604 // declarations. 605 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { 606 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 607 QualType DefnUnderlying = 608 SemaRef.SubstType(TI->getType(), TemplateArgs, 609 UnderlyingLoc, DeclarationName()); 610 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(), 611 DefnUnderlying, Enum); 612 } 613 } 614 615 if (D->getDeclContext()->isFunctionOrMethod()) 616 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 617 618 // C++11 [temp.inst]p1: The implicit instantiation of a class template 619 // specialization causes the implicit instantiation of the declarations, but 620 // not the definitions of scoped member enumerations. 621 // FIXME: There appears to be no wording for what happens for an enum defined 622 // within a block scope, but we treat that much like a member template. Only 623 // instantiate the definition when visiting the definition in that case, since 624 // we will visit all redeclarations. 625 if (!Enum->isScoped() && Def && 626 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition())) 627 InstantiateEnumDefinition(Enum, Def); 628 629 return Enum; 630} 631 632void TemplateDeclInstantiator::InstantiateEnumDefinition( 633 EnumDecl *Enum, EnumDecl *Pattern) { 634 Enum->startDefinition(); 635 636 // Update the location to refer to the definition. 637 Enum->setLocation(Pattern->getLocation()); 638 639 SmallVector<Decl*, 4> Enumerators; 640 641 EnumConstantDecl *LastEnumConst = 0; 642 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(), 643 ECEnd = Pattern->enumerator_end(); 644 EC != ECEnd; ++EC) { 645 // The specified value for the enumerator. 646 ExprResult Value = SemaRef.Owned((Expr *)0); 647 if (Expr *UninstValue = EC->getInitExpr()) { 648 // The enumerator's value expression is a constant expression. 649 EnterExpressionEvaluationContext Unevaluated(SemaRef, 650 Sema::ConstantEvaluated); 651 652 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 653 } 654 655 // Drop the initial value and continue. 656 bool isInvalid = false; 657 if (Value.isInvalid()) { 658 Value = SemaRef.Owned((Expr *)0); 659 isInvalid = true; 660 } 661 662 EnumConstantDecl *EnumConst 663 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 664 EC->getLocation(), EC->getIdentifier(), 665 Value.get()); 666 667 if (isInvalid) { 668 if (EnumConst) 669 EnumConst->setInvalidDecl(); 670 Enum->setInvalidDecl(); 671 } 672 673 if (EnumConst) { 674 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst); 675 676 EnumConst->setAccess(Enum->getAccess()); 677 Enum->addDecl(EnumConst); 678 Enumerators.push_back(EnumConst); 679 LastEnumConst = EnumConst; 680 681 if (Pattern->getDeclContext()->isFunctionOrMethod() && 682 !Enum->isScoped()) { 683 // If the enumeration is within a function or method, record the enum 684 // constant as a local. 685 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst); 686 } 687 } 688 } 689 690 // FIXME: Fixup LBraceLoc 691 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), 692 Enum->getRBraceLoc(), Enum, 693 Enumerators.data(), Enumerators.size(), 694 0, 0); 695} 696 697Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 698 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls."); 699} 700 701Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 702 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 703 704 // Create a local instantiation scope for this class template, which 705 // will contain the instantiations of the template parameters. 706 LocalInstantiationScope Scope(SemaRef); 707 TemplateParameterList *TempParams = D->getTemplateParameters(); 708 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 709 if (!InstParams) 710 return NULL; 711 712 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 713 714 // Instantiate the qualifier. We have to do this first in case 715 // we're a friend declaration, because if we are then we need to put 716 // the new declaration in the appropriate context. 717 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); 718 if (QualifierLoc) { 719 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 720 TemplateArgs); 721 if (!QualifierLoc) 722 return 0; 723 } 724 725 CXXRecordDecl *PrevDecl = 0; 726 ClassTemplateDecl *PrevClassTemplate = 0; 727 728 if (!isFriend && Pattern->getPreviousDecl()) { 729 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 730 if (Found.first != Found.second) { 731 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first); 732 if (PrevClassTemplate) 733 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 734 } 735 } 736 737 // If this isn't a friend, then it's a member template, in which 738 // case we just want to build the instantiation in the 739 // specialization. If it is a friend, we want to build it in 740 // the appropriate context. 741 DeclContext *DC = Owner; 742 if (isFriend) { 743 if (QualifierLoc) { 744 CXXScopeSpec SS; 745 SS.Adopt(QualifierLoc); 746 DC = SemaRef.computeDeclContext(SS); 747 if (!DC) return 0; 748 } else { 749 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 750 Pattern->getDeclContext(), 751 TemplateArgs); 752 } 753 754 // Look for a previous declaration of the template in the owning 755 // context. 756 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 757 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 758 SemaRef.LookupQualifiedName(R, DC); 759 760 if (R.isSingleResult()) { 761 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 762 if (PrevClassTemplate) 763 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 764 } 765 766 if (!PrevClassTemplate && QualifierLoc) { 767 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 768 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 769 << QualifierLoc.getSourceRange(); 770 return 0; 771 } 772 773 bool AdoptedPreviousTemplateParams = false; 774 if (PrevClassTemplate) { 775 bool Complain = true; 776 777 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 778 // template for struct std::tr1::__detail::_Map_base, where the 779 // template parameters of the friend declaration don't match the 780 // template parameters of the original declaration. In this one 781 // case, we don't complain about the ill-formed friend 782 // declaration. 783 if (isFriend && Pattern->getIdentifier() && 784 Pattern->getIdentifier()->isStr("_Map_base") && 785 DC->isNamespace() && 786 cast<NamespaceDecl>(DC)->getIdentifier() && 787 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 788 DeclContext *DCParent = DC->getParent(); 789 if (DCParent->isNamespace() && 790 cast<NamespaceDecl>(DCParent)->getIdentifier() && 791 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 792 DeclContext *DCParent2 = DCParent->getParent(); 793 if (DCParent2->isNamespace() && 794 cast<NamespaceDecl>(DCParent2)->getIdentifier() && 795 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") && 796 DCParent2->getParent()->isTranslationUnit()) 797 Complain = false; 798 } 799 } 800 801 TemplateParameterList *PrevParams 802 = PrevClassTemplate->getTemplateParameters(); 803 804 // Make sure the parameter lists match. 805 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 806 Complain, 807 Sema::TPL_TemplateMatch)) { 808 if (Complain) 809 return 0; 810 811 AdoptedPreviousTemplateParams = true; 812 InstParams = PrevParams; 813 } 814 815 // Do some additional validation, then merge default arguments 816 // from the existing declarations. 817 if (!AdoptedPreviousTemplateParams && 818 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 819 Sema::TPC_ClassTemplate)) 820 return 0; 821 } 822 } 823 824 CXXRecordDecl *RecordInst 825 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 826 Pattern->getLocStart(), Pattern->getLocation(), 827 Pattern->getIdentifier(), PrevDecl, 828 /*DelayTypeCreation=*/true); 829 830 if (QualifierLoc) 831 RecordInst->setQualifierInfo(QualifierLoc); 832 833 ClassTemplateDecl *Inst 834 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 835 D->getIdentifier(), InstParams, RecordInst, 836 PrevClassTemplate); 837 RecordInst->setDescribedClassTemplate(Inst); 838 839 if (isFriend) { 840 if (PrevClassTemplate) 841 Inst->setAccess(PrevClassTemplate->getAccess()); 842 else 843 Inst->setAccess(D->getAccess()); 844 845 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0); 846 // TODO: do we want to track the instantiation progeny of this 847 // friend target decl? 848 } else { 849 Inst->setAccess(D->getAccess()); 850 if (!PrevClassTemplate) 851 Inst->setInstantiatedFromMemberTemplate(D); 852 } 853 854 // Trigger creation of the type for the instantiation. 855 SemaRef.Context.getInjectedClassNameType(RecordInst, 856 Inst->getInjectedClassNameSpecialization()); 857 858 // Finish handling of friends. 859 if (isFriend) { 860 DC->makeDeclVisibleInContext(Inst); 861 Inst->setLexicalDeclContext(Owner); 862 RecordInst->setLexicalDeclContext(Owner); 863 return Inst; 864 } 865 866 if (D->isOutOfLine()) { 867 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 868 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); 869 } 870 871 Owner->addDecl(Inst); 872 873 if (!PrevClassTemplate) { 874 // Queue up any out-of-line partial specializations of this member 875 // class template; the client will force their instantiation once 876 // the enclosing class has been instantiated. 877 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 878 D->getPartialSpecializations(PartialSpecs); 879 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 880 if (PartialSpecs[I]->isOutOfLine()) 881 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I])); 882 } 883 884 return Inst; 885} 886 887Decl * 888TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 889 ClassTemplatePartialSpecializationDecl *D) { 890 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 891 892 // Lookup the already-instantiated declaration in the instantiation 893 // of the class template and return that. 894 DeclContext::lookup_result Found 895 = Owner->lookup(ClassTemplate->getDeclName()); 896 if (Found.first == Found.second) 897 return 0; 898 899 ClassTemplateDecl *InstClassTemplate 900 = dyn_cast<ClassTemplateDecl>(*Found.first); 901 if (!InstClassTemplate) 902 return 0; 903 904 if (ClassTemplatePartialSpecializationDecl *Result 905 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) 906 return Result; 907 908 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D); 909} 910 911Decl * 912TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 913 // Create a local instantiation scope for this function template, which 914 // will contain the instantiations of the template parameters and then get 915 // merged with the local instantiation scope for the function template 916 // itself. 917 LocalInstantiationScope Scope(SemaRef); 918 919 TemplateParameterList *TempParams = D->getTemplateParameters(); 920 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 921 if (!InstParams) 922 return NULL; 923 924 FunctionDecl *Instantiated = 0; 925 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 926 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 927 InstParams)); 928 else 929 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 930 D->getTemplatedDecl(), 931 InstParams)); 932 933 if (!Instantiated) 934 return 0; 935 936 Instantiated->setAccess(D->getAccess()); 937 938 // Link the instantiated function template declaration to the function 939 // template from which it was instantiated. 940 FunctionTemplateDecl *InstTemplate 941 = Instantiated->getDescribedFunctionTemplate(); 942 InstTemplate->setAccess(D->getAccess()); 943 assert(InstTemplate && 944 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 945 946 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 947 948 // Link the instantiation back to the pattern *unless* this is a 949 // non-definition friend declaration. 950 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 951 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 952 InstTemplate->setInstantiatedFromMemberTemplate(D); 953 954 // Make declarations visible in the appropriate context. 955 if (!isFriend) 956 Owner->addDecl(InstTemplate); 957 958 return InstTemplate; 959} 960 961Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 962 CXXRecordDecl *PrevDecl = 0; 963 if (D->isInjectedClassName()) 964 PrevDecl = cast<CXXRecordDecl>(Owner); 965 else if (D->getPreviousDecl()) { 966 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 967 D->getPreviousDecl(), 968 TemplateArgs); 969 if (!Prev) return 0; 970 PrevDecl = cast<CXXRecordDecl>(Prev); 971 } 972 973 CXXRecordDecl *Record 974 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 975 D->getLocStart(), D->getLocation(), 976 D->getIdentifier(), PrevDecl); 977 978 // Substitute the nested name specifier, if any. 979 if (SubstQualifier(D, Record)) 980 return 0; 981 982 Record->setImplicit(D->isImplicit()); 983 // FIXME: Check against AS_none is an ugly hack to work around the issue that 984 // the tag decls introduced by friend class declarations don't have an access 985 // specifier. Remove once this area of the code gets sorted out. 986 if (D->getAccess() != AS_none) 987 Record->setAccess(D->getAccess()); 988 if (!D->isInjectedClassName()) 989 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 990 991 // If the original function was part of a friend declaration, 992 // inherit its namespace state. 993 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 994 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 995 996 // Make sure that anonymous structs and unions are recorded. 997 if (D->isAnonymousStructOrUnion()) { 998 Record->setAnonymousStructOrUnion(true); 999 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod()) 1000 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 1001 } 1002 1003 Owner->addDecl(Record); 1004 return Record; 1005} 1006 1007/// Normal class members are of more specific types and therefore 1008/// don't make it here. This function serves two purposes: 1009/// 1) instantiating function templates 1010/// 2) substituting friend declarations 1011/// FIXME: preserve function definitions in case #2 1012Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 1013 TemplateParameterList *TemplateParams) { 1014 // Check whether there is already a function template specialization for 1015 // this declaration. 1016 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1017 if (FunctionTemplate && !TemplateParams) { 1018 std::pair<const TemplateArgument *, unsigned> Innermost 1019 = TemplateArgs.getInnermost(); 1020 1021 void *InsertPos = 0; 1022 FunctionDecl *SpecFunc 1023 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second, 1024 InsertPos); 1025 1026 // If we already have a function template specialization, return it. 1027 if (SpecFunc) 1028 return SpecFunc; 1029 } 1030 1031 bool isFriend; 1032 if (FunctionTemplate) 1033 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1034 else 1035 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1036 1037 bool MergeWithParentScope = (TemplateParams != 0) || 1038 Owner->isFunctionOrMethod() || 1039 !(isa<Decl>(Owner) && 1040 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1041 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1042 1043 SmallVector<ParmVarDecl *, 4> Params; 1044 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1045 if (!TInfo) 1046 return 0; 1047 QualType T = TInfo->getType(); 1048 1049 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1050 if (QualifierLoc) { 1051 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1052 TemplateArgs); 1053 if (!QualifierLoc) 1054 return 0; 1055 } 1056 1057 // If we're instantiating a local function declaration, put the result 1058 // in the owner; otherwise we need to find the instantiated context. 1059 DeclContext *DC; 1060 if (D->getDeclContext()->isFunctionOrMethod()) 1061 DC = Owner; 1062 else if (isFriend && QualifierLoc) { 1063 CXXScopeSpec SS; 1064 SS.Adopt(QualifierLoc); 1065 DC = SemaRef.computeDeclContext(SS); 1066 if (!DC) return 0; 1067 } else { 1068 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 1069 TemplateArgs); 1070 } 1071 1072 FunctionDecl *Function = 1073 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 1074 D->getLocation(), D->getDeclName(), T, TInfo, 1075 D->getStorageClass(), D->getStorageClassAsWritten(), 1076 D->isInlineSpecified(), D->hasWrittenPrototype(), 1077 D->isConstexpr()); 1078 1079 if (QualifierLoc) 1080 Function->setQualifierInfo(QualifierLoc); 1081 1082 DeclContext *LexicalDC = Owner; 1083 if (!isFriend && D->isOutOfLine()) { 1084 assert(D->getDeclContext()->isFileContext()); 1085 LexicalDC = D->getDeclContext(); 1086 } 1087 1088 Function->setLexicalDeclContext(LexicalDC); 1089 1090 // Attach the parameters 1091 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) { 1092 // Adopt the already-instantiated parameters into our own context. 1093 for (unsigned P = 0; P < Params.size(); ++P) 1094 if (Params[P]) 1095 Params[P]->setOwningFunction(Function); 1096 } else { 1097 // Since we were instantiated via a typedef of a function type, create 1098 // new parameters. 1099 const FunctionProtoType *Proto 1100 = Function->getType()->getAs<FunctionProtoType>(); 1101 assert(Proto && "No function prototype in template instantiation?"); 1102 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(), 1103 AE = Proto->arg_type_end(); AI != AE; ++AI) { 1104 ParmVarDecl *Param 1105 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(), 1106 *AI); 1107 Param->setScopeInfo(0, Params.size()); 1108 Params.push_back(Param); 1109 } 1110 } 1111 Function->setParams(Params); 1112 1113 SourceLocation InstantiateAtPOI; 1114 if (TemplateParams) { 1115 // Our resulting instantiation is actually a function template, since we 1116 // are substituting only the outer template parameters. For example, given 1117 // 1118 // template<typename T> 1119 // struct X { 1120 // template<typename U> friend void f(T, U); 1121 // }; 1122 // 1123 // X<int> x; 1124 // 1125 // We are instantiating the friend function template "f" within X<int>, 1126 // which means substituting int for T, but leaving "f" as a friend function 1127 // template. 1128 // Build the function template itself. 1129 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1130 Function->getLocation(), 1131 Function->getDeclName(), 1132 TemplateParams, Function); 1133 Function->setDescribedFunctionTemplate(FunctionTemplate); 1134 1135 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1136 1137 if (isFriend && D->isThisDeclarationADefinition()) { 1138 // TODO: should we remember this connection regardless of whether 1139 // the friend declaration provided a body? 1140 FunctionTemplate->setInstantiatedFromMemberTemplate( 1141 D->getDescribedFunctionTemplate()); 1142 } 1143 } else if (FunctionTemplate) { 1144 // Record this function template specialization. 1145 std::pair<const TemplateArgument *, unsigned> Innermost 1146 = TemplateArgs.getInnermost(); 1147 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1148 TemplateArgumentList::CreateCopy(SemaRef.Context, 1149 Innermost.first, 1150 Innermost.second), 1151 /*InsertPos=*/0); 1152 } else if (isFriend) { 1153 // Note, we need this connection even if the friend doesn't have a body. 1154 // Its body may exist but not have been attached yet due to deferred 1155 // parsing. 1156 // FIXME: It might be cleaner to set this when attaching the body to the 1157 // friend function declaration, however that would require finding all the 1158 // instantiations and modifying them. 1159 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1160 } 1161 1162 if (InitFunctionInstantiation(Function, D)) 1163 Function->setInvalidDecl(); 1164 1165 bool isExplicitSpecialization = false; 1166 1167 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(), 1168 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 1169 1170 if (DependentFunctionTemplateSpecializationInfo *Info 1171 = D->getDependentSpecializationInfo()) { 1172 assert(isFriend && "non-friend has dependent specialization info?"); 1173 1174 // This needs to be set now for future sanity. 1175 Function->setObjectOfFriendDecl(/*HasPrevious*/ true); 1176 1177 // Instantiate the explicit template arguments. 1178 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1179 Info->getRAngleLoc()); 1180 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1181 ExplicitArgs, TemplateArgs)) 1182 return 0; 1183 1184 // Map the candidate templates to their instantiations. 1185 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1186 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1187 Info->getTemplate(I), 1188 TemplateArgs); 1189 if (!Temp) return 0; 1190 1191 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1192 } 1193 1194 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1195 &ExplicitArgs, 1196 Previous)) 1197 Function->setInvalidDecl(); 1198 1199 isExplicitSpecialization = true; 1200 1201 } else if (TemplateParams || !FunctionTemplate) { 1202 // Look only into the namespace where the friend would be declared to 1203 // find a previous declaration. This is the innermost enclosing namespace, 1204 // as described in ActOnFriendFunctionDecl. 1205 SemaRef.LookupQualifiedName(Previous, DC); 1206 1207 // In C++, the previous declaration we find might be a tag type 1208 // (class or enum). In this case, the new declaration will hide the 1209 // tag type. Note that this does does not apply if we're declaring a 1210 // typedef (C++ [dcl.typedef]p4). 1211 if (Previous.isSingleTagDecl()) 1212 Previous.clear(); 1213 } 1214 1215 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 1216 isExplicitSpecialization); 1217 1218 NamedDecl *PrincipalDecl = (TemplateParams 1219 ? cast<NamedDecl>(FunctionTemplate) 1220 : Function); 1221 1222 // If the original function was part of a friend declaration, 1223 // inherit its namespace state and add it to the owner. 1224 if (isFriend) { 1225 NamedDecl *PrevDecl; 1226 if (TemplateParams) 1227 PrevDecl = FunctionTemplate->getPreviousDecl(); 1228 else 1229 PrevDecl = Function->getPreviousDecl(); 1230 1231 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0); 1232 DC->makeDeclVisibleInContext(PrincipalDecl); 1233 1234 bool queuedInstantiation = false; 1235 1236 // C++98 [temp.friend]p5: When a function is defined in a friend function 1237 // declaration in a class template, the function is defined at each 1238 // instantiation of the class template. The function is defined even if it 1239 // is never used. 1240 // C++11 [temp.friend]p4: When a function is defined in a friend function 1241 // declaration in a class template, the function is instantiated when the 1242 // function is odr-used. 1243 // 1244 // If -Wc++98-compat is enabled, we go through the motions of checking for a 1245 // redefinition, but don't instantiate the function. 1246 if ((!SemaRef.getLangOpts().CPlusPlus0x || 1247 SemaRef.Diags.getDiagnosticLevel( 1248 diag::warn_cxx98_compat_friend_redefinition, 1249 Function->getLocation()) 1250 != DiagnosticsEngine::Ignored) && 1251 D->isThisDeclarationADefinition()) { 1252 // Check for a function body. 1253 const FunctionDecl *Definition = 0; 1254 if (Function->isDefined(Definition) && 1255 Definition->getTemplateSpecializationKind() == TSK_Undeclared) { 1256 SemaRef.Diag(Function->getLocation(), 1257 SemaRef.getLangOpts().CPlusPlus0x ? 1258 diag::warn_cxx98_compat_friend_redefinition : 1259 diag::err_redefinition) << Function->getDeclName(); 1260 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition); 1261 if (!SemaRef.getLangOpts().CPlusPlus0x) 1262 Function->setInvalidDecl(); 1263 } 1264 // Check for redefinitions due to other instantiations of this or 1265 // a similar friend function. 1266 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(), 1267 REnd = Function->redecls_end(); 1268 R != REnd; ++R) { 1269 if (*R == Function) 1270 continue; 1271 switch (R->getFriendObjectKind()) { 1272 case Decl::FOK_None: 1273 if (!SemaRef.getLangOpts().CPlusPlus0x && 1274 !queuedInstantiation && R->isUsed(false)) { 1275 if (MemberSpecializationInfo *MSInfo 1276 = Function->getMemberSpecializationInfo()) { 1277 if (MSInfo->getPointOfInstantiation().isInvalid()) { 1278 SourceLocation Loc = R->getLocation(); // FIXME 1279 MSInfo->setPointOfInstantiation(Loc); 1280 SemaRef.PendingLocalImplicitInstantiations.push_back( 1281 std::make_pair(Function, Loc)); 1282 queuedInstantiation = true; 1283 } 1284 } 1285 } 1286 break; 1287 default: 1288 if (const FunctionDecl *RPattern 1289 = R->getTemplateInstantiationPattern()) 1290 if (RPattern->isDefined(RPattern)) { 1291 SemaRef.Diag(Function->getLocation(), 1292 SemaRef.getLangOpts().CPlusPlus0x ? 1293 diag::warn_cxx98_compat_friend_redefinition : 1294 diag::err_redefinition) 1295 << Function->getDeclName(); 1296 SemaRef.Diag(R->getLocation(), diag::note_previous_definition); 1297 if (!SemaRef.getLangOpts().CPlusPlus0x) 1298 Function->setInvalidDecl(); 1299 break; 1300 } 1301 } 1302 } 1303 } 1304 } 1305 1306 if (Function->isOverloadedOperator() && !DC->isRecord() && 1307 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1308 PrincipalDecl->setNonMemberOperator(); 1309 1310 assert(!D->isDefaulted() && "only methods should be defaulted"); 1311 return Function; 1312} 1313 1314Decl * 1315TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 1316 TemplateParameterList *TemplateParams, 1317 bool IsClassScopeSpecialization) { 1318 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1319 if (FunctionTemplate && !TemplateParams) { 1320 // We are creating a function template specialization from a function 1321 // template. Check whether there is already a function template 1322 // specialization for this particular set of template arguments. 1323 std::pair<const TemplateArgument *, unsigned> Innermost 1324 = TemplateArgs.getInnermost(); 1325 1326 void *InsertPos = 0; 1327 FunctionDecl *SpecFunc 1328 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second, 1329 InsertPos); 1330 1331 // If we already have a function template specialization, return it. 1332 if (SpecFunc) 1333 return SpecFunc; 1334 } 1335 1336 bool isFriend; 1337 if (FunctionTemplate) 1338 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1339 else 1340 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1341 1342 bool MergeWithParentScope = (TemplateParams != 0) || 1343 !(isa<Decl>(Owner) && 1344 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1345 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1346 1347 // Instantiate enclosing template arguments for friends. 1348 SmallVector<TemplateParameterList *, 4> TempParamLists; 1349 unsigned NumTempParamLists = 0; 1350 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 1351 TempParamLists.set_size(NumTempParamLists); 1352 for (unsigned I = 0; I != NumTempParamLists; ++I) { 1353 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 1354 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1355 if (!InstParams) 1356 return NULL; 1357 TempParamLists[I] = InstParams; 1358 } 1359 } 1360 1361 SmallVector<ParmVarDecl *, 4> Params; 1362 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1363 if (!TInfo) 1364 return 0; 1365 QualType T = TInfo->getType(); 1366 1367 // \brief If the type of this function, after ignoring parentheses, 1368 // is not *directly* a function type, then we're instantiating a function 1369 // that was declared via a typedef, e.g., 1370 // 1371 // typedef int functype(int, int); 1372 // functype func; 1373 // 1374 // In this case, we'll just go instantiate the ParmVarDecls that we 1375 // synthesized in the method declaration. 1376 if (!isa<FunctionProtoType>(T.IgnoreParens())) { 1377 assert(!Params.size() && "Instantiating type could not yield parameters"); 1378 SmallVector<QualType, 4> ParamTypes; 1379 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(), 1380 D->getNumParams(), TemplateArgs, ParamTypes, 1381 &Params)) 1382 return 0; 1383 } 1384 1385 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1386 if (QualifierLoc) { 1387 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1388 TemplateArgs); 1389 if (!QualifierLoc) 1390 return 0; 1391 } 1392 1393 DeclContext *DC = Owner; 1394 if (isFriend) { 1395 if (QualifierLoc) { 1396 CXXScopeSpec SS; 1397 SS.Adopt(QualifierLoc); 1398 DC = SemaRef.computeDeclContext(SS); 1399 1400 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 1401 return 0; 1402 } else { 1403 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 1404 D->getDeclContext(), 1405 TemplateArgs); 1406 } 1407 if (!DC) return 0; 1408 } 1409 1410 // Build the instantiated method declaration. 1411 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1412 CXXMethodDecl *Method = 0; 1413 1414 SourceLocation StartLoc = D->getInnerLocStart(); 1415 DeclarationNameInfo NameInfo 1416 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1417 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1418 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 1419 StartLoc, NameInfo, T, TInfo, 1420 Constructor->isExplicit(), 1421 Constructor->isInlineSpecified(), 1422 false, Constructor->isConstexpr()); 1423 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 1424 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 1425 StartLoc, NameInfo, T, TInfo, 1426 Destructor->isInlineSpecified(), 1427 false); 1428 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 1429 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 1430 StartLoc, NameInfo, T, TInfo, 1431 Conversion->isInlineSpecified(), 1432 Conversion->isExplicit(), 1433 Conversion->isConstexpr(), 1434 Conversion->getLocEnd()); 1435 } else { 1436 Method = CXXMethodDecl::Create(SemaRef.Context, Record, 1437 StartLoc, NameInfo, T, TInfo, 1438 D->isStatic(), 1439 D->getStorageClassAsWritten(), 1440 D->isInlineSpecified(), 1441 D->isConstexpr(), D->getLocEnd()); 1442 } 1443 1444 if (QualifierLoc) 1445 Method->setQualifierInfo(QualifierLoc); 1446 1447 if (TemplateParams) { 1448 // Our resulting instantiation is actually a function template, since we 1449 // are substituting only the outer template parameters. For example, given 1450 // 1451 // template<typename T> 1452 // struct X { 1453 // template<typename U> void f(T, U); 1454 // }; 1455 // 1456 // X<int> x; 1457 // 1458 // We are instantiating the member template "f" within X<int>, which means 1459 // substituting int for T, but leaving "f" as a member function template. 1460 // Build the function template itself. 1461 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 1462 Method->getLocation(), 1463 Method->getDeclName(), 1464 TemplateParams, Method); 1465 if (isFriend) { 1466 FunctionTemplate->setLexicalDeclContext(Owner); 1467 FunctionTemplate->setObjectOfFriendDecl(true); 1468 } else if (D->isOutOfLine()) 1469 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 1470 Method->setDescribedFunctionTemplate(FunctionTemplate); 1471 } else if (FunctionTemplate) { 1472 // Record this function template specialization. 1473 std::pair<const TemplateArgument *, unsigned> Innermost 1474 = TemplateArgs.getInnermost(); 1475 Method->setFunctionTemplateSpecialization(FunctionTemplate, 1476 TemplateArgumentList::CreateCopy(SemaRef.Context, 1477 Innermost.first, 1478 Innermost.second), 1479 /*InsertPos=*/0); 1480 } else if (!isFriend) { 1481 // Record that this is an instantiation of a member function. 1482 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1483 } 1484 1485 // If we are instantiating a member function defined 1486 // out-of-line, the instantiation will have the same lexical 1487 // context (which will be a namespace scope) as the template. 1488 if (isFriend) { 1489 if (NumTempParamLists) 1490 Method->setTemplateParameterListsInfo(SemaRef.Context, 1491 NumTempParamLists, 1492 TempParamLists.data()); 1493 1494 Method->setLexicalDeclContext(Owner); 1495 Method->setObjectOfFriendDecl(true); 1496 } else if (D->isOutOfLine()) 1497 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 1498 1499 // Attach the parameters 1500 for (unsigned P = 0; P < Params.size(); ++P) 1501 Params[P]->setOwningFunction(Method); 1502 Method->setParams(Params); 1503 1504 if (InitMethodInstantiation(Method, D)) 1505 Method->setInvalidDecl(); 1506 1507 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 1508 Sema::ForRedeclaration); 1509 1510 if (!FunctionTemplate || TemplateParams || isFriend) { 1511 SemaRef.LookupQualifiedName(Previous, Record); 1512 1513 // In C++, the previous declaration we find might be a tag type 1514 // (class or enum). In this case, the new declaration will hide the 1515 // tag type. Note that this does does not apply if we're declaring a 1516 // typedef (C++ [dcl.typedef]p4). 1517 if (Previous.isSingleTagDecl()) 1518 Previous.clear(); 1519 } 1520 1521 if (!IsClassScopeSpecialization) 1522 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false); 1523 1524 if (D->isPure()) 1525 SemaRef.CheckPureMethod(Method, SourceRange()); 1526 1527 Method->setAccess(D->getAccess()); 1528 1529 SemaRef.CheckOverrideControl(Method); 1530 1531 // If a function is defined as defaulted or deleted, mark it as such now. 1532 if (D->isDefaulted()) 1533 Method->setDefaulted(); 1534 if (D->isDeletedAsWritten()) 1535 Method->setDeletedAsWritten(); 1536 1537 if (FunctionTemplate) { 1538 // If there's a function template, let our caller handle it. 1539 } else if (Method->isInvalidDecl() && !Previous.empty()) { 1540 // Don't hide a (potentially) valid declaration with an invalid one. 1541 } else { 1542 NamedDecl *DeclToAdd = (TemplateParams 1543 ? cast<NamedDecl>(FunctionTemplate) 1544 : Method); 1545 if (isFriend) 1546 Record->makeDeclVisibleInContext(DeclToAdd); 1547 else if (!IsClassScopeSpecialization) 1548 Owner->addDecl(DeclToAdd); 1549 } 1550 1551 if (D->isExplicitlyDefaulted()) { 1552 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 1553 } else { 1554 assert(!D->isDefaulted() && 1555 "should not implicitly default uninstantiated function"); 1556 } 1557 1558 return Method; 1559} 1560 1561Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1562 return VisitCXXMethodDecl(D); 1563} 1564 1565Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1566 return VisitCXXMethodDecl(D); 1567} 1568 1569Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 1570 return VisitCXXMethodDecl(D); 1571} 1572 1573ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 1574 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, 1575 llvm::Optional<unsigned>(), 1576 /*ExpectParameterPack=*/false); 1577} 1578 1579Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1580 TemplateTypeParmDecl *D) { 1581 // TODO: don't always clone when decls are refcounted. 1582 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 1583 1584 TemplateTypeParmDecl *Inst = 1585 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, 1586 D->getLocStart(), D->getLocation(), 1587 D->getDepth() - TemplateArgs.getNumLevels(), 1588 D->getIndex(), D->getIdentifier(), 1589 D->wasDeclaredWithTypename(), 1590 D->isParameterPack()); 1591 Inst->setAccess(AS_public); 1592 1593 if (D->hasDefaultArgument()) 1594 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 1595 1596 // Introduce this template parameter's instantiation into the instantiation 1597 // scope. 1598 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1599 1600 return Inst; 1601} 1602 1603Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1604 NonTypeTemplateParmDecl *D) { 1605 // Substitute into the type of the non-type template parameter. 1606 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 1607 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 1608 SmallVector<QualType, 4> ExpandedParameterPackTypes; 1609 bool IsExpandedParameterPack = false; 1610 TypeSourceInfo *DI; 1611 QualType T; 1612 bool Invalid = false; 1613 1614 if (D->isExpandedParameterPack()) { 1615 // The non-type template parameter pack is an already-expanded pack 1616 // expansion of types. Substitute into each of the expanded types. 1617 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 1618 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 1619 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 1620 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), 1621 TemplateArgs, 1622 D->getLocation(), 1623 D->getDeclName()); 1624 if (!NewDI) 1625 return 0; 1626 1627 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1628 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(), 1629 D->getLocation()); 1630 if (NewT.isNull()) 1631 return 0; 1632 ExpandedParameterPackTypes.push_back(NewT); 1633 } 1634 1635 IsExpandedParameterPack = true; 1636 DI = D->getTypeSourceInfo(); 1637 T = DI->getType(); 1638 } else if (isa<PackExpansionTypeLoc>(TL)) { 1639 // The non-type template parameter pack's type is a pack expansion of types. 1640 // Determine whether we need to expand this parameter pack into separate 1641 // types. 1642 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL); 1643 TypeLoc Pattern = Expansion.getPatternLoc(); 1644 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1645 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 1646 1647 // Determine whether the set of unexpanded parameter packs can and should 1648 // be expanded. 1649 bool Expand = true; 1650 bool RetainExpansion = false; 1651 llvm::Optional<unsigned> OrigNumExpansions 1652 = Expansion.getTypePtr()->getNumExpansions(); 1653 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions; 1654 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 1655 Pattern.getSourceRange(), 1656 Unexpanded, 1657 TemplateArgs, 1658 Expand, RetainExpansion, 1659 NumExpansions)) 1660 return 0; 1661 1662 if (Expand) { 1663 for (unsigned I = 0; I != *NumExpansions; ++I) { 1664 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 1665 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 1666 D->getLocation(), 1667 D->getDeclName()); 1668 if (!NewDI) 1669 return 0; 1670 1671 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1672 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType( 1673 NewDI->getType(), 1674 D->getLocation()); 1675 if (NewT.isNull()) 1676 return 0; 1677 ExpandedParameterPackTypes.push_back(NewT); 1678 } 1679 1680 // Note that we have an expanded parameter pack. The "type" of this 1681 // expanded parameter pack is the original expansion type, but callers 1682 // will end up using the expanded parameter pack types for type-checking. 1683 IsExpandedParameterPack = true; 1684 DI = D->getTypeSourceInfo(); 1685 T = DI->getType(); 1686 } else { 1687 // We cannot fully expand the pack expansion now, so substitute into the 1688 // pattern and create a new pack expansion type. 1689 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 1690 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 1691 D->getLocation(), 1692 D->getDeclName()); 1693 if (!NewPattern) 1694 return 0; 1695 1696 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 1697 NumExpansions); 1698 if (!DI) 1699 return 0; 1700 1701 T = DI->getType(); 1702 } 1703 } else { 1704 // Simple case: substitution into a parameter that is not a parameter pack. 1705 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 1706 D->getLocation(), D->getDeclName()); 1707 if (!DI) 1708 return 0; 1709 1710 // Check that this type is acceptable for a non-type template parameter. 1711 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(), 1712 D->getLocation()); 1713 if (T.isNull()) { 1714 T = SemaRef.Context.IntTy; 1715 Invalid = true; 1716 } 1717 } 1718 1719 NonTypeTemplateParmDecl *Param; 1720 if (IsExpandedParameterPack) 1721 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1722 D->getInnerLocStart(), 1723 D->getLocation(), 1724 D->getDepth() - TemplateArgs.getNumLevels(), 1725 D->getPosition(), 1726 D->getIdentifier(), T, 1727 DI, 1728 ExpandedParameterPackTypes.data(), 1729 ExpandedParameterPackTypes.size(), 1730 ExpandedParameterPackTypesAsWritten.data()); 1731 else 1732 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1733 D->getInnerLocStart(), 1734 D->getLocation(), 1735 D->getDepth() - TemplateArgs.getNumLevels(), 1736 D->getPosition(), 1737 D->getIdentifier(), T, 1738 D->isParameterPack(), DI); 1739 1740 Param->setAccess(AS_public); 1741 if (Invalid) 1742 Param->setInvalidDecl(); 1743 1744 Param->setDefaultArgument(D->getDefaultArgument(), false); 1745 1746 // Introduce this template parameter's instantiation into the instantiation 1747 // scope. 1748 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1749 return Param; 1750} 1751 1752Decl * 1753TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1754 TemplateTemplateParmDecl *D) { 1755 // Instantiate the template parameter list of the template template parameter. 1756 TemplateParameterList *TempParams = D->getTemplateParameters(); 1757 TemplateParameterList *InstParams; 1758 { 1759 // Perform the actual substitution of template parameters within a new, 1760 // local instantiation scope. 1761 LocalInstantiationScope Scope(SemaRef); 1762 InstParams = SubstTemplateParams(TempParams); 1763 if (!InstParams) 1764 return NULL; 1765 } 1766 1767 // Build the template template parameter. 1768 TemplateTemplateParmDecl *Param 1769 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1770 D->getDepth() - TemplateArgs.getNumLevels(), 1771 D->getPosition(), D->isParameterPack(), 1772 D->getIdentifier(), InstParams); 1773 Param->setDefaultArgument(D->getDefaultArgument(), false); 1774 Param->setAccess(AS_public); 1775 1776 // Introduce this template parameter's instantiation into the instantiation 1777 // scope. 1778 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1779 1780 return Param; 1781} 1782 1783Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1784 // Using directives are never dependent (and never contain any types or 1785 // expressions), so they require no explicit instantiation work. 1786 1787 UsingDirectiveDecl *Inst 1788 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1789 D->getNamespaceKeyLocation(), 1790 D->getQualifierLoc(), 1791 D->getIdentLocation(), 1792 D->getNominatedNamespace(), 1793 D->getCommonAncestor()); 1794 Owner->addDecl(Inst); 1795 return Inst; 1796} 1797 1798Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 1799 1800 // The nested name specifier may be dependent, for example 1801 // template <typename T> struct t { 1802 // struct s1 { T f1(); }; 1803 // struct s2 : s1 { using s1::f1; }; 1804 // }; 1805 // template struct t<int>; 1806 // Here, in using s1::f1, s1 refers to t<T>::s1; 1807 // we need to substitute for t<int>::s1. 1808 NestedNameSpecifierLoc QualifierLoc 1809 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 1810 TemplateArgs); 1811 if (!QualifierLoc) 1812 return 0; 1813 1814 // The name info is non-dependent, so no transformation 1815 // is required. 1816 DeclarationNameInfo NameInfo = D->getNameInfo(); 1817 1818 // We only need to do redeclaration lookups if we're in a class 1819 // scope (in fact, it's not really even possible in non-class 1820 // scopes). 1821 bool CheckRedeclaration = Owner->isRecord(); 1822 1823 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 1824 Sema::ForRedeclaration); 1825 1826 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 1827 D->getUsingLocation(), 1828 QualifierLoc, 1829 NameInfo, 1830 D->isTypeName()); 1831 1832 CXXScopeSpec SS; 1833 SS.Adopt(QualifierLoc); 1834 if (CheckRedeclaration) { 1835 Prev.setHideTags(false); 1836 SemaRef.LookupQualifiedName(Prev, Owner); 1837 1838 // Check for invalid redeclarations. 1839 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(), 1840 D->isTypeName(), SS, 1841 D->getLocation(), Prev)) 1842 NewUD->setInvalidDecl(); 1843 1844 } 1845 1846 if (!NewUD->isInvalidDecl() && 1847 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS, 1848 D->getLocation())) 1849 NewUD->setInvalidDecl(); 1850 1851 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 1852 NewUD->setAccess(D->getAccess()); 1853 Owner->addDecl(NewUD); 1854 1855 // Don't process the shadow decls for an invalid decl. 1856 if (NewUD->isInvalidDecl()) 1857 return NewUD; 1858 1859 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 1860 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD)) 1861 NewUD->setInvalidDecl(); 1862 return NewUD; 1863 } 1864 1865 bool isFunctionScope = Owner->isFunctionOrMethod(); 1866 1867 // Process the shadow decls. 1868 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 1869 I != E; ++I) { 1870 UsingShadowDecl *Shadow = *I; 1871 NamedDecl *InstTarget = 1872 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 1873 Shadow->getLocation(), 1874 Shadow->getTargetDecl(), 1875 TemplateArgs)); 1876 if (!InstTarget) 1877 return 0; 1878 1879 if (CheckRedeclaration && 1880 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev)) 1881 continue; 1882 1883 UsingShadowDecl *InstShadow 1884 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget); 1885 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 1886 1887 if (isFunctionScope) 1888 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 1889 } 1890 1891 return NewUD; 1892} 1893 1894Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 1895 // Ignore these; we handle them in bulk when processing the UsingDecl. 1896 return 0; 1897} 1898 1899Decl * TemplateDeclInstantiator 1900 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 1901 NestedNameSpecifierLoc QualifierLoc 1902 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 1903 TemplateArgs); 1904 if (!QualifierLoc) 1905 return 0; 1906 1907 CXXScopeSpec SS; 1908 SS.Adopt(QualifierLoc); 1909 1910 // Since NameInfo refers to a typename, it cannot be a C++ special name. 1911 // Hence, no tranformation is required for it. 1912 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation()); 1913 NamedDecl *UD = 1914 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1915 D->getUsingLoc(), SS, NameInfo, 0, 1916 /*instantiation*/ true, 1917 /*typename*/ true, D->getTypenameLoc()); 1918 if (UD) 1919 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1920 1921 return UD; 1922} 1923 1924Decl * TemplateDeclInstantiator 1925 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1926 NestedNameSpecifierLoc QualifierLoc 1927 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs); 1928 if (!QualifierLoc) 1929 return 0; 1930 1931 CXXScopeSpec SS; 1932 SS.Adopt(QualifierLoc); 1933 1934 DeclarationNameInfo NameInfo 1935 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1936 1937 NamedDecl *UD = 1938 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1939 D->getUsingLoc(), SS, NameInfo, 0, 1940 /*instantiation*/ true, 1941 /*typename*/ false, SourceLocation()); 1942 if (UD) 1943 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1944 1945 return UD; 1946} 1947 1948 1949Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 1950 ClassScopeFunctionSpecializationDecl *Decl) { 1951 CXXMethodDecl *OldFD = Decl->getSpecialization(); 1952 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 0, true)); 1953 1954 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName, 1955 Sema::ForRedeclaration); 1956 1957 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext); 1958 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, 0, Previous)) { 1959 NewFD->setInvalidDecl(); 1960 return NewFD; 1961 } 1962 1963 // Associate the specialization with the pattern. 1964 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl()); 1965 assert(Specialization && "Class scope Specialization is null"); 1966 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD); 1967 1968 return NewFD; 1969} 1970 1971Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 1972 const MultiLevelTemplateArgumentList &TemplateArgs) { 1973 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 1974 if (D->isInvalidDecl()) 1975 return 0; 1976 1977 return Instantiator.Visit(D); 1978} 1979 1980/// \brief Instantiates a nested template parameter list in the current 1981/// instantiation context. 1982/// 1983/// \param L The parameter list to instantiate 1984/// 1985/// \returns NULL if there was an error 1986TemplateParameterList * 1987TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 1988 // Get errors for all the parameters before bailing out. 1989 bool Invalid = false; 1990 1991 unsigned N = L->size(); 1992 typedef SmallVector<NamedDecl *, 8> ParamVector; 1993 ParamVector Params; 1994 Params.reserve(N); 1995 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 1996 PI != PE; ++PI) { 1997 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 1998 Params.push_back(D); 1999 Invalid = Invalid || !D || D->isInvalidDecl(); 2000 } 2001 2002 // Clean up if we had an error. 2003 if (Invalid) 2004 return NULL; 2005 2006 TemplateParameterList *InstL 2007 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 2008 L->getLAngleLoc(), &Params.front(), N, 2009 L->getRAngleLoc()); 2010 return InstL; 2011} 2012 2013/// \brief Instantiate the declaration of a class template partial 2014/// specialization. 2015/// 2016/// \param ClassTemplate the (instantiated) class template that is partially 2017// specialized by the instantiation of \p PartialSpec. 2018/// 2019/// \param PartialSpec the (uninstantiated) class template partial 2020/// specialization that we are instantiating. 2021/// 2022/// \returns The instantiated partial specialization, if successful; otherwise, 2023/// NULL to indicate an error. 2024ClassTemplatePartialSpecializationDecl * 2025TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 2026 ClassTemplateDecl *ClassTemplate, 2027 ClassTemplatePartialSpecializationDecl *PartialSpec) { 2028 // Create a local instantiation scope for this class template partial 2029 // specialization, which will contain the instantiations of the template 2030 // parameters. 2031 LocalInstantiationScope Scope(SemaRef); 2032 2033 // Substitute into the template parameters of the class template partial 2034 // specialization. 2035 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 2036 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2037 if (!InstParams) 2038 return 0; 2039 2040 // Substitute into the template arguments of the class template partial 2041 // specialization. 2042 TemplateArgumentListInfo InstTemplateArgs; // no angle locations 2043 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(), 2044 PartialSpec->getNumTemplateArgsAsWritten(), 2045 InstTemplateArgs, TemplateArgs)) 2046 return 0; 2047 2048 // Check that the template argument list is well-formed for this 2049 // class template. 2050 SmallVector<TemplateArgument, 4> Converted; 2051 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 2052 PartialSpec->getLocation(), 2053 InstTemplateArgs, 2054 false, 2055 Converted)) 2056 return 0; 2057 2058 // Figure out where to insert this class template partial specialization 2059 // in the member template's set of class template partial specializations. 2060 void *InsertPos = 0; 2061 ClassTemplateSpecializationDecl *PrevDecl 2062 = ClassTemplate->findPartialSpecialization(Converted.data(), 2063 Converted.size(), InsertPos); 2064 2065 // Build the canonical type that describes the converted template 2066 // arguments of the class template partial specialization. 2067 QualType CanonType 2068 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 2069 Converted.data(), 2070 Converted.size()); 2071 2072 // Build the fully-sugared type for this class template 2073 // specialization as the user wrote in the specialization 2074 // itself. This means that we'll pretty-print the type retrieved 2075 // from the specialization's declaration the way that the user 2076 // actually wrote the specialization, rather than formatting the 2077 // name based on the "canonical" representation used to store the 2078 // template arguments in the specialization. 2079 TypeSourceInfo *WrittenTy 2080 = SemaRef.Context.getTemplateSpecializationTypeInfo( 2081 TemplateName(ClassTemplate), 2082 PartialSpec->getLocation(), 2083 InstTemplateArgs, 2084 CanonType); 2085 2086 if (PrevDecl) { 2087 // We've already seen a partial specialization with the same template 2088 // parameters and template arguments. This can happen, for example, when 2089 // substituting the outer template arguments ends up causing two 2090 // class template partial specializations of a member class template 2091 // to have identical forms, e.g., 2092 // 2093 // template<typename T, typename U> 2094 // struct Outer { 2095 // template<typename X, typename Y> struct Inner; 2096 // template<typename Y> struct Inner<T, Y>; 2097 // template<typename Y> struct Inner<U, Y>; 2098 // }; 2099 // 2100 // Outer<int, int> outer; // error: the partial specializations of Inner 2101 // // have the same signature. 2102 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 2103 << WrittenTy->getType(); 2104 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 2105 << SemaRef.Context.getTypeDeclType(PrevDecl); 2106 return 0; 2107 } 2108 2109 2110 // Create the class template partial specialization declaration. 2111 ClassTemplatePartialSpecializationDecl *InstPartialSpec 2112 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, 2113 PartialSpec->getTagKind(), 2114 Owner, 2115 PartialSpec->getLocStart(), 2116 PartialSpec->getLocation(), 2117 InstParams, 2118 ClassTemplate, 2119 Converted.data(), 2120 Converted.size(), 2121 InstTemplateArgs, 2122 CanonType, 2123 0, 2124 ClassTemplate->getNextPartialSpecSequenceNumber()); 2125 // Substitute the nested name specifier, if any. 2126 if (SubstQualifier(PartialSpec, InstPartialSpec)) 2127 return 0; 2128 2129 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 2130 InstPartialSpec->setTypeAsWritten(WrittenTy); 2131 2132 // Add this partial specialization to the set of class template partial 2133 // specializations. 2134 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0); 2135 return InstPartialSpec; 2136} 2137 2138TypeSourceInfo* 2139TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 2140 SmallVectorImpl<ParmVarDecl *> &Params) { 2141 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 2142 assert(OldTInfo && "substituting function without type source info"); 2143 assert(Params.empty() && "parameter vector is non-empty at start"); 2144 2145 CXXRecordDecl *ThisContext = 0; 2146 unsigned ThisTypeQuals = 0; 2147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 2148 ThisContext = Method->getParent(); 2149 ThisTypeQuals = Method->getTypeQualifiers(); 2150 } 2151 2152 TypeSourceInfo *NewTInfo 2153 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 2154 D->getTypeSpecStartLoc(), 2155 D->getDeclName(), 2156 ThisContext, ThisTypeQuals); 2157 if (!NewTInfo) 2158 return 0; 2159 2160 if (NewTInfo != OldTInfo) { 2161 // Get parameters from the new type info. 2162 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 2163 if (FunctionProtoTypeLoc *OldProtoLoc 2164 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 2165 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 2166 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL); 2167 assert(NewProtoLoc && "Missing prototype?"); 2168 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs(); 2169 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs(); 2170 OldIdx != NumOldParams; ++OldIdx) { 2171 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx); 2172 if (!OldParam->isParameterPack() || 2173 // FIXME: Is this right? OldParam could expand to an empty parameter 2174 // pack and the next parameter could be an unexpanded parameter pack 2175 (NewIdx < NumNewParams && 2176 NewProtoLoc->getArg(NewIdx)->isParameterPack())) { 2177 // Simple case: normal parameter, or a parameter pack that's 2178 // instantiated to a (still-dependent) parameter pack. 2179 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++); 2180 Params.push_back(NewParam); 2181 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, 2182 NewParam); 2183 continue; 2184 } 2185 2186 // Parameter pack: make the instantiation an argument pack. 2187 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack( 2188 OldParam); 2189 unsigned NumArgumentsInExpansion 2190 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 2191 TemplateArgs); 2192 while (NumArgumentsInExpansion--) { 2193 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++); 2194 Params.push_back(NewParam); 2195 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam, 2196 NewParam); 2197 } 2198 } 2199 } 2200 } else { 2201 // The function type itself was not dependent and therefore no 2202 // substitution occurred. However, we still need to instantiate 2203 // the function parameters themselves. 2204 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 2205 if (FunctionProtoTypeLoc *OldProtoLoc 2206 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 2207 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) { 2208 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i)); 2209 if (!Parm) 2210 return 0; 2211 Params.push_back(Parm); 2212 } 2213 } 2214 } 2215 return NewTInfo; 2216} 2217 2218/// Introduce the instantiated function parameters into the local 2219/// instantiation scope, and set the parameter names to those used 2220/// in the template. 2221static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 2222 const FunctionDecl *PatternDecl, 2223 LocalInstantiationScope &Scope, 2224 const MultiLevelTemplateArgumentList &TemplateArgs) { 2225 unsigned FParamIdx = 0; 2226 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 2227 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 2228 if (!PatternParam->isParameterPack()) { 2229 // Simple case: not a parameter pack. 2230 assert(FParamIdx < Function->getNumParams()); 2231 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 2232 FunctionParam->setDeclName(PatternParam->getDeclName()); 2233 Scope.InstantiatedLocal(PatternParam, FunctionParam); 2234 ++FParamIdx; 2235 continue; 2236 } 2237 2238 // Expand the parameter pack. 2239 Scope.MakeInstantiatedLocalArgPack(PatternParam); 2240 unsigned NumArgumentsInExpansion 2241 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 2242 for (unsigned Arg = 0; Arg < NumArgumentsInExpansion; ++Arg) { 2243 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 2244 FunctionParam->setDeclName(PatternParam->getDeclName()); 2245 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 2246 ++FParamIdx; 2247 } 2248 } 2249} 2250 2251static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New, 2252 const FunctionProtoType *Proto, 2253 const MultiLevelTemplateArgumentList &TemplateArgs) { 2254 // C++11 [expr.prim.general]p3: 2255 // If a declaration declares a member function or member function 2256 // template of a class X, the expression this is a prvalue of type 2257 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 2258 // and the end of the function-definition, member-declarator, or 2259 // declarator. 2260 CXXRecordDecl *ThisContext = 0; 2261 unsigned ThisTypeQuals = 0; 2262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) { 2263 ThisContext = Method->getParent(); 2264 ThisTypeQuals = Method->getTypeQualifiers(); 2265 } 2266 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals, 2267 SemaRef.getLangOpts().CPlusPlus0x); 2268 2269 // The function has an exception specification or a "noreturn" 2270 // attribute. Substitute into each of the exception types. 2271 SmallVector<QualType, 4> Exceptions; 2272 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 2273 // FIXME: Poor location information! 2274 if (const PackExpansionType *PackExpansion 2275 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) { 2276 // We have a pack expansion. Instantiate it. 2277 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2278 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(), 2279 Unexpanded); 2280 assert(!Unexpanded.empty() && 2281 "Pack expansion without parameter packs?"); 2282 2283 bool Expand = false; 2284 bool RetainExpansion = false; 2285 llvm::Optional<unsigned> NumExpansions 2286 = PackExpansion->getNumExpansions(); 2287 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(), 2288 SourceRange(), 2289 Unexpanded, 2290 TemplateArgs, 2291 Expand, 2292 RetainExpansion, 2293 NumExpansions)) 2294 break; 2295 2296 if (!Expand) { 2297 // We can't expand this pack expansion into separate arguments yet; 2298 // just substitute into the pattern and create a new pack expansion 2299 // type. 2300 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2301 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 2302 TemplateArgs, 2303 New->getLocation(), New->getDeclName()); 2304 if (T.isNull()) 2305 break; 2306 2307 T = SemaRef.Context.getPackExpansionType(T, NumExpansions); 2308 Exceptions.push_back(T); 2309 continue; 2310 } 2311 2312 // Substitute into the pack expansion pattern for each template 2313 bool Invalid = false; 2314 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) { 2315 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx); 2316 2317 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 2318 TemplateArgs, 2319 New->getLocation(), New->getDeclName()); 2320 if (T.isNull()) { 2321 Invalid = true; 2322 break; 2323 } 2324 2325 Exceptions.push_back(T); 2326 } 2327 2328 if (Invalid) 2329 break; 2330 2331 continue; 2332 } 2333 2334 QualType T 2335 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 2336 New->getLocation(), New->getDeclName()); 2337 if (T.isNull() || 2338 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 2339 continue; 2340 2341 Exceptions.push_back(T); 2342 } 2343 Expr *NoexceptExpr = 0; 2344 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) { 2345 EnterExpressionEvaluationContext Unevaluated(SemaRef, 2346 Sema::ConstantEvaluated); 2347 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs); 2348 if (E.isUsable()) 2349 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart()); 2350 2351 if (E.isUsable()) { 2352 NoexceptExpr = E.take(); 2353 if (!NoexceptExpr->isTypeDependent() && 2354 !NoexceptExpr->isValueDependent()) 2355 NoexceptExpr = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr, 2356 0, SemaRef.PDiag(diag::err_noexcept_needs_constant_expression), 2357 /*AllowFold*/ false).take(); 2358 } 2359 } 2360 2361 // Rebuild the function type 2362 const FunctionProtoType *NewProto 2363 = New->getType()->getAs<FunctionProtoType>(); 2364 assert(NewProto && "Template instantiation without function prototype?"); 2365 2366 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo(); 2367 EPI.ExceptionSpecType = Proto->getExceptionSpecType(); 2368 EPI.NumExceptions = Exceptions.size(); 2369 EPI.Exceptions = Exceptions.data(); 2370 EPI.NoexceptExpr = NoexceptExpr; 2371 2372 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 2373 NewProto->arg_type_begin(), 2374 NewProto->getNumArgs(), 2375 EPI)); 2376} 2377 2378void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 2379 FunctionDecl *Decl) { 2380 FunctionDecl *Tmpl = Decl->getTemplateInstantiationPattern(); 2381 assert(Tmpl && "can't instantiate non-template"); 2382 2383 if (Decl->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() 2384 != EST_Uninstantiated) 2385 return; 2386 2387 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 2388 InstantiatingTemplate::ExceptionSpecification()); 2389 if (Inst) 2390 return; 2391 2392 // Enter the scope of this instantiation. We don't use 2393 // PushDeclContext because we don't have a scope. 2394 Sema::ContextRAII savedContext(*this, Decl); 2395 LocalInstantiationScope Scope(*this); 2396 2397 MultiLevelTemplateArgumentList TemplateArgs = 2398 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true); 2399 2400 addInstantiatedParametersToScope(*this, Decl, Tmpl, Scope, TemplateArgs); 2401 2402 const FunctionProtoType *Proto = Tmpl->getType()->castAs<FunctionProtoType>(); 2403 ::InstantiateExceptionSpec(*this, Decl, Proto, TemplateArgs); 2404} 2405 2406/// \brief Initializes the common fields of an instantiation function 2407/// declaration (New) from the corresponding fields of its template (Tmpl). 2408/// 2409/// \returns true if there was an error 2410bool 2411TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 2412 FunctionDecl *Tmpl) { 2413 if (Tmpl->isDeletedAsWritten()) 2414 New->setDeletedAsWritten(); 2415 2416 // If we are performing substituting explicitly-specified template arguments 2417 // or deduced template arguments into a function template and we reach this 2418 // point, we are now past the point where SFINAE applies and have committed 2419 // to keeping the new function template specialization. We therefore 2420 // convert the active template instantiation for the function template 2421 // into a template instantiation for this specific function template 2422 // specialization, which is not a SFINAE context, so that we diagnose any 2423 // further errors in the declaration itself. 2424 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 2425 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 2426 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 2427 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 2428 if (FunctionTemplateDecl *FunTmpl 2429 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 2430 assert(FunTmpl->getTemplatedDecl() == Tmpl && 2431 "Deduction from the wrong function template?"); 2432 (void) FunTmpl; 2433 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 2434 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 2435 --SemaRef.NonInstantiationEntries; 2436 } 2437 } 2438 2439 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 2440 assert(Proto && "Function template without prototype?"); 2441 2442 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 2443 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 2444 2445 // DR1330: In C++11, defer instantiation of a non-trivial 2446 // exception specification. 2447 if (SemaRef.getLangOpts().CPlusPlus0x && 2448 EPI.ExceptionSpecType != EST_None && 2449 EPI.ExceptionSpecType != EST_DynamicNone && 2450 EPI.ExceptionSpecType != EST_BasicNoexcept) { 2451 // Mark the function has having an uninstantiated exception specification. 2452 const FunctionProtoType *NewProto 2453 = New->getType()->getAs<FunctionProtoType>(); 2454 assert(NewProto && "Template instantiation without function prototype?"); 2455 EPI = NewProto->getExtProtoInfo(); 2456 EPI.ExceptionSpecType = EST_Uninstantiated; 2457 EPI.ExceptionSpecDecl = New; 2458 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 2459 NewProto->arg_type_begin(), 2460 NewProto->getNumArgs(), 2461 EPI)); 2462 } else { 2463 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs); 2464 } 2465 } 2466 2467 // Get the definition. Leaves the variable unchanged if undefined. 2468 const FunctionDecl *Definition = Tmpl; 2469 Tmpl->isDefined(Definition); 2470 2471 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 2472 LateAttrs, StartingScope); 2473 2474 return false; 2475} 2476 2477/// \brief Initializes common fields of an instantiated method 2478/// declaration (New) from the corresponding fields of its template 2479/// (Tmpl). 2480/// 2481/// \returns true if there was an error 2482bool 2483TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 2484 CXXMethodDecl *Tmpl) { 2485 if (InitFunctionInstantiation(New, Tmpl)) 2486 return true; 2487 2488 New->setAccess(Tmpl->getAccess()); 2489 if (Tmpl->isVirtualAsWritten()) 2490 New->setVirtualAsWritten(true); 2491 2492 // FIXME: attributes 2493 // FIXME: New needs a pointer to Tmpl 2494 return false; 2495} 2496 2497/// \brief Instantiate the definition of the given function from its 2498/// template. 2499/// 2500/// \param PointOfInstantiation the point at which the instantiation was 2501/// required. Note that this is not precisely a "point of instantiation" 2502/// for the function, but it's close. 2503/// 2504/// \param Function the already-instantiated declaration of a 2505/// function template specialization or member function of a class template 2506/// specialization. 2507/// 2508/// \param Recursive if true, recursively instantiates any functions that 2509/// are required by this instantiation. 2510/// 2511/// \param DefinitionRequired if true, then we are performing an explicit 2512/// instantiation where the body of the function is required. Complain if 2513/// there is no such body. 2514void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 2515 FunctionDecl *Function, 2516 bool Recursive, 2517 bool DefinitionRequired) { 2518 if (Function->isInvalidDecl() || Function->isDefined()) 2519 return; 2520 2521 // Never instantiate an explicit specialization except if it is a class scope 2522 // explicit specialization. 2523 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 2524 !Function->getClassScopeSpecializationPattern()) 2525 return; 2526 2527 // Find the function body that we'll be substituting. 2528 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 2529 assert(PatternDecl && "instantiating a non-template"); 2530 2531 Stmt *Pattern = PatternDecl->getBody(PatternDecl); 2532 assert(PatternDecl && "template definition is not a template"); 2533 if (!Pattern) { 2534 // Try to find a defaulted definition 2535 PatternDecl->isDefined(PatternDecl); 2536 } 2537 assert(PatternDecl && "template definition is not a template"); 2538 2539 // Postpone late parsed template instantiations. 2540 if (PatternDecl->isLateTemplateParsed() && 2541 !LateTemplateParser) { 2542 PendingInstantiations.push_back( 2543 std::make_pair(Function, PointOfInstantiation)); 2544 return; 2545 } 2546 2547 // Call the LateTemplateParser callback if there a need to late parse 2548 // a templated function definition. 2549 if (!Pattern && PatternDecl->isLateTemplateParsed() && 2550 LateTemplateParser) { 2551 LateTemplateParser(OpaqueParser, PatternDecl); 2552 Pattern = PatternDecl->getBody(PatternDecl); 2553 } 2554 2555 if (!Pattern && !PatternDecl->isDefaulted()) { 2556 if (DefinitionRequired) { 2557 if (Function->getPrimaryTemplate()) 2558 Diag(PointOfInstantiation, 2559 diag::err_explicit_instantiation_undefined_func_template) 2560 << Function->getPrimaryTemplate(); 2561 else 2562 Diag(PointOfInstantiation, 2563 diag::err_explicit_instantiation_undefined_member) 2564 << 1 << Function->getDeclName() << Function->getDeclContext(); 2565 2566 if (PatternDecl) 2567 Diag(PatternDecl->getLocation(), 2568 diag::note_explicit_instantiation_here); 2569 Function->setInvalidDecl(); 2570 } else if (Function->getTemplateSpecializationKind() 2571 == TSK_ExplicitInstantiationDefinition) { 2572 PendingInstantiations.push_back( 2573 std::make_pair(Function, PointOfInstantiation)); 2574 } 2575 2576 return; 2577 } 2578 2579 // C++0x [temp.explicit]p9: 2580 // Except for inline functions, other explicit instantiation declarations 2581 // have the effect of suppressing the implicit instantiation of the entity 2582 // to which they refer. 2583 if (Function->getTemplateSpecializationKind() 2584 == TSK_ExplicitInstantiationDeclaration && 2585 !PatternDecl->isInlined()) 2586 return; 2587 2588 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 2589 if (Inst) 2590 return; 2591 2592 // Copy the inner loc start from the pattern. 2593 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 2594 2595 // If we're performing recursive template instantiation, create our own 2596 // queue of pending implicit instantiations that we will instantiate later, 2597 // while we're still within our own instantiation context. 2598 SmallVector<VTableUse, 16> SavedVTableUses; 2599 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 2600 if (Recursive) { 2601 VTableUses.swap(SavedVTableUses); 2602 PendingInstantiations.swap(SavedPendingInstantiations); 2603 } 2604 2605 EnterExpressionEvaluationContext EvalContext(*this, 2606 Sema::PotentiallyEvaluated); 2607 ActOnStartOfFunctionDef(0, Function); 2608 2609 // Introduce a new scope where local variable instantiations will be 2610 // recorded, unless we're actually a member function within a local 2611 // class, in which case we need to merge our results with the parent 2612 // scope (of the enclosing function). 2613 bool MergeWithParentScope = false; 2614 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 2615 MergeWithParentScope = Rec->isLocalClass(); 2616 2617 LocalInstantiationScope Scope(*this, MergeWithParentScope); 2618 2619 // Enter the scope of this instantiation. We don't use 2620 // PushDeclContext because we don't have a scope. 2621 Sema::ContextRAII savedContext(*this, Function); 2622 2623 MultiLevelTemplateArgumentList TemplateArgs = 2624 getTemplateInstantiationArgs(Function, 0, false, PatternDecl); 2625 2626 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 2627 TemplateArgs); 2628 2629 if (PatternDecl->isDefaulted()) { 2630 ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true); 2631 2632 SetDeclDefaulted(Function, PatternDecl->getLocation()); 2633 } else { 2634 // If this is a constructor, instantiate the member initializers. 2635 if (const CXXConstructorDecl *Ctor = 2636 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 2637 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 2638 TemplateArgs); 2639 } 2640 2641 // Instantiate the function body. 2642 StmtResult Body = SubstStmt(Pattern, TemplateArgs); 2643 2644 if (Body.isInvalid()) 2645 Function->setInvalidDecl(); 2646 2647 ActOnFinishFunctionBody(Function, Body.get(), 2648 /*IsInstantiation=*/true); 2649 } 2650 2651 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 2652 2653 savedContext.pop(); 2654 2655 DeclGroupRef DG(Function); 2656 Consumer.HandleTopLevelDecl(DG); 2657 2658 // This class may have local implicit instantiations that need to be 2659 // instantiation within this scope. 2660 PerformPendingInstantiations(/*LocalOnly=*/true); 2661 Scope.Exit(); 2662 2663 if (Recursive) { 2664 // Define any pending vtables. 2665 DefineUsedVTables(); 2666 2667 // Instantiate any pending implicit instantiations found during the 2668 // instantiation of this template. 2669 PerformPendingInstantiations(); 2670 2671 // Restore the set of pending vtables. 2672 assert(VTableUses.empty() && 2673 "VTableUses should be empty before it is discarded."); 2674 VTableUses.swap(SavedVTableUses); 2675 2676 // Restore the set of pending implicit instantiations. 2677 assert(PendingInstantiations.empty() && 2678 "PendingInstantiations should be empty before it is discarded."); 2679 PendingInstantiations.swap(SavedPendingInstantiations); 2680 } 2681} 2682 2683/// \brief Instantiate the definition of the given variable from its 2684/// template. 2685/// 2686/// \param PointOfInstantiation the point at which the instantiation was 2687/// required. Note that this is not precisely a "point of instantiation" 2688/// for the function, but it's close. 2689/// 2690/// \param Var the already-instantiated declaration of a static member 2691/// variable of a class template specialization. 2692/// 2693/// \param Recursive if true, recursively instantiates any functions that 2694/// are required by this instantiation. 2695/// 2696/// \param DefinitionRequired if true, then we are performing an explicit 2697/// instantiation where an out-of-line definition of the member variable 2698/// is required. Complain if there is no such definition. 2699void Sema::InstantiateStaticDataMemberDefinition( 2700 SourceLocation PointOfInstantiation, 2701 VarDecl *Var, 2702 bool Recursive, 2703 bool DefinitionRequired) { 2704 if (Var->isInvalidDecl()) 2705 return; 2706 2707 // Find the out-of-line definition of this static data member. 2708 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 2709 assert(Def && "This data member was not instantiated from a template?"); 2710 assert(Def->isStaticDataMember() && "Not a static data member?"); 2711 Def = Def->getOutOfLineDefinition(); 2712 2713 if (!Def) { 2714 // We did not find an out-of-line definition of this static data member, 2715 // so we won't perform any instantiation. Rather, we rely on the user to 2716 // instantiate this definition (or provide a specialization for it) in 2717 // another translation unit. 2718 if (DefinitionRequired) { 2719 Def = Var->getInstantiatedFromStaticDataMember(); 2720 Diag(PointOfInstantiation, 2721 diag::err_explicit_instantiation_undefined_member) 2722 << 2 << Var->getDeclName() << Var->getDeclContext(); 2723 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 2724 } else if (Var->getTemplateSpecializationKind() 2725 == TSK_ExplicitInstantiationDefinition) { 2726 PendingInstantiations.push_back( 2727 std::make_pair(Var, PointOfInstantiation)); 2728 } 2729 2730 return; 2731 } 2732 2733 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 2734 2735 // Never instantiate an explicit specialization. 2736 if (TSK == TSK_ExplicitSpecialization) 2737 return; 2738 2739 // C++0x [temp.explicit]p9: 2740 // Except for inline functions, other explicit instantiation declarations 2741 // have the effect of suppressing the implicit instantiation of the entity 2742 // to which they refer. 2743 if (TSK == TSK_ExplicitInstantiationDeclaration) 2744 return; 2745 2746 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 2747 2748 // If we already have a definition, we're done. 2749 if (VarDecl *Def = Var->getDefinition()) { 2750 // We may be explicitly instantiating something we've already implicitly 2751 // instantiated. 2752 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 2753 PointOfInstantiation); 2754 return; 2755 } 2756 2757 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 2758 if (Inst) 2759 return; 2760 2761 // If we're performing recursive template instantiation, create our own 2762 // queue of pending implicit instantiations that we will instantiate later, 2763 // while we're still within our own instantiation context. 2764 SmallVector<VTableUse, 16> SavedVTableUses; 2765 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 2766 if (Recursive) { 2767 VTableUses.swap(SavedVTableUses); 2768 PendingInstantiations.swap(SavedPendingInstantiations); 2769 } 2770 2771 // Enter the scope of this instantiation. We don't use 2772 // PushDeclContext because we don't have a scope. 2773 ContextRAII previousContext(*this, Var->getDeclContext()); 2774 LocalInstantiationScope Local(*this); 2775 2776 VarDecl *OldVar = Var; 2777 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 2778 getTemplateInstantiationArgs(Var))); 2779 2780 previousContext.pop(); 2781 2782 if (Var) { 2783 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 2784 assert(MSInfo && "Missing member specialization information?"); 2785 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 2786 MSInfo->getPointOfInstantiation()); 2787 DeclGroupRef DG(Var); 2788 Consumer.HandleTopLevelDecl(DG); 2789 } 2790 Local.Exit(); 2791 2792 if (Recursive) { 2793 // Define any newly required vtables. 2794 DefineUsedVTables(); 2795 2796 // Instantiate any pending implicit instantiations found during the 2797 // instantiation of this template. 2798 PerformPendingInstantiations(); 2799 2800 // Restore the set of pending vtables. 2801 assert(VTableUses.empty() && 2802 "VTableUses should be empty before it is discarded, " 2803 "while instantiating static data member."); 2804 VTableUses.swap(SavedVTableUses); 2805 2806 // Restore the set of pending implicit instantiations. 2807 assert(PendingInstantiations.empty() && 2808 "PendingInstantiations should be empty before it is discarded, " 2809 "while instantiating static data member."); 2810 PendingInstantiations.swap(SavedPendingInstantiations); 2811 } 2812} 2813 2814void 2815Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 2816 const CXXConstructorDecl *Tmpl, 2817 const MultiLevelTemplateArgumentList &TemplateArgs) { 2818 2819 SmallVector<CXXCtorInitializer*, 4> NewInits; 2820 bool AnyErrors = false; 2821 2822 // Instantiate all the initializers. 2823 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 2824 InitsEnd = Tmpl->init_end(); 2825 Inits != InitsEnd; ++Inits) { 2826 CXXCtorInitializer *Init = *Inits; 2827 2828 // Only instantiate written initializers, let Sema re-construct implicit 2829 // ones. 2830 if (!Init->isWritten()) 2831 continue; 2832 2833 SourceLocation EllipsisLoc; 2834 2835 if (Init->isPackExpansion()) { 2836 // This is a pack expansion. We should expand it now. 2837 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 2838 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2839 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 2840 bool ShouldExpand = false; 2841 bool RetainExpansion = false; 2842 llvm::Optional<unsigned> NumExpansions; 2843 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 2844 BaseTL.getSourceRange(), 2845 Unexpanded, 2846 TemplateArgs, ShouldExpand, 2847 RetainExpansion, 2848 NumExpansions)) { 2849 AnyErrors = true; 2850 New->setInvalidDecl(); 2851 continue; 2852 } 2853 assert(ShouldExpand && "Partial instantiation of base initializer?"); 2854 2855 // Loop over all of the arguments in the argument pack(s), 2856 for (unsigned I = 0; I != *NumExpansions; ++I) { 2857 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 2858 2859 // Instantiate the initializer. 2860 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 2861 /*CXXDirectInit=*/true); 2862 if (TempInit.isInvalid()) { 2863 AnyErrors = true; 2864 break; 2865 } 2866 2867 // Instantiate the base type. 2868 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 2869 TemplateArgs, 2870 Init->getSourceLocation(), 2871 New->getDeclName()); 2872 if (!BaseTInfo) { 2873 AnyErrors = true; 2874 break; 2875 } 2876 2877 // Build the initializer. 2878 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 2879 BaseTInfo, TempInit.take(), 2880 New->getParent(), 2881 SourceLocation()); 2882 if (NewInit.isInvalid()) { 2883 AnyErrors = true; 2884 break; 2885 } 2886 2887 NewInits.push_back(NewInit.get()); 2888 } 2889 2890 continue; 2891 } 2892 2893 // Instantiate the initializer. 2894 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 2895 /*CXXDirectInit=*/true); 2896 if (TempInit.isInvalid()) { 2897 AnyErrors = true; 2898 continue; 2899 } 2900 2901 MemInitResult NewInit; 2902 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 2903 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 2904 TemplateArgs, 2905 Init->getSourceLocation(), 2906 New->getDeclName()); 2907 if (!TInfo) { 2908 AnyErrors = true; 2909 New->setInvalidDecl(); 2910 continue; 2911 } 2912 2913 if (Init->isBaseInitializer()) 2914 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(), 2915 New->getParent(), EllipsisLoc); 2916 else 2917 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(), 2918 cast<CXXRecordDecl>(CurContext->getParent())); 2919 } else if (Init->isMemberInitializer()) { 2920 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 2921 Init->getMemberLocation(), 2922 Init->getMember(), 2923 TemplateArgs)); 2924 if (!Member) { 2925 AnyErrors = true; 2926 New->setInvalidDecl(); 2927 continue; 2928 } 2929 2930 NewInit = BuildMemberInitializer(Member, TempInit.take(), 2931 Init->getSourceLocation()); 2932 } else if (Init->isIndirectMemberInitializer()) { 2933 IndirectFieldDecl *IndirectMember = 2934 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 2935 Init->getMemberLocation(), 2936 Init->getIndirectMember(), TemplateArgs)); 2937 2938 if (!IndirectMember) { 2939 AnyErrors = true; 2940 New->setInvalidDecl(); 2941 continue; 2942 } 2943 2944 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(), 2945 Init->getSourceLocation()); 2946 } 2947 2948 if (NewInit.isInvalid()) { 2949 AnyErrors = true; 2950 New->setInvalidDecl(); 2951 } else { 2952 NewInits.push_back(NewInit.get()); 2953 } 2954 } 2955 2956 // Assign all the initializers to the new constructor. 2957 ActOnMemInitializers(New, 2958 /*FIXME: ColonLoc */ 2959 SourceLocation(), 2960 NewInits.data(), NewInits.size(), 2961 AnyErrors); 2962} 2963 2964ExprResult Sema::SubstInitializer(Expr *Init, 2965 const MultiLevelTemplateArgumentList &TemplateArgs, 2966 bool CXXDirectInit) { 2967 // Initializers are instantiated like expressions, except that various outer 2968 // layers are stripped. 2969 if (!Init) 2970 return Owned(Init); 2971 2972 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init)) 2973 Init = ExprTemp->getSubExpr(); 2974 2975 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init)) 2976 Init = Binder->getSubExpr(); 2977 2978 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init)) 2979 Init = ICE->getSubExprAsWritten(); 2980 2981 // If this is a direct-initializer, we take apart CXXConstructExprs. 2982 // Everything else is passed through. 2983 CXXConstructExpr *Construct; 2984 if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) || 2985 isa<CXXTemporaryObjectExpr>(Construct)) 2986 return SubstExpr(Init, TemplateArgs); 2987 2988 ASTOwningVector<Expr*> NewArgs(*this); 2989 if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true, 2990 TemplateArgs, NewArgs)) 2991 return ExprError(); 2992 2993 // Treat an empty initializer like none. 2994 if (NewArgs.empty()) 2995 return Owned((Expr*)0); 2996 2997 // Build a ParenListExpr to represent anything else. 2998 // FIXME: Fake locations! 2999 SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart()); 3000 return ActOnParenListExpr(Loc, Loc, move_arg(NewArgs)); 3001} 3002 3003// TODO: this could be templated if the various decl types used the 3004// same method name. 3005static bool isInstantiationOf(ClassTemplateDecl *Pattern, 3006 ClassTemplateDecl *Instance) { 3007 Pattern = Pattern->getCanonicalDecl(); 3008 3009 do { 3010 Instance = Instance->getCanonicalDecl(); 3011 if (Pattern == Instance) return true; 3012 Instance = Instance->getInstantiatedFromMemberTemplate(); 3013 } while (Instance); 3014 3015 return false; 3016} 3017 3018static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 3019 FunctionTemplateDecl *Instance) { 3020 Pattern = Pattern->getCanonicalDecl(); 3021 3022 do { 3023 Instance = Instance->getCanonicalDecl(); 3024 if (Pattern == Instance) return true; 3025 Instance = Instance->getInstantiatedFromMemberTemplate(); 3026 } while (Instance); 3027 3028 return false; 3029} 3030 3031static bool 3032isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 3033 ClassTemplatePartialSpecializationDecl *Instance) { 3034 Pattern 3035 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 3036 do { 3037 Instance = cast<ClassTemplatePartialSpecializationDecl>( 3038 Instance->getCanonicalDecl()); 3039 if (Pattern == Instance) 3040 return true; 3041 Instance = Instance->getInstantiatedFromMember(); 3042 } while (Instance); 3043 3044 return false; 3045} 3046 3047static bool isInstantiationOf(CXXRecordDecl *Pattern, 3048 CXXRecordDecl *Instance) { 3049 Pattern = Pattern->getCanonicalDecl(); 3050 3051 do { 3052 Instance = Instance->getCanonicalDecl(); 3053 if (Pattern == Instance) return true; 3054 Instance = Instance->getInstantiatedFromMemberClass(); 3055 } while (Instance); 3056 3057 return false; 3058} 3059 3060static bool isInstantiationOf(FunctionDecl *Pattern, 3061 FunctionDecl *Instance) { 3062 Pattern = Pattern->getCanonicalDecl(); 3063 3064 do { 3065 Instance = Instance->getCanonicalDecl(); 3066 if (Pattern == Instance) return true; 3067 Instance = Instance->getInstantiatedFromMemberFunction(); 3068 } while (Instance); 3069 3070 return false; 3071} 3072 3073static bool isInstantiationOf(EnumDecl *Pattern, 3074 EnumDecl *Instance) { 3075 Pattern = Pattern->getCanonicalDecl(); 3076 3077 do { 3078 Instance = Instance->getCanonicalDecl(); 3079 if (Pattern == Instance) return true; 3080 Instance = Instance->getInstantiatedFromMemberEnum(); 3081 } while (Instance); 3082 3083 return false; 3084} 3085 3086static bool isInstantiationOf(UsingShadowDecl *Pattern, 3087 UsingShadowDecl *Instance, 3088 ASTContext &C) { 3089 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 3090} 3091 3092static bool isInstantiationOf(UsingDecl *Pattern, 3093 UsingDecl *Instance, 3094 ASTContext &C) { 3095 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 3096} 3097 3098static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 3099 UsingDecl *Instance, 3100 ASTContext &C) { 3101 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 3102} 3103 3104static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 3105 UsingDecl *Instance, 3106 ASTContext &C) { 3107 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 3108} 3109 3110static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 3111 VarDecl *Instance) { 3112 assert(Instance->isStaticDataMember()); 3113 3114 Pattern = Pattern->getCanonicalDecl(); 3115 3116 do { 3117 Instance = Instance->getCanonicalDecl(); 3118 if (Pattern == Instance) return true; 3119 Instance = Instance->getInstantiatedFromStaticDataMember(); 3120 } while (Instance); 3121 3122 return false; 3123} 3124 3125// Other is the prospective instantiation 3126// D is the prospective pattern 3127static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 3128 if (D->getKind() != Other->getKind()) { 3129 if (UnresolvedUsingTypenameDecl *UUD 3130 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 3131 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 3132 return isInstantiationOf(UUD, UD, Ctx); 3133 } 3134 } 3135 3136 if (UnresolvedUsingValueDecl *UUD 3137 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 3138 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 3139 return isInstantiationOf(UUD, UD, Ctx); 3140 } 3141 } 3142 3143 return false; 3144 } 3145 3146 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 3147 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 3148 3149 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 3150 return isInstantiationOf(cast<FunctionDecl>(D), Function); 3151 3152 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 3153 return isInstantiationOf(cast<EnumDecl>(D), Enum); 3154 3155 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 3156 if (Var->isStaticDataMember()) 3157 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 3158 3159 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 3160 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 3161 3162 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 3163 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 3164 3165 if (ClassTemplatePartialSpecializationDecl *PartialSpec 3166 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 3167 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 3168 PartialSpec); 3169 3170 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 3171 if (!Field->getDeclName()) { 3172 // This is an unnamed field. 3173 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 3174 cast<FieldDecl>(D); 3175 } 3176 } 3177 3178 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 3179 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 3180 3181 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 3182 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 3183 3184 return D->getDeclName() && isa<NamedDecl>(Other) && 3185 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 3186} 3187 3188template<typename ForwardIterator> 3189static NamedDecl *findInstantiationOf(ASTContext &Ctx, 3190 NamedDecl *D, 3191 ForwardIterator first, 3192 ForwardIterator last) { 3193 for (; first != last; ++first) 3194 if (isInstantiationOf(Ctx, D, *first)) 3195 return cast<NamedDecl>(*first); 3196 3197 return 0; 3198} 3199 3200/// \brief Finds the instantiation of the given declaration context 3201/// within the current instantiation. 3202/// 3203/// \returns NULL if there was an error 3204DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 3205 const MultiLevelTemplateArgumentList &TemplateArgs) { 3206 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 3207 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 3208 return cast_or_null<DeclContext>(ID); 3209 } else return DC; 3210} 3211 3212/// \brief Find the instantiation of the given declaration within the 3213/// current instantiation. 3214/// 3215/// This routine is intended to be used when \p D is a declaration 3216/// referenced from within a template, that needs to mapped into the 3217/// corresponding declaration within an instantiation. For example, 3218/// given: 3219/// 3220/// \code 3221/// template<typename T> 3222/// struct X { 3223/// enum Kind { 3224/// KnownValue = sizeof(T) 3225/// }; 3226/// 3227/// bool getKind() const { return KnownValue; } 3228/// }; 3229/// 3230/// template struct X<int>; 3231/// \endcode 3232/// 3233/// In the instantiation of X<int>::getKind(), we need to map the 3234/// EnumConstantDecl for KnownValue (which refers to 3235/// X<T>::<Kind>::KnownValue) to its instantiation 3236/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 3237/// this mapping from within the instantiation of X<int>. 3238NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 3239 const MultiLevelTemplateArgumentList &TemplateArgs) { 3240 DeclContext *ParentDC = D->getDeclContext(); 3241 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 3242 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 3243 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) || 3244 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 3245 // D is a local of some kind. Look into the map of local 3246 // declarations to their instantiations. 3247 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 3248 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found 3249 = CurrentInstantiationScope->findInstantiationOf(D); 3250 3251 if (Found) { 3252 if (Decl *FD = Found->dyn_cast<Decl *>()) 3253 return cast<NamedDecl>(FD); 3254 3255 unsigned PackIdx = ArgumentPackSubstitutionIndex; 3256 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 3257 } 3258 3259 // If we didn't find the decl, then we must have a label decl that hasn't 3260 // been found yet. Lazily instantiate it and return it now. 3261 assert(isa<LabelDecl>(D)); 3262 3263 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 3264 assert(Inst && "Failed to instantiate label??"); 3265 3266 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 3267 return cast<LabelDecl>(Inst); 3268 } 3269 3270 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 3271 if (!Record->isDependentContext()) 3272 return D; 3273 3274 // Determine whether this record is the "templated" declaration describing 3275 // a class template or class template partial specialization. 3276 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 3277 if (ClassTemplate) 3278 ClassTemplate = ClassTemplate->getCanonicalDecl(); 3279 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 3280 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 3281 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 3282 3283 // Walk the current context to find either the record or an instantiation of 3284 // it. 3285 DeclContext *DC = CurContext; 3286 while (!DC->isFileContext()) { 3287 // If we're performing substitution while we're inside the template 3288 // definition, we'll find our own context. We're done. 3289 if (DC->Equals(Record)) 3290 return Record; 3291 3292 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 3293 // Check whether we're in the process of instantiating a class template 3294 // specialization of the template we're mapping. 3295 if (ClassTemplateSpecializationDecl *InstSpec 3296 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 3297 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 3298 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 3299 return InstRecord; 3300 } 3301 3302 // Check whether we're in the process of instantiating a member class. 3303 if (isInstantiationOf(Record, InstRecord)) 3304 return InstRecord; 3305 } 3306 3307 3308 // Move to the outer template scope. 3309 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 3310 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 3311 DC = FD->getLexicalDeclContext(); 3312 continue; 3313 } 3314 } 3315 3316 DC = DC->getParent(); 3317 } 3318 3319 // Fall through to deal with other dependent record types (e.g., 3320 // anonymous unions in class templates). 3321 } 3322 3323 if (!ParentDC->isDependentContext()) 3324 return D; 3325 3326 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 3327 if (!ParentDC) 3328 return 0; 3329 3330 if (ParentDC != D->getDeclContext()) { 3331 // We performed some kind of instantiation in the parent context, 3332 // so now we need to look into the instantiated parent context to 3333 // find the instantiation of the declaration D. 3334 3335 // If our context used to be dependent, we may need to instantiate 3336 // it before performing lookup into that context. 3337 bool IsBeingInstantiated = false; 3338 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 3339 if (!Spec->isDependentContext()) { 3340 QualType T = Context.getTypeDeclType(Spec); 3341 const RecordType *Tag = T->getAs<RecordType>(); 3342 assert(Tag && "type of non-dependent record is not a RecordType"); 3343 if (Tag->isBeingDefined()) 3344 IsBeingInstantiated = true; 3345 if (!Tag->isBeingDefined() && 3346 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 3347 return 0; 3348 3349 ParentDC = Tag->getDecl(); 3350 } 3351 } 3352 3353 NamedDecl *Result = 0; 3354 if (D->getDeclName()) { 3355 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 3356 Result = findInstantiationOf(Context, D, Found.first, Found.second); 3357 } else { 3358 // Since we don't have a name for the entity we're looking for, 3359 // our only option is to walk through all of the declarations to 3360 // find that name. This will occur in a few cases: 3361 // 3362 // - anonymous struct/union within a template 3363 // - unnamed class/struct/union/enum within a template 3364 // 3365 // FIXME: Find a better way to find these instantiations! 3366 Result = findInstantiationOf(Context, D, 3367 ParentDC->decls_begin(), 3368 ParentDC->decls_end()); 3369 } 3370 3371 if (!Result) { 3372 if (isa<UsingShadowDecl>(D)) { 3373 // UsingShadowDecls can instantiate to nothing because of using hiding. 3374 } else if (Diags.hasErrorOccurred()) { 3375 // We've already complained about something, so most likely this 3376 // declaration failed to instantiate. There's no point in complaining 3377 // further, since this is normal in invalid code. 3378 } else if (IsBeingInstantiated) { 3379 // The class in which this member exists is currently being 3380 // instantiated, and we haven't gotten around to instantiating this 3381 // member yet. This can happen when the code uses forward declarations 3382 // of member classes, and introduces ordering dependencies via 3383 // template instantiation. 3384 Diag(Loc, diag::err_member_not_yet_instantiated) 3385 << D->getDeclName() 3386 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 3387 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 3388 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 3389 // This enumeration constant was found when the template was defined, 3390 // but can't be found in the instantiation. This can happen if an 3391 // unscoped enumeration member is explicitly specialized. 3392 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 3393 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 3394 TemplateArgs)); 3395 assert(Spec->getTemplateSpecializationKind() == 3396 TSK_ExplicitSpecialization); 3397 Diag(Loc, diag::err_enumerator_does_not_exist) 3398 << D->getDeclName() 3399 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 3400 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 3401 << Context.getTypeDeclType(Spec); 3402 } else { 3403 // We should have found something, but didn't. 3404 llvm_unreachable("Unable to find instantiation of declaration!"); 3405 } 3406 } 3407 3408 D = Result; 3409 } 3410 3411 return D; 3412} 3413 3414/// \brief Performs template instantiation for all implicit template 3415/// instantiations we have seen until this point. 3416void Sema::PerformPendingInstantiations(bool LocalOnly) { 3417 // Load pending instantiations from the external source. 3418 if (!LocalOnly && ExternalSource) { 3419 SmallVector<std::pair<ValueDecl *, SourceLocation>, 4> Pending; 3420 ExternalSource->ReadPendingInstantiations(Pending); 3421 PendingInstantiations.insert(PendingInstantiations.begin(), 3422 Pending.begin(), Pending.end()); 3423 } 3424 3425 while (!PendingLocalImplicitInstantiations.empty() || 3426 (!LocalOnly && !PendingInstantiations.empty())) { 3427 PendingImplicitInstantiation Inst; 3428 3429 if (PendingLocalImplicitInstantiations.empty()) { 3430 Inst = PendingInstantiations.front(); 3431 PendingInstantiations.pop_front(); 3432 } else { 3433 Inst = PendingLocalImplicitInstantiations.front(); 3434 PendingLocalImplicitInstantiations.pop_front(); 3435 } 3436 3437 // Instantiate function definitions 3438 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 3439 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(), 3440 "instantiating function definition"); 3441 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 3442 TSK_ExplicitInstantiationDefinition; 3443 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true, 3444 DefinitionRequired); 3445 continue; 3446 } 3447 3448 // Instantiate static data member definitions. 3449 VarDecl *Var = cast<VarDecl>(Inst.first); 3450 assert(Var->isStaticDataMember() && "Not a static data member?"); 3451 3452 // Don't try to instantiate declarations if the most recent redeclaration 3453 // is invalid. 3454 if (Var->getMostRecentDecl()->isInvalidDecl()) 3455 continue; 3456 3457 // Check if the most recent declaration has changed the specialization kind 3458 // and removed the need for implicit instantiation. 3459 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) { 3460 case TSK_Undeclared: 3461 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 3462 case TSK_ExplicitInstantiationDeclaration: 3463 case TSK_ExplicitSpecialization: 3464 continue; // No longer need to instantiate this type. 3465 case TSK_ExplicitInstantiationDefinition: 3466 // We only need an instantiation if the pending instantiation *is* the 3467 // explicit instantiation. 3468 if (Var != Var->getMostRecentDecl()) continue; 3469 case TSK_ImplicitInstantiation: 3470 break; 3471 } 3472 3473 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(), 3474 "instantiating static data member " 3475 "definition"); 3476 3477 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 3478 TSK_ExplicitInstantiationDefinition; 3479 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true, 3480 DefinitionRequired); 3481 } 3482} 3483 3484void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 3485 const MultiLevelTemplateArgumentList &TemplateArgs) { 3486 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(), 3487 E = Pattern->ddiag_end(); I != E; ++I) { 3488 DependentDiagnostic *DD = *I; 3489 3490 switch (DD->getKind()) { 3491 case DependentDiagnostic::Access: 3492 HandleDependentAccessCheck(*DD, TemplateArgs); 3493 break; 3494 } 3495 } 3496} 3497