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