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