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