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/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/DeclTemplate.h" 16 #include "clang/AST/DeclVisitor.h" 17 #include "clang/AST/DependentDiagnostic.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/TypeLoc.h" 21 #include "clang/Lex/Preprocessor.h" 22 #include "clang/Sema/Lookup.h" 23 #include "clang/Sema/PrettyDeclStackTrace.h" 24 #include "clang/Sema/Template.h" 25 26 using namespace clang; 27 28 static bool isDeclWithinFunction(const Decl *D) { 29 const DeclContext *DC = D->getDeclContext(); 30 if (DC->isFunctionOrMethod()) 31 return true; 32 33 if (DC->isRecord()) 34 return cast<CXXRecordDecl>(DC)->isLocalClass(); 35 36 return false; 37 } 38 39 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 40 DeclaratorDecl *NewDecl) { 41 if (!OldDecl->getQualifierLoc()) 42 return false; 43 44 NestedNameSpecifierLoc NewQualifierLoc 45 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 46 TemplateArgs); 47 48 if (!NewQualifierLoc) 49 return true; 50 51 NewDecl->setQualifierInfo(NewQualifierLoc); 52 return false; 53 } 54 55 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 56 TagDecl *NewDecl) { 57 if (!OldDecl->getQualifierLoc()) 58 return false; 59 60 NestedNameSpecifierLoc NewQualifierLoc 61 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 62 TemplateArgs); 63 64 if (!NewQualifierLoc) 65 return true; 66 67 NewDecl->setQualifierInfo(NewQualifierLoc); 68 return false; 69 } 70 71 // Include attribute instantiation code. 72 #include "clang/Sema/AttrTemplateInstantiate.inc" 73 74 static void instantiateDependentAlignedAttr( 75 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 76 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) { 77 if (Aligned->isAlignmentExpr()) { 78 // The alignment expression is a constant expression. 79 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated); 80 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs); 81 if (!Result.isInvalid()) 82 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(), 83 Aligned->getSpellingListIndex(), IsPackExpansion); 84 } else { 85 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(), 86 TemplateArgs, Aligned->getLocation(), 87 DeclarationName()); 88 if (Result) 89 S.AddAlignedAttr(Aligned->getLocation(), New, Result, 90 Aligned->getSpellingListIndex(), IsPackExpansion); 91 } 92 } 93 94 static void instantiateDependentAlignedAttr( 95 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 96 const AlignedAttr *Aligned, Decl *New) { 97 if (!Aligned->isPackExpansion()) { 98 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 99 return; 100 } 101 102 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 103 if (Aligned->isAlignmentExpr()) 104 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(), 105 Unexpanded); 106 else 107 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(), 108 Unexpanded); 109 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); 110 111 // Determine whether we can expand this attribute pack yet. 112 bool Expand = true, RetainExpansion = false; 113 Optional<unsigned> NumExpansions; 114 // FIXME: Use the actual location of the ellipsis. 115 SourceLocation EllipsisLoc = Aligned->getLocation(); 116 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(), 117 Unexpanded, TemplateArgs, Expand, 118 RetainExpansion, NumExpansions)) 119 return; 120 121 if (!Expand) { 122 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1); 123 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true); 124 } else { 125 for (unsigned I = 0; I != *NumExpansions; ++I) { 126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I); 127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 128 } 129 } 130 } 131 132 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 133 const Decl *Tmpl, Decl *New, 134 LateInstantiatedAttrVec *LateAttrs, 135 LocalInstantiationScope *OuterMostScope) { 136 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end(); 137 i != e; ++i) { 138 const Attr *TmplAttr = *i; 139 140 // FIXME: This should be generalized to more than just the AlignedAttr. 141 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr); 142 if (Aligned && Aligned->isAlignmentDependent()) { 143 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New); 144 continue; 145 } 146 147 assert(!TmplAttr->isPackExpansion()); 148 if (TmplAttr->isLateParsed() && LateAttrs) { 149 // Late parsed attributes must be instantiated and attached after the 150 // enclosing class has been instantiated. See Sema::InstantiateClass. 151 LocalInstantiationScope *Saved = 0; 152 if (CurrentInstantiationScope) 153 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); 154 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); 155 } else { 156 // Allow 'this' within late-parsed attributes. 157 NamedDecl *ND = dyn_cast<NamedDecl>(New); 158 CXXRecordDecl *ThisContext = 159 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); 160 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0, 161 ND && ND->isCXXInstanceMember()); 162 163 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, 164 *this, TemplateArgs); 165 if (NewAttr) 166 New->addAttr(NewAttr); 167 } 168 } 169 } 170 171 Decl * 172 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 173 llvm_unreachable("Translation units cannot be instantiated"); 174 } 175 176 Decl * 177 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 178 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 179 D->getIdentifier()); 180 Owner->addDecl(Inst); 181 return Inst; 182 } 183 184 Decl * 185 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 186 llvm_unreachable("Namespaces cannot be instantiated"); 187 } 188 189 Decl * 190 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 191 NamespaceAliasDecl *Inst 192 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 193 D->getNamespaceLoc(), 194 D->getAliasLoc(), 195 D->getIdentifier(), 196 D->getQualifierLoc(), 197 D->getTargetNameLoc(), 198 D->getNamespace()); 199 Owner->addDecl(Inst); 200 return Inst; 201 } 202 203 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 204 bool IsTypeAlias) { 205 bool Invalid = false; 206 TypeSourceInfo *DI = D->getTypeSourceInfo(); 207 if (DI->getType()->isInstantiationDependentType() || 208 DI->getType()->isVariablyModifiedType()) { 209 DI = SemaRef.SubstType(DI, TemplateArgs, 210 D->getLocation(), D->getDeclName()); 211 if (!DI) { 212 Invalid = true; 213 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 214 } 215 } else { 216 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 217 } 218 219 // HACK: g++ has a bug where it gets the value kind of ?: wrong. 220 // libstdc++ relies upon this bug in its implementation of common_type. 221 // If we happen to be processing that implementation, fake up the g++ ?: 222 // semantics. See LWG issue 2141 for more information on the bug. 223 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>(); 224 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 225 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) && 226 DT->isReferenceType() && 227 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() && 228 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") && 229 D->getIdentifier() && D->getIdentifier()->isStr("type") && 230 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart())) 231 // Fold it to the (non-reference) type which g++ would have produced. 232 DI = SemaRef.Context.getTrivialTypeSourceInfo( 233 DI->getType().getNonReferenceType()); 234 235 // Create the new typedef 236 TypedefNameDecl *Typedef; 237 if (IsTypeAlias) 238 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 239 D->getLocation(), D->getIdentifier(), DI); 240 else 241 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 242 D->getLocation(), D->getIdentifier(), DI); 243 if (Invalid) 244 Typedef->setInvalidDecl(); 245 246 // If the old typedef was the name for linkage purposes of an anonymous 247 // tag decl, re-establish that relationship for the new typedef. 248 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 249 TagDecl *oldTag = oldTagType->getDecl(); 250 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) { 251 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 252 assert(!newTag->hasNameForLinkage()); 253 newTag->setTypedefNameForAnonDecl(Typedef); 254 } 255 } 256 257 if (TypedefNameDecl *Prev = D->getPreviousDecl()) { 258 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 259 TemplateArgs); 260 if (!InstPrev) 261 return 0; 262 263 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev); 264 265 // If the typedef types are not identical, reject them. 266 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); 267 268 Typedef->setPreviousDecl(InstPrevTypedef); 269 } 270 271 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); 272 273 Typedef->setAccess(D->getAccess()); 274 275 return Typedef; 276 } 277 278 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 279 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); 280 Owner->addDecl(Typedef); 281 return Typedef; 282 } 283 284 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { 285 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); 286 Owner->addDecl(Typedef); 287 return Typedef; 288 } 289 290 Decl * 291 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 292 // Create a local instantiation scope for this type alias template, which 293 // will contain the instantiations of the template parameters. 294 LocalInstantiationScope Scope(SemaRef); 295 296 TemplateParameterList *TempParams = D->getTemplateParameters(); 297 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 298 if (!InstParams) 299 return 0; 300 301 TypeAliasDecl *Pattern = D->getTemplatedDecl(); 302 303 TypeAliasTemplateDecl *PrevAliasTemplate = 0; 304 if (Pattern->getPreviousDecl()) { 305 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 306 if (!Found.empty()) { 307 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front()); 308 } 309 } 310 311 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( 312 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); 313 if (!AliasInst) 314 return 0; 315 316 TypeAliasTemplateDecl *Inst 317 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 318 D->getDeclName(), InstParams, AliasInst); 319 if (PrevAliasTemplate) 320 Inst->setPreviousDecl(PrevAliasTemplate); 321 322 Inst->setAccess(D->getAccess()); 323 324 if (!PrevAliasTemplate) 325 Inst->setInstantiatedFromMemberTemplate(D); 326 327 Owner->addDecl(Inst); 328 329 return Inst; 330 } 331 332 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 333 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false); 334 } 335 336 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, 337 bool InstantiatingVarTemplate) { 338 339 // If this is the variable for an anonymous struct or union, 340 // instantiate the anonymous struct/union type first. 341 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 342 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 343 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 344 return 0; 345 346 // Do substitution on the type of the declaration 347 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 348 TemplateArgs, 349 D->getTypeSpecStartLoc(), 350 D->getDeclName()); 351 if (!DI) 352 return 0; 353 354 if (DI->getType()->isFunctionType()) { 355 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 356 << D->isStaticDataMember() << DI->getType(); 357 return 0; 358 } 359 360 DeclContext *DC = Owner; 361 if (D->isLocalExternDecl()) 362 SemaRef.adjustContextForLocalExternDecl(DC); 363 364 // Build the instantiated declaration. 365 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 366 D->getLocation(), D->getIdentifier(), 367 DI->getType(), DI, D->getStorageClass()); 368 369 // In ARC, infer 'retaining' for variables of retainable type. 370 if (SemaRef.getLangOpts().ObjCAutoRefCount && 371 SemaRef.inferObjCARCLifetime(Var)) 372 Var->setInvalidDecl(); 373 374 // Substitute the nested name specifier, if any. 375 if (SubstQualifier(D, Var)) 376 return 0; 377 378 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 379 StartingScope, InstantiatingVarTemplate); 380 return Var; 381 } 382 383 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { 384 AccessSpecDecl* AD 385 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner, 386 D->getAccessSpecifierLoc(), D->getColonLoc()); 387 Owner->addHiddenDecl(AD); 388 return AD; 389 } 390 391 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 392 bool Invalid = false; 393 TypeSourceInfo *DI = D->getTypeSourceInfo(); 394 if (DI->getType()->isInstantiationDependentType() || 395 DI->getType()->isVariablyModifiedType()) { 396 DI = SemaRef.SubstType(DI, TemplateArgs, 397 D->getLocation(), D->getDeclName()); 398 if (!DI) { 399 DI = D->getTypeSourceInfo(); 400 Invalid = true; 401 } else if (DI->getType()->isFunctionType()) { 402 // C++ [temp.arg.type]p3: 403 // If a declaration acquires a function type through a type 404 // dependent on a template-parameter and this causes a 405 // declaration that does not use the syntactic form of a 406 // function declarator to have function type, the program is 407 // ill-formed. 408 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 409 << DI->getType(); 410 Invalid = true; 411 } 412 } else { 413 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 414 } 415 416 Expr *BitWidth = D->getBitWidth(); 417 if (Invalid) 418 BitWidth = 0; 419 else if (BitWidth) { 420 // The bit-width expression is a constant expression. 421 EnterExpressionEvaluationContext Unevaluated(SemaRef, 422 Sema::ConstantEvaluated); 423 424 ExprResult InstantiatedBitWidth 425 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 426 if (InstantiatedBitWidth.isInvalid()) { 427 Invalid = true; 428 BitWidth = 0; 429 } else 430 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 431 } 432 433 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 434 DI->getType(), DI, 435 cast<RecordDecl>(Owner), 436 D->getLocation(), 437 D->isMutable(), 438 BitWidth, 439 D->getInClassInitStyle(), 440 D->getInnerLocStart(), 441 D->getAccess(), 442 0); 443 if (!Field) { 444 cast<Decl>(Owner)->setInvalidDecl(); 445 return 0; 446 } 447 448 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope); 449 450 if (Field->hasAttrs()) 451 SemaRef.CheckAlignasUnderalignment(Field); 452 453 if (Invalid) 454 Field->setInvalidDecl(); 455 456 if (!Field->getDeclName()) { 457 // Keep track of where this decl came from. 458 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 459 } 460 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 461 if (Parent->isAnonymousStructOrUnion() && 462 Parent->getRedeclContext()->isFunctionOrMethod()) 463 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 464 } 465 466 Field->setImplicit(D->isImplicit()); 467 Field->setAccess(D->getAccess()); 468 Owner->addDecl(Field); 469 470 return Field; 471 } 472 473 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) { 474 bool Invalid = false; 475 TypeSourceInfo *DI = D->getTypeSourceInfo(); 476 477 if (DI->getType()->isVariablyModifiedType()) { 478 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified) 479 << D->getName(); 480 Invalid = true; 481 } else if (DI->getType()->isInstantiationDependentType()) { 482 DI = SemaRef.SubstType(DI, TemplateArgs, 483 D->getLocation(), D->getDeclName()); 484 if (!DI) { 485 DI = D->getTypeSourceInfo(); 486 Invalid = true; 487 } else if (DI->getType()->isFunctionType()) { 488 // C++ [temp.arg.type]p3: 489 // If a declaration acquires a function type through a type 490 // dependent on a template-parameter and this causes a 491 // declaration that does not use the syntactic form of a 492 // function declarator to have function type, the program is 493 // ill-formed. 494 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 495 << DI->getType(); 496 Invalid = true; 497 } 498 } else { 499 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 500 } 501 502 MSPropertyDecl *Property = MSPropertyDecl::Create( 503 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(), 504 DI, D->getLocStart(), D->getGetterId(), D->getSetterId()); 505 506 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs, 507 StartingScope); 508 509 if (Invalid) 510 Property->setInvalidDecl(); 511 512 Property->setAccess(D->getAccess()); 513 Owner->addDecl(Property); 514 515 return Property; 516 } 517 518 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 519 NamedDecl **NamedChain = 520 new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; 521 522 int i = 0; 523 for (IndirectFieldDecl::chain_iterator PI = 524 D->chain_begin(), PE = D->chain_end(); 525 PI != PE; ++PI) { 526 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI, 527 TemplateArgs); 528 if (!Next) 529 return 0; 530 531 NamedChain[i++] = Next; 532 } 533 534 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType(); 535 IndirectFieldDecl* IndirectField 536 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(), 537 D->getIdentifier(), T, 538 NamedChain, D->getChainingSize()); 539 540 541 IndirectField->setImplicit(D->isImplicit()); 542 IndirectField->setAccess(D->getAccess()); 543 Owner->addDecl(IndirectField); 544 return IndirectField; 545 } 546 547 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 548 // Handle friend type expressions by simply substituting template 549 // parameters into the pattern type and checking the result. 550 if (TypeSourceInfo *Ty = D->getFriendType()) { 551 TypeSourceInfo *InstTy; 552 // If this is an unsupported friend, don't bother substituting template 553 // arguments into it. The actual type referred to won't be used by any 554 // parts of Clang, and may not be valid for instantiating. Just use the 555 // same info for the instantiated friend. 556 if (D->isUnsupportedFriend()) { 557 InstTy = Ty; 558 } else { 559 InstTy = SemaRef.SubstType(Ty, TemplateArgs, 560 D->getLocation(), DeclarationName()); 561 } 562 if (!InstTy) 563 return 0; 564 565 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(), 566 D->getFriendLoc(), InstTy); 567 if (!FD) 568 return 0; 569 570 FD->setAccess(AS_public); 571 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 572 Owner->addDecl(FD); 573 return FD; 574 } 575 576 NamedDecl *ND = D->getFriendDecl(); 577 assert(ND && "friend decl must be a decl or a type!"); 578 579 // All of the Visit implementations for the various potential friend 580 // declarations have to be carefully written to work for friend 581 // objects, with the most important detail being that the target 582 // decl should almost certainly not be placed in Owner. 583 Decl *NewND = Visit(ND); 584 if (!NewND) return 0; 585 586 FriendDecl *FD = 587 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 588 cast<NamedDecl>(NewND), D->getFriendLoc()); 589 FD->setAccess(AS_public); 590 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 591 Owner->addDecl(FD); 592 return FD; 593 } 594 595 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 596 Expr *AssertExpr = D->getAssertExpr(); 597 598 // The expression in a static assertion is a constant expression. 599 EnterExpressionEvaluationContext Unevaluated(SemaRef, 600 Sema::ConstantEvaluated); 601 602 ExprResult InstantiatedAssertExpr 603 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 604 if (InstantiatedAssertExpr.isInvalid()) 605 return 0; 606 607 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(), 608 InstantiatedAssertExpr.get(), 609 D->getMessage(), 610 D->getRParenLoc(), 611 D->isFailed()); 612 } 613 614 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 615 EnumDecl *PrevDecl = 0; 616 if (D->getPreviousDecl()) { 617 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 618 D->getPreviousDecl(), 619 TemplateArgs); 620 if (!Prev) return 0; 621 PrevDecl = cast<EnumDecl>(Prev); 622 } 623 624 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 625 D->getLocation(), D->getIdentifier(), 626 PrevDecl, D->isScoped(), 627 D->isScopedUsingClassTag(), D->isFixed()); 628 if (D->isFixed()) { 629 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { 630 // If we have type source information for the underlying type, it means it 631 // has been explicitly set by the user. Perform substitution on it before 632 // moving on. 633 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 634 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc, 635 DeclarationName()); 636 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI)) 637 Enum->setIntegerType(SemaRef.Context.IntTy); 638 else 639 Enum->setIntegerTypeSourceInfo(NewTI); 640 } else { 641 assert(!D->getIntegerType()->isDependentType() 642 && "Dependent type without type source info"); 643 Enum->setIntegerType(D->getIntegerType()); 644 } 645 } 646 647 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); 648 649 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation); 650 Enum->setAccess(D->getAccess()); 651 // Forward the mangling number from the template to the instantiated decl. 652 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D)); 653 if (SubstQualifier(D, Enum)) return 0; 654 Owner->addDecl(Enum); 655 656 EnumDecl *Def = D->getDefinition(); 657 if (Def && Def != D) { 658 // If this is an out-of-line definition of an enum member template, check 659 // that the underlying types match in the instantiation of both 660 // declarations. 661 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { 662 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 663 QualType DefnUnderlying = 664 SemaRef.SubstType(TI->getType(), TemplateArgs, 665 UnderlyingLoc, DeclarationName()); 666 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(), 667 DefnUnderlying, Enum); 668 } 669 } 670 671 // C++11 [temp.inst]p1: The implicit instantiation of a class template 672 // specialization causes the implicit instantiation of the declarations, but 673 // not the definitions of scoped member enumerations. 674 // 675 // DR1484 clarifies that enumeration definitions inside of a template 676 // declaration aren't considered entities that can be separately instantiated 677 // from the rest of the entity they are declared inside of. 678 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) { 679 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 680 InstantiateEnumDefinition(Enum, Def); 681 } 682 683 return Enum; 684 } 685 686 void TemplateDeclInstantiator::InstantiateEnumDefinition( 687 EnumDecl *Enum, EnumDecl *Pattern) { 688 Enum->startDefinition(); 689 690 // Update the location to refer to the definition. 691 Enum->setLocation(Pattern->getLocation()); 692 693 SmallVector<Decl*, 4> Enumerators; 694 695 EnumConstantDecl *LastEnumConst = 0; 696 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(), 697 ECEnd = Pattern->enumerator_end(); 698 EC != ECEnd; ++EC) { 699 // The specified value for the enumerator. 700 ExprResult Value = SemaRef.Owned((Expr *)0); 701 if (Expr *UninstValue = EC->getInitExpr()) { 702 // The enumerator's value expression is a constant expression. 703 EnterExpressionEvaluationContext Unevaluated(SemaRef, 704 Sema::ConstantEvaluated); 705 706 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 707 } 708 709 // Drop the initial value and continue. 710 bool isInvalid = false; 711 if (Value.isInvalid()) { 712 Value = SemaRef.Owned((Expr *)0); 713 isInvalid = true; 714 } 715 716 EnumConstantDecl *EnumConst 717 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 718 EC->getLocation(), EC->getIdentifier(), 719 Value.get()); 720 721 if (isInvalid) { 722 if (EnumConst) 723 EnumConst->setInvalidDecl(); 724 Enum->setInvalidDecl(); 725 } 726 727 if (EnumConst) { 728 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst); 729 730 EnumConst->setAccess(Enum->getAccess()); 731 Enum->addDecl(EnumConst); 732 Enumerators.push_back(EnumConst); 733 LastEnumConst = EnumConst; 734 735 if (Pattern->getDeclContext()->isFunctionOrMethod() && 736 !Enum->isScoped()) { 737 // If the enumeration is within a function or method, record the enum 738 // constant as a local. 739 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst); 740 } 741 } 742 } 743 744 // FIXME: Fixup LBraceLoc 745 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), 746 Enum->getRBraceLoc(), Enum, 747 Enumerators, 748 0, 0); 749 } 750 751 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 752 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls."); 753 } 754 755 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 756 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 757 758 // Create a local instantiation scope for this class template, which 759 // will contain the instantiations of the template parameters. 760 LocalInstantiationScope Scope(SemaRef); 761 TemplateParameterList *TempParams = D->getTemplateParameters(); 762 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 763 if (!InstParams) 764 return NULL; 765 766 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 767 768 // Instantiate the qualifier. We have to do this first in case 769 // we're a friend declaration, because if we are then we need to put 770 // the new declaration in the appropriate context. 771 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); 772 if (QualifierLoc) { 773 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 774 TemplateArgs); 775 if (!QualifierLoc) 776 return 0; 777 } 778 779 CXXRecordDecl *PrevDecl = 0; 780 ClassTemplateDecl *PrevClassTemplate = 0; 781 782 if (!isFriend && Pattern->getPreviousDecl()) { 783 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 784 if (!Found.empty()) { 785 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front()); 786 if (PrevClassTemplate) 787 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 788 } 789 } 790 791 // If this isn't a friend, then it's a member template, in which 792 // case we just want to build the instantiation in the 793 // specialization. If it is a friend, we want to build it in 794 // the appropriate context. 795 DeclContext *DC = Owner; 796 if (isFriend) { 797 if (QualifierLoc) { 798 CXXScopeSpec SS; 799 SS.Adopt(QualifierLoc); 800 DC = SemaRef.computeDeclContext(SS); 801 if (!DC) return 0; 802 } else { 803 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 804 Pattern->getDeclContext(), 805 TemplateArgs); 806 } 807 808 // Look for a previous declaration of the template in the owning 809 // context. 810 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 811 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 812 SemaRef.LookupQualifiedName(R, DC); 813 814 if (R.isSingleResult()) { 815 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 816 if (PrevClassTemplate) 817 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 818 } 819 820 if (!PrevClassTemplate && QualifierLoc) { 821 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 822 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 823 << QualifierLoc.getSourceRange(); 824 return 0; 825 } 826 827 bool AdoptedPreviousTemplateParams = false; 828 if (PrevClassTemplate) { 829 bool Complain = true; 830 831 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 832 // template for struct std::tr1::__detail::_Map_base, where the 833 // template parameters of the friend declaration don't match the 834 // template parameters of the original declaration. In this one 835 // case, we don't complain about the ill-formed friend 836 // declaration. 837 if (isFriend && Pattern->getIdentifier() && 838 Pattern->getIdentifier()->isStr("_Map_base") && 839 DC->isNamespace() && 840 cast<NamespaceDecl>(DC)->getIdentifier() && 841 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 842 DeclContext *DCParent = DC->getParent(); 843 if (DCParent->isNamespace() && 844 cast<NamespaceDecl>(DCParent)->getIdentifier() && 845 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 846 DeclContext *DCParent2 = DCParent->getParent(); 847 if (DCParent2->isNamespace() && 848 cast<NamespaceDecl>(DCParent2)->getIdentifier() && 849 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") && 850 DCParent2->getParent()->isTranslationUnit()) 851 Complain = false; 852 } 853 } 854 855 TemplateParameterList *PrevParams 856 = PrevClassTemplate->getTemplateParameters(); 857 858 // Make sure the parameter lists match. 859 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 860 Complain, 861 Sema::TPL_TemplateMatch)) { 862 if (Complain) 863 return 0; 864 865 AdoptedPreviousTemplateParams = true; 866 InstParams = PrevParams; 867 } 868 869 // Do some additional validation, then merge default arguments 870 // from the existing declarations. 871 if (!AdoptedPreviousTemplateParams && 872 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 873 Sema::TPC_ClassTemplate)) 874 return 0; 875 } 876 } 877 878 CXXRecordDecl *RecordInst 879 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 880 Pattern->getLocStart(), Pattern->getLocation(), 881 Pattern->getIdentifier(), PrevDecl, 882 /*DelayTypeCreation=*/true); 883 884 if (QualifierLoc) 885 RecordInst->setQualifierInfo(QualifierLoc); 886 887 ClassTemplateDecl *Inst 888 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 889 D->getIdentifier(), InstParams, RecordInst, 890 PrevClassTemplate); 891 RecordInst->setDescribedClassTemplate(Inst); 892 893 if (isFriend) { 894 if (PrevClassTemplate) 895 Inst->setAccess(PrevClassTemplate->getAccess()); 896 else 897 Inst->setAccess(D->getAccess()); 898 899 Inst->setObjectOfFriendDecl(); 900 // TODO: do we want to track the instantiation progeny of this 901 // friend target decl? 902 } else { 903 Inst->setAccess(D->getAccess()); 904 if (!PrevClassTemplate) 905 Inst->setInstantiatedFromMemberTemplate(D); 906 } 907 908 // Trigger creation of the type for the instantiation. 909 SemaRef.Context.getInjectedClassNameType(RecordInst, 910 Inst->getInjectedClassNameSpecialization()); 911 912 // Finish handling of friends. 913 if (isFriend) { 914 DC->makeDeclVisibleInContext(Inst); 915 Inst->setLexicalDeclContext(Owner); 916 RecordInst->setLexicalDeclContext(Owner); 917 return Inst; 918 } 919 920 if (D->isOutOfLine()) { 921 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 922 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); 923 } 924 925 Owner->addDecl(Inst); 926 927 if (!PrevClassTemplate) { 928 // Queue up any out-of-line partial specializations of this member 929 // class template; the client will force their instantiation once 930 // the enclosing class has been instantiated. 931 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 932 D->getPartialSpecializations(PartialSpecs); 933 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 934 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 935 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I])); 936 } 937 938 return Inst; 939 } 940 941 Decl * 942 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 943 ClassTemplatePartialSpecializationDecl *D) { 944 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 945 946 // Lookup the already-instantiated declaration in the instantiation 947 // of the class template and return that. 948 DeclContext::lookup_result Found 949 = Owner->lookup(ClassTemplate->getDeclName()); 950 if (Found.empty()) 951 return 0; 952 953 ClassTemplateDecl *InstClassTemplate 954 = dyn_cast<ClassTemplateDecl>(Found.front()); 955 if (!InstClassTemplate) 956 return 0; 957 958 if (ClassTemplatePartialSpecializationDecl *Result 959 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) 960 return Result; 961 962 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D); 963 } 964 965 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) { 966 assert(D->getTemplatedDecl()->isStaticDataMember() && 967 "Only static data member templates are allowed."); 968 969 // Create a local instantiation scope for this variable template, which 970 // will contain the instantiations of the template parameters. 971 LocalInstantiationScope Scope(SemaRef); 972 TemplateParameterList *TempParams = D->getTemplateParameters(); 973 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 974 if (!InstParams) 975 return NULL; 976 977 VarDecl *Pattern = D->getTemplatedDecl(); 978 VarTemplateDecl *PrevVarTemplate = 0; 979 980 if (Pattern->getPreviousDecl()) { 981 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 982 if (!Found.empty()) 983 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 984 } 985 986 VarDecl *VarInst = 987 cast_or_null<VarDecl>(VisitVarDecl(Pattern, 988 /*InstantiatingVarTemplate=*/true)); 989 990 DeclContext *DC = Owner; 991 992 VarTemplateDecl *Inst = VarTemplateDecl::Create( 993 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams, 994 VarInst, PrevVarTemplate); 995 VarInst->setDescribedVarTemplate(Inst); 996 997 Inst->setAccess(D->getAccess()); 998 if (!PrevVarTemplate) 999 Inst->setInstantiatedFromMemberTemplate(D); 1000 1001 if (D->isOutOfLine()) { 1002 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 1003 VarInst->setLexicalDeclContext(D->getLexicalDeclContext()); 1004 } 1005 1006 Owner->addDecl(Inst); 1007 1008 if (!PrevVarTemplate) { 1009 // Queue up any out-of-line partial specializations of this member 1010 // variable template; the client will force their instantiation once 1011 // the enclosing class has been instantiated. 1012 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 1013 D->getPartialSpecializations(PartialSpecs); 1014 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 1015 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 1016 OutOfLineVarPartialSpecs.push_back( 1017 std::make_pair(Inst, PartialSpecs[I])); 1018 } 1019 1020 return Inst; 1021 } 1022 1023 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl( 1024 VarTemplatePartialSpecializationDecl *D) { 1025 assert(D->isStaticDataMember() && 1026 "Only static data member templates are allowed."); 1027 1028 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 1029 1030 // Lookup the already-instantiated declaration and return that. 1031 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName()); 1032 assert(!Found.empty() && "Instantiation found nothing?"); 1033 1034 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 1035 assert(InstVarTemplate && "Instantiation did not find a variable template?"); 1036 1037 if (VarTemplatePartialSpecializationDecl *Result = 1038 InstVarTemplate->findPartialSpecInstantiatedFromMember(D)) 1039 return Result; 1040 1041 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D); 1042 } 1043 1044 Decl * 1045 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 1046 // Create a local instantiation scope for this function template, which 1047 // will contain the instantiations of the template parameters and then get 1048 // merged with the local instantiation scope for the function template 1049 // itself. 1050 LocalInstantiationScope Scope(SemaRef); 1051 1052 TemplateParameterList *TempParams = D->getTemplateParameters(); 1053 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1054 if (!InstParams) 1055 return NULL; 1056 1057 FunctionDecl *Instantiated = 0; 1058 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 1059 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 1060 InstParams)); 1061 else 1062 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 1063 D->getTemplatedDecl(), 1064 InstParams)); 1065 1066 if (!Instantiated) 1067 return 0; 1068 1069 // Link the instantiated function template declaration to the function 1070 // template from which it was instantiated. 1071 FunctionTemplateDecl *InstTemplate 1072 = Instantiated->getDescribedFunctionTemplate(); 1073 InstTemplate->setAccess(D->getAccess()); 1074 assert(InstTemplate && 1075 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 1076 1077 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 1078 1079 // Link the instantiation back to the pattern *unless* this is a 1080 // non-definition friend declaration. 1081 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 1082 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 1083 InstTemplate->setInstantiatedFromMemberTemplate(D); 1084 1085 // Make declarations visible in the appropriate context. 1086 if (!isFriend) { 1087 Owner->addDecl(InstTemplate); 1088 } else if (InstTemplate->getDeclContext()->isRecord() && 1089 !D->getPreviousDecl()) { 1090 SemaRef.CheckFriendAccess(InstTemplate); 1091 } 1092 1093 return InstTemplate; 1094 } 1095 1096 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 1097 CXXRecordDecl *PrevDecl = 0; 1098 if (D->isInjectedClassName()) 1099 PrevDecl = cast<CXXRecordDecl>(Owner); 1100 else if (D->getPreviousDecl()) { 1101 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 1102 D->getPreviousDecl(), 1103 TemplateArgs); 1104 if (!Prev) return 0; 1105 PrevDecl = cast<CXXRecordDecl>(Prev); 1106 } 1107 1108 CXXRecordDecl *Record 1109 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 1110 D->getLocStart(), D->getLocation(), 1111 D->getIdentifier(), PrevDecl); 1112 1113 // Substitute the nested name specifier, if any. 1114 if (SubstQualifier(D, Record)) 1115 return 0; 1116 1117 Record->setImplicit(D->isImplicit()); 1118 // FIXME: Check against AS_none is an ugly hack to work around the issue that 1119 // the tag decls introduced by friend class declarations don't have an access 1120 // specifier. Remove once this area of the code gets sorted out. 1121 if (D->getAccess() != AS_none) 1122 Record->setAccess(D->getAccess()); 1123 if (!D->isInjectedClassName()) 1124 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 1125 1126 // If the original function was part of a friend declaration, 1127 // inherit its namespace state. 1128 if (D->getFriendObjectKind()) 1129 Record->setObjectOfFriendDecl(); 1130 1131 // Make sure that anonymous structs and unions are recorded. 1132 if (D->isAnonymousStructOrUnion()) 1133 Record->setAnonymousStructOrUnion(true); 1134 1135 if (D->isLocalClass()) 1136 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 1137 1138 // Forward the mangling number from the template to the instantiated decl. 1139 SemaRef.Context.setManglingNumber(Record, 1140 SemaRef.Context.getManglingNumber(D)); 1141 1142 Owner->addDecl(Record); 1143 1144 // DR1484 clarifies that the members of a local class are instantiated as part 1145 // of the instantiation of their enclosing entity. 1146 if (D->isCompleteDefinition() && D->isLocalClass()) { 1147 if (SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs, 1148 TSK_ImplicitInstantiation, 1149 /*Complain=*/true)) { 1150 llvm_unreachable("InstantiateClass shouldn't fail here!"); 1151 } else { 1152 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs, 1153 TSK_ImplicitInstantiation); 1154 } 1155 } 1156 return Record; 1157 } 1158 1159 /// \brief Adjust the given function type for an instantiation of the 1160 /// given declaration, to cope with modifications to the function's type that 1161 /// aren't reflected in the type-source information. 1162 /// 1163 /// \param D The declaration we're instantiating. 1164 /// \param TInfo The already-instantiated type. 1165 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, 1166 FunctionDecl *D, 1167 TypeSourceInfo *TInfo) { 1168 const FunctionProtoType *OrigFunc 1169 = D->getType()->castAs<FunctionProtoType>(); 1170 const FunctionProtoType *NewFunc 1171 = TInfo->getType()->castAs<FunctionProtoType>(); 1172 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo()) 1173 return TInfo->getType(); 1174 1175 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo(); 1176 NewEPI.ExtInfo = OrigFunc->getExtInfo(); 1177 return Context.getFunctionType(NewFunc->getResultType(), 1178 NewFunc->getArgTypes(), NewEPI); 1179 } 1180 1181 /// Normal class members are of more specific types and therefore 1182 /// don't make it here. This function serves two purposes: 1183 /// 1) instantiating function templates 1184 /// 2) substituting friend declarations 1185 /// FIXME: preserve function definitions in case #2 1186 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 1187 TemplateParameterList *TemplateParams) { 1188 // Check whether there is already a function template specialization for 1189 // this declaration. 1190 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1191 if (FunctionTemplate && !TemplateParams) { 1192 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1193 1194 void *InsertPos = 0; 1195 FunctionDecl *SpecFunc 1196 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(), 1197 InsertPos); 1198 1199 // If we already have a function template specialization, return it. 1200 if (SpecFunc) 1201 return SpecFunc; 1202 } 1203 1204 bool isFriend; 1205 if (FunctionTemplate) 1206 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1207 else 1208 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1209 1210 bool MergeWithParentScope = (TemplateParams != 0) || 1211 Owner->isFunctionOrMethod() || 1212 !(isa<Decl>(Owner) && 1213 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1214 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1215 1216 SmallVector<ParmVarDecl *, 4> Params; 1217 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1218 if (!TInfo) 1219 return 0; 1220 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 1221 1222 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1223 if (QualifierLoc) { 1224 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1225 TemplateArgs); 1226 if (!QualifierLoc) 1227 return 0; 1228 } 1229 1230 // If we're instantiating a local function declaration, put the result 1231 // in the enclosing namespace; otherwise we need to find the instantiated 1232 // context. 1233 DeclContext *DC; 1234 if (D->isLocalExternDecl()) { 1235 DC = Owner; 1236 SemaRef.adjustContextForLocalExternDecl(DC); 1237 } else if (isFriend && QualifierLoc) { 1238 CXXScopeSpec SS; 1239 SS.Adopt(QualifierLoc); 1240 DC = SemaRef.computeDeclContext(SS); 1241 if (!DC) return 0; 1242 } else { 1243 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 1244 TemplateArgs); 1245 } 1246 1247 FunctionDecl *Function = 1248 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 1249 D->getNameInfo(), T, TInfo, 1250 D->getCanonicalDecl()->getStorageClass(), 1251 D->isInlineSpecified(), D->hasWrittenPrototype(), 1252 D->isConstexpr()); 1253 Function->setRangeEnd(D->getSourceRange().getEnd()); 1254 1255 if (D->isInlined()) 1256 Function->setImplicitlyInline(); 1257 1258 if (QualifierLoc) 1259 Function->setQualifierInfo(QualifierLoc); 1260 1261 if (D->isLocalExternDecl()) 1262 Function->setLocalExternDecl(); 1263 1264 DeclContext *LexicalDC = Owner; 1265 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) { 1266 assert(D->getDeclContext()->isFileContext()); 1267 LexicalDC = D->getDeclContext(); 1268 } 1269 1270 Function->setLexicalDeclContext(LexicalDC); 1271 1272 // Attach the parameters 1273 for (unsigned P = 0; P < Params.size(); ++P) 1274 if (Params[P]) 1275 Params[P]->setOwningFunction(Function); 1276 Function->setParams(Params); 1277 1278 SourceLocation InstantiateAtPOI; 1279 if (TemplateParams) { 1280 // Our resulting instantiation is actually a function template, since we 1281 // are substituting only the outer template parameters. For example, given 1282 // 1283 // template<typename T> 1284 // struct X { 1285 // template<typename U> friend void f(T, U); 1286 // }; 1287 // 1288 // X<int> x; 1289 // 1290 // We are instantiating the friend function template "f" within X<int>, 1291 // which means substituting int for T, but leaving "f" as a friend function 1292 // template. 1293 // Build the function template itself. 1294 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1295 Function->getLocation(), 1296 Function->getDeclName(), 1297 TemplateParams, Function); 1298 Function->setDescribedFunctionTemplate(FunctionTemplate); 1299 1300 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1301 1302 if (isFriend && D->isThisDeclarationADefinition()) { 1303 // TODO: should we remember this connection regardless of whether 1304 // the friend declaration provided a body? 1305 FunctionTemplate->setInstantiatedFromMemberTemplate( 1306 D->getDescribedFunctionTemplate()); 1307 } 1308 } else if (FunctionTemplate) { 1309 // Record this function template specialization. 1310 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1311 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1312 TemplateArgumentList::CreateCopy(SemaRef.Context, 1313 Innermost.begin(), 1314 Innermost.size()), 1315 /*InsertPos=*/0); 1316 } else if (isFriend) { 1317 // Note, we need this connection even if the friend doesn't have a body. 1318 // Its body may exist but not have been attached yet due to deferred 1319 // parsing. 1320 // FIXME: It might be cleaner to set this when attaching the body to the 1321 // friend function declaration, however that would require finding all the 1322 // instantiations and modifying them. 1323 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1324 } 1325 1326 if (InitFunctionInstantiation(Function, D)) 1327 Function->setInvalidDecl(); 1328 1329 bool isExplicitSpecialization = false; 1330 1331 LookupResult Previous( 1332 SemaRef, Function->getDeclName(), SourceLocation(), 1333 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 1334 : Sema::LookupOrdinaryName, 1335 Sema::ForRedeclaration); 1336 1337 if (DependentFunctionTemplateSpecializationInfo *Info 1338 = D->getDependentSpecializationInfo()) { 1339 assert(isFriend && "non-friend has dependent specialization info?"); 1340 1341 // This needs to be set now for future sanity. 1342 Function->setObjectOfFriendDecl(); 1343 1344 // Instantiate the explicit template arguments. 1345 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1346 Info->getRAngleLoc()); 1347 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1348 ExplicitArgs, TemplateArgs)) 1349 return 0; 1350 1351 // Map the candidate templates to their instantiations. 1352 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1353 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1354 Info->getTemplate(I), 1355 TemplateArgs); 1356 if (!Temp) return 0; 1357 1358 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1359 } 1360 1361 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1362 &ExplicitArgs, 1363 Previous)) 1364 Function->setInvalidDecl(); 1365 1366 isExplicitSpecialization = true; 1367 1368 } else if (TemplateParams || !FunctionTemplate) { 1369 // Look only into the namespace where the friend would be declared to 1370 // find a previous declaration. This is the innermost enclosing namespace, 1371 // as described in ActOnFriendFunctionDecl. 1372 SemaRef.LookupQualifiedName(Previous, DC); 1373 1374 // In C++, the previous declaration we find might be a tag type 1375 // (class or enum). In this case, the new declaration will hide the 1376 // tag type. Note that this does does not apply if we're declaring a 1377 // typedef (C++ [dcl.typedef]p4). 1378 if (Previous.isSingleTagDecl()) 1379 Previous.clear(); 1380 } 1381 1382 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 1383 isExplicitSpecialization); 1384 1385 NamedDecl *PrincipalDecl = (TemplateParams 1386 ? cast<NamedDecl>(FunctionTemplate) 1387 : Function); 1388 1389 // If the original function was part of a friend declaration, 1390 // inherit its namespace state and add it to the owner. 1391 if (isFriend) { 1392 PrincipalDecl->setObjectOfFriendDecl(); 1393 DC->makeDeclVisibleInContext(PrincipalDecl); 1394 1395 bool queuedInstantiation = false; 1396 1397 // C++98 [temp.friend]p5: When a function is defined in a friend function 1398 // declaration in a class template, the function is defined at each 1399 // instantiation of the class template. The function is defined even if it 1400 // is never used. 1401 // C++11 [temp.friend]p4: When a function is defined in a friend function 1402 // declaration in a class template, the function is instantiated when the 1403 // function is odr-used. 1404 // 1405 // If -Wc++98-compat is enabled, we go through the motions of checking for a 1406 // redefinition, but don't instantiate the function. 1407 if ((!SemaRef.getLangOpts().CPlusPlus11 || 1408 SemaRef.Diags.getDiagnosticLevel( 1409 diag::warn_cxx98_compat_friend_redefinition, 1410 Function->getLocation()) 1411 != DiagnosticsEngine::Ignored) && 1412 D->isThisDeclarationADefinition()) { 1413 // Check for a function body. 1414 const FunctionDecl *Definition = 0; 1415 if (Function->isDefined(Definition) && 1416 Definition->getTemplateSpecializationKind() == TSK_Undeclared) { 1417 SemaRef.Diag(Function->getLocation(), 1418 SemaRef.getLangOpts().CPlusPlus11 ? 1419 diag::warn_cxx98_compat_friend_redefinition : 1420 diag::err_redefinition) << Function->getDeclName(); 1421 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition); 1422 if (!SemaRef.getLangOpts().CPlusPlus11) 1423 Function->setInvalidDecl(); 1424 } 1425 // Check for redefinitions due to other instantiations of this or 1426 // a similar friend function. 1427 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(), 1428 REnd = Function->redecls_end(); 1429 R != REnd; ++R) { 1430 if (*R == Function) 1431 continue; 1432 switch (R->getFriendObjectKind()) { 1433 case Decl::FOK_None: 1434 if (!SemaRef.getLangOpts().CPlusPlus11 && 1435 !queuedInstantiation && R->isUsed(false)) { 1436 if (MemberSpecializationInfo *MSInfo 1437 = Function->getMemberSpecializationInfo()) { 1438 if (MSInfo->getPointOfInstantiation().isInvalid()) { 1439 SourceLocation Loc = R->getLocation(); // FIXME 1440 MSInfo->setPointOfInstantiation(Loc); 1441 SemaRef.PendingLocalImplicitInstantiations.push_back( 1442 std::make_pair(Function, Loc)); 1443 queuedInstantiation = true; 1444 } 1445 } 1446 } 1447 break; 1448 default: 1449 if (const FunctionDecl *RPattern 1450 = R->getTemplateInstantiationPattern()) 1451 if (RPattern->isDefined(RPattern)) { 1452 SemaRef.Diag(Function->getLocation(), 1453 SemaRef.getLangOpts().CPlusPlus11 ? 1454 diag::warn_cxx98_compat_friend_redefinition : 1455 diag::err_redefinition) 1456 << Function->getDeclName(); 1457 SemaRef.Diag(R->getLocation(), diag::note_previous_definition); 1458 if (!SemaRef.getLangOpts().CPlusPlus11) 1459 Function->setInvalidDecl(); 1460 break; 1461 } 1462 } 1463 } 1464 } 1465 } 1466 1467 if (Function->isLocalExternDecl() && !Function->getPreviousDecl()) 1468 DC->makeDeclVisibleInContext(PrincipalDecl); 1469 1470 if (Function->isOverloadedOperator() && !DC->isRecord() && 1471 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1472 PrincipalDecl->setNonMemberOperator(); 1473 1474 assert(!D->isDefaulted() && "only methods should be defaulted"); 1475 return Function; 1476 } 1477 1478 Decl * 1479 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 1480 TemplateParameterList *TemplateParams, 1481 bool IsClassScopeSpecialization) { 1482 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1483 if (FunctionTemplate && !TemplateParams) { 1484 // We are creating a function template specialization from a function 1485 // template. Check whether there is already a function template 1486 // specialization for this particular set of template arguments. 1487 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1488 1489 void *InsertPos = 0; 1490 FunctionDecl *SpecFunc 1491 = FunctionTemplate->findSpecialization(Innermost.begin(), 1492 Innermost.size(), 1493 InsertPos); 1494 1495 // If we already have a function template specialization, return it. 1496 if (SpecFunc) 1497 return SpecFunc; 1498 } 1499 1500 bool isFriend; 1501 if (FunctionTemplate) 1502 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1503 else 1504 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1505 1506 bool MergeWithParentScope = (TemplateParams != 0) || 1507 !(isa<Decl>(Owner) && 1508 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1509 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1510 1511 // Instantiate enclosing template arguments for friends. 1512 SmallVector<TemplateParameterList *, 4> TempParamLists; 1513 unsigned NumTempParamLists = 0; 1514 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 1515 TempParamLists.set_size(NumTempParamLists); 1516 for (unsigned I = 0; I != NumTempParamLists; ++I) { 1517 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 1518 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1519 if (!InstParams) 1520 return NULL; 1521 TempParamLists[I] = InstParams; 1522 } 1523 } 1524 1525 SmallVector<ParmVarDecl *, 4> Params; 1526 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1527 if (!TInfo) 1528 return 0; 1529 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 1530 1531 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1532 if (QualifierLoc) { 1533 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1534 TemplateArgs); 1535 if (!QualifierLoc) 1536 return 0; 1537 } 1538 1539 DeclContext *DC = Owner; 1540 if (isFriend) { 1541 if (QualifierLoc) { 1542 CXXScopeSpec SS; 1543 SS.Adopt(QualifierLoc); 1544 DC = SemaRef.computeDeclContext(SS); 1545 1546 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 1547 return 0; 1548 } else { 1549 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 1550 D->getDeclContext(), 1551 TemplateArgs); 1552 } 1553 if (!DC) return 0; 1554 } 1555 1556 // Build the instantiated method declaration. 1557 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1558 CXXMethodDecl *Method = 0; 1559 1560 SourceLocation StartLoc = D->getInnerLocStart(); 1561 DeclarationNameInfo NameInfo 1562 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1563 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1564 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 1565 StartLoc, NameInfo, T, TInfo, 1566 Constructor->isExplicit(), 1567 Constructor->isInlineSpecified(), 1568 false, Constructor->isConstexpr()); 1569 1570 // Claim that the instantiation of a constructor or constructor template 1571 // inherits the same constructor that the template does. 1572 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>( 1573 Constructor->getInheritedConstructor())) { 1574 // If we're instantiating a specialization of a function template, our 1575 // "inherited constructor" will actually itself be a function template. 1576 // Instantiate a declaration of it, too. 1577 if (FunctionTemplate) { 1578 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() && 1579 !Inh->getParent()->isDependentContext() && 1580 "inheriting constructor template in dependent context?"); 1581 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(), 1582 Inh); 1583 if (Inst.isInvalid()) 1584 return 0; 1585 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext()); 1586 LocalInstantiationScope LocalScope(SemaRef); 1587 1588 // Use the same template arguments that we deduced for the inheriting 1589 // constructor. There's no way they could be deduced differently. 1590 MultiLevelTemplateArgumentList InheritedArgs; 1591 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost()); 1592 Inh = cast_or_null<CXXConstructorDecl>( 1593 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs)); 1594 if (!Inh) 1595 return 0; 1596 } 1597 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh); 1598 } 1599 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 1600 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 1601 StartLoc, NameInfo, T, TInfo, 1602 Destructor->isInlineSpecified(), 1603 false); 1604 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 1605 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 1606 StartLoc, NameInfo, T, TInfo, 1607 Conversion->isInlineSpecified(), 1608 Conversion->isExplicit(), 1609 Conversion->isConstexpr(), 1610 Conversion->getLocEnd()); 1611 } else { 1612 StorageClass SC = D->isStatic() ? SC_Static : SC_None; 1613 Method = CXXMethodDecl::Create(SemaRef.Context, Record, 1614 StartLoc, NameInfo, T, TInfo, 1615 SC, D->isInlineSpecified(), 1616 D->isConstexpr(), D->getLocEnd()); 1617 } 1618 1619 if (D->isInlined()) 1620 Method->setImplicitlyInline(); 1621 1622 if (QualifierLoc) 1623 Method->setQualifierInfo(QualifierLoc); 1624 1625 if (TemplateParams) { 1626 // Our resulting instantiation is actually a function template, since we 1627 // are substituting only the outer template parameters. For example, given 1628 // 1629 // template<typename T> 1630 // struct X { 1631 // template<typename U> void f(T, U); 1632 // }; 1633 // 1634 // X<int> x; 1635 // 1636 // We are instantiating the member template "f" within X<int>, which means 1637 // substituting int for T, but leaving "f" as a member function template. 1638 // Build the function template itself. 1639 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 1640 Method->getLocation(), 1641 Method->getDeclName(), 1642 TemplateParams, Method); 1643 if (isFriend) { 1644 FunctionTemplate->setLexicalDeclContext(Owner); 1645 FunctionTemplate->setObjectOfFriendDecl(); 1646 } else if (D->isOutOfLine()) 1647 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 1648 Method->setDescribedFunctionTemplate(FunctionTemplate); 1649 } else if (FunctionTemplate) { 1650 // Record this function template specialization. 1651 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1652 Method->setFunctionTemplateSpecialization(FunctionTemplate, 1653 TemplateArgumentList::CreateCopy(SemaRef.Context, 1654 Innermost.begin(), 1655 Innermost.size()), 1656 /*InsertPos=*/0); 1657 } else if (!isFriend) { 1658 // Record that this is an instantiation of a member function. 1659 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1660 } 1661 1662 // If we are instantiating a member function defined 1663 // out-of-line, the instantiation will have the same lexical 1664 // context (which will be a namespace scope) as the template. 1665 if (isFriend) { 1666 if (NumTempParamLists) 1667 Method->setTemplateParameterListsInfo(SemaRef.Context, 1668 NumTempParamLists, 1669 TempParamLists.data()); 1670 1671 Method->setLexicalDeclContext(Owner); 1672 Method->setObjectOfFriendDecl(); 1673 } else if (D->isOutOfLine()) 1674 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 1675 1676 // Attach the parameters 1677 for (unsigned P = 0; P < Params.size(); ++P) 1678 Params[P]->setOwningFunction(Method); 1679 Method->setParams(Params); 1680 1681 if (InitMethodInstantiation(Method, D)) 1682 Method->setInvalidDecl(); 1683 1684 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 1685 Sema::ForRedeclaration); 1686 1687 if (!FunctionTemplate || TemplateParams || isFriend) { 1688 SemaRef.LookupQualifiedName(Previous, Record); 1689 1690 // In C++, the previous declaration we find might be a tag type 1691 // (class or enum). In this case, the new declaration will hide the 1692 // tag type. Note that this does does not apply if we're declaring a 1693 // typedef (C++ [dcl.typedef]p4). 1694 if (Previous.isSingleTagDecl()) 1695 Previous.clear(); 1696 } 1697 1698 if (!IsClassScopeSpecialization) 1699 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false); 1700 1701 if (D->isPure()) 1702 SemaRef.CheckPureMethod(Method, SourceRange()); 1703 1704 // Propagate access. For a non-friend declaration, the access is 1705 // whatever we're propagating from. For a friend, it should be the 1706 // previous declaration we just found. 1707 if (isFriend && Method->getPreviousDecl()) 1708 Method->setAccess(Method->getPreviousDecl()->getAccess()); 1709 else 1710 Method->setAccess(D->getAccess()); 1711 if (FunctionTemplate) 1712 FunctionTemplate->setAccess(Method->getAccess()); 1713 1714 SemaRef.CheckOverrideControl(Method); 1715 1716 // If a function is defined as defaulted or deleted, mark it as such now. 1717 if (D->isExplicitlyDefaulted()) 1718 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 1719 if (D->isDeletedAsWritten()) 1720 SemaRef.SetDeclDeleted(Method, Method->getLocation()); 1721 1722 // If there's a function template, let our caller handle it. 1723 if (FunctionTemplate) { 1724 // do nothing 1725 1726 // Don't hide a (potentially) valid declaration with an invalid one. 1727 } else if (Method->isInvalidDecl() && !Previous.empty()) { 1728 // do nothing 1729 1730 // Otherwise, check access to friends and make them visible. 1731 } else if (isFriend) { 1732 // We only need to re-check access for methods which we didn't 1733 // manage to match during parsing. 1734 if (!D->getPreviousDecl()) 1735 SemaRef.CheckFriendAccess(Method); 1736 1737 Record->makeDeclVisibleInContext(Method); 1738 1739 // Otherwise, add the declaration. We don't need to do this for 1740 // class-scope specializations because we'll have matched them with 1741 // the appropriate template. 1742 } else if (!IsClassScopeSpecialization) { 1743 Owner->addDecl(Method); 1744 } 1745 1746 return Method; 1747 } 1748 1749 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1750 return VisitCXXMethodDecl(D); 1751 } 1752 1753 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1754 return VisitCXXMethodDecl(D); 1755 } 1756 1757 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 1758 return VisitCXXMethodDecl(D); 1759 } 1760 1761 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 1762 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None, 1763 /*ExpectParameterPack=*/ false); 1764 } 1765 1766 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1767 TemplateTypeParmDecl *D) { 1768 // TODO: don't always clone when decls are refcounted. 1769 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 1770 1771 TemplateTypeParmDecl *Inst = 1772 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, 1773 D->getLocStart(), D->getLocation(), 1774 D->getDepth() - TemplateArgs.getNumLevels(), 1775 D->getIndex(), D->getIdentifier(), 1776 D->wasDeclaredWithTypename(), 1777 D->isParameterPack()); 1778 Inst->setAccess(AS_public); 1779 1780 if (D->hasDefaultArgument()) { 1781 TypeSourceInfo *InstantiatedDefaultArg = 1782 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, 1783 D->getDefaultArgumentLoc(), D->getDeclName()); 1784 if (InstantiatedDefaultArg) 1785 Inst->setDefaultArgument(InstantiatedDefaultArg, false); 1786 } 1787 1788 // Introduce this template parameter's instantiation into the instantiation 1789 // scope. 1790 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1791 1792 return Inst; 1793 } 1794 1795 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1796 NonTypeTemplateParmDecl *D) { 1797 // Substitute into the type of the non-type template parameter. 1798 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 1799 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 1800 SmallVector<QualType, 4> ExpandedParameterPackTypes; 1801 bool IsExpandedParameterPack = false; 1802 TypeSourceInfo *DI; 1803 QualType T; 1804 bool Invalid = false; 1805 1806 if (D->isExpandedParameterPack()) { 1807 // The non-type template parameter pack is an already-expanded pack 1808 // expansion of types. Substitute into each of the expanded types. 1809 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 1810 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 1811 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 1812 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), 1813 TemplateArgs, 1814 D->getLocation(), 1815 D->getDeclName()); 1816 if (!NewDI) 1817 return 0; 1818 1819 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1820 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(), 1821 D->getLocation()); 1822 if (NewT.isNull()) 1823 return 0; 1824 ExpandedParameterPackTypes.push_back(NewT); 1825 } 1826 1827 IsExpandedParameterPack = true; 1828 DI = D->getTypeSourceInfo(); 1829 T = DI->getType(); 1830 } else if (D->isPackExpansion()) { 1831 // The non-type template parameter pack's type is a pack expansion of types. 1832 // Determine whether we need to expand this parameter pack into separate 1833 // types. 1834 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); 1835 TypeLoc Pattern = Expansion.getPatternLoc(); 1836 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1837 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 1838 1839 // Determine whether the set of unexpanded parameter packs can and should 1840 // be expanded. 1841 bool Expand = true; 1842 bool RetainExpansion = false; 1843 Optional<unsigned> OrigNumExpansions 1844 = Expansion.getTypePtr()->getNumExpansions(); 1845 Optional<unsigned> NumExpansions = OrigNumExpansions; 1846 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 1847 Pattern.getSourceRange(), 1848 Unexpanded, 1849 TemplateArgs, 1850 Expand, RetainExpansion, 1851 NumExpansions)) 1852 return 0; 1853 1854 if (Expand) { 1855 for (unsigned I = 0; I != *NumExpansions; ++I) { 1856 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 1857 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 1858 D->getLocation(), 1859 D->getDeclName()); 1860 if (!NewDI) 1861 return 0; 1862 1863 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1864 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType( 1865 NewDI->getType(), 1866 D->getLocation()); 1867 if (NewT.isNull()) 1868 return 0; 1869 ExpandedParameterPackTypes.push_back(NewT); 1870 } 1871 1872 // Note that we have an expanded parameter pack. The "type" of this 1873 // expanded parameter pack is the original expansion type, but callers 1874 // will end up using the expanded parameter pack types for type-checking. 1875 IsExpandedParameterPack = true; 1876 DI = D->getTypeSourceInfo(); 1877 T = DI->getType(); 1878 } else { 1879 // We cannot fully expand the pack expansion now, so substitute into the 1880 // pattern and create a new pack expansion type. 1881 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 1882 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 1883 D->getLocation(), 1884 D->getDeclName()); 1885 if (!NewPattern) 1886 return 0; 1887 1888 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 1889 NumExpansions); 1890 if (!DI) 1891 return 0; 1892 1893 T = DI->getType(); 1894 } 1895 } else { 1896 // Simple case: substitution into a parameter that is not a parameter pack. 1897 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 1898 D->getLocation(), D->getDeclName()); 1899 if (!DI) 1900 return 0; 1901 1902 // Check that this type is acceptable for a non-type template parameter. 1903 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(), 1904 D->getLocation()); 1905 if (T.isNull()) { 1906 T = SemaRef.Context.IntTy; 1907 Invalid = true; 1908 } 1909 } 1910 1911 NonTypeTemplateParmDecl *Param; 1912 if (IsExpandedParameterPack) 1913 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1914 D->getInnerLocStart(), 1915 D->getLocation(), 1916 D->getDepth() - TemplateArgs.getNumLevels(), 1917 D->getPosition(), 1918 D->getIdentifier(), T, 1919 DI, 1920 ExpandedParameterPackTypes.data(), 1921 ExpandedParameterPackTypes.size(), 1922 ExpandedParameterPackTypesAsWritten.data()); 1923 else 1924 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1925 D->getInnerLocStart(), 1926 D->getLocation(), 1927 D->getDepth() - TemplateArgs.getNumLevels(), 1928 D->getPosition(), 1929 D->getIdentifier(), T, 1930 D->isParameterPack(), DI); 1931 1932 Param->setAccess(AS_public); 1933 if (Invalid) 1934 Param->setInvalidDecl(); 1935 1936 if (D->hasDefaultArgument()) { 1937 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs); 1938 if (!Value.isInvalid()) 1939 Param->setDefaultArgument(Value.get(), false); 1940 } 1941 1942 // Introduce this template parameter's instantiation into the instantiation 1943 // scope. 1944 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1945 return Param; 1946 } 1947 1948 static void collectUnexpandedParameterPacks( 1949 Sema &S, 1950 TemplateParameterList *Params, 1951 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 1952 for (TemplateParameterList::const_iterator I = Params->begin(), 1953 E = Params->end(); I != E; ++I) { 1954 if ((*I)->isTemplateParameterPack()) 1955 continue; 1956 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I)) 1957 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), 1958 Unexpanded); 1959 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I)) 1960 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), 1961 Unexpanded); 1962 } 1963 } 1964 1965 Decl * 1966 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1967 TemplateTemplateParmDecl *D) { 1968 // Instantiate the template parameter list of the template template parameter. 1969 TemplateParameterList *TempParams = D->getTemplateParameters(); 1970 TemplateParameterList *InstParams; 1971 SmallVector<TemplateParameterList*, 8> ExpandedParams; 1972 1973 bool IsExpandedParameterPack = false; 1974 1975 if (D->isExpandedParameterPack()) { 1976 // The template template parameter pack is an already-expanded pack 1977 // expansion of template parameters. Substitute into each of the expanded 1978 // parameters. 1979 ExpandedParams.reserve(D->getNumExpansionTemplateParameters()); 1980 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 1981 I != N; ++I) { 1982 LocalInstantiationScope Scope(SemaRef); 1983 TemplateParameterList *Expansion = 1984 SubstTemplateParams(D->getExpansionTemplateParameters(I)); 1985 if (!Expansion) 1986 return 0; 1987 ExpandedParams.push_back(Expansion); 1988 } 1989 1990 IsExpandedParameterPack = true; 1991 InstParams = TempParams; 1992 } else if (D->isPackExpansion()) { 1993 // The template template parameter pack expands to a pack of template 1994 // template parameters. Determine whether we need to expand this parameter 1995 // pack into separate parameters. 1996 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1997 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), 1998 Unexpanded); 1999 2000 // Determine whether the set of unexpanded parameter packs can and should 2001 // be expanded. 2002 bool Expand = true; 2003 bool RetainExpansion = false; 2004 Optional<unsigned> NumExpansions; 2005 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), 2006 TempParams->getSourceRange(), 2007 Unexpanded, 2008 TemplateArgs, 2009 Expand, RetainExpansion, 2010 NumExpansions)) 2011 return 0; 2012 2013 if (Expand) { 2014 for (unsigned I = 0; I != *NumExpansions; ++I) { 2015 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2016 LocalInstantiationScope Scope(SemaRef); 2017 TemplateParameterList *Expansion = SubstTemplateParams(TempParams); 2018 if (!Expansion) 2019 return 0; 2020 ExpandedParams.push_back(Expansion); 2021 } 2022 2023 // Note that we have an expanded parameter pack. The "type" of this 2024 // expanded parameter pack is the original expansion type, but callers 2025 // will end up using the expanded parameter pack types for type-checking. 2026 IsExpandedParameterPack = true; 2027 InstParams = TempParams; 2028 } else { 2029 // We cannot fully expand the pack expansion now, so just substitute 2030 // into the pattern. 2031 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2032 2033 LocalInstantiationScope Scope(SemaRef); 2034 InstParams = SubstTemplateParams(TempParams); 2035 if (!InstParams) 2036 return 0; 2037 } 2038 } else { 2039 // Perform the actual substitution of template parameters within a new, 2040 // local instantiation scope. 2041 LocalInstantiationScope Scope(SemaRef); 2042 InstParams = SubstTemplateParams(TempParams); 2043 if (!InstParams) 2044 return 0; 2045 } 2046 2047 // Build the template template parameter. 2048 TemplateTemplateParmDecl *Param; 2049 if (IsExpandedParameterPack) 2050 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, 2051 D->getLocation(), 2052 D->getDepth() - TemplateArgs.getNumLevels(), 2053 D->getPosition(), 2054 D->getIdentifier(), InstParams, 2055 ExpandedParams); 2056 else 2057 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, 2058 D->getLocation(), 2059 D->getDepth() - TemplateArgs.getNumLevels(), 2060 D->getPosition(), 2061 D->isParameterPack(), 2062 D->getIdentifier(), InstParams); 2063 if (D->hasDefaultArgument()) { 2064 NestedNameSpecifierLoc QualifierLoc = 2065 D->getDefaultArgument().getTemplateQualifierLoc(); 2066 QualifierLoc = 2067 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs); 2068 TemplateName TName = SemaRef.SubstTemplateName( 2069 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(), 2070 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); 2071 if (!TName.isNull()) 2072 Param->setDefaultArgument( 2073 TemplateArgumentLoc(TemplateArgument(TName), 2074 D->getDefaultArgument().getTemplateQualifierLoc(), 2075 D->getDefaultArgument().getTemplateNameLoc()), 2076 false); 2077 } 2078 Param->setAccess(AS_public); 2079 2080 // Introduce this template parameter's instantiation into the instantiation 2081 // scope. 2082 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2083 2084 return Param; 2085 } 2086 2087 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 2088 // Using directives are never dependent (and never contain any types or 2089 // expressions), so they require no explicit instantiation work. 2090 2091 UsingDirectiveDecl *Inst 2092 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 2093 D->getNamespaceKeyLocation(), 2094 D->getQualifierLoc(), 2095 D->getIdentLocation(), 2096 D->getNominatedNamespace(), 2097 D->getCommonAncestor()); 2098 2099 // Add the using directive to its declaration context 2100 // only if this is not a function or method. 2101 if (!Owner->isFunctionOrMethod()) 2102 Owner->addDecl(Inst); 2103 2104 return Inst; 2105 } 2106 2107 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 2108 2109 // The nested name specifier may be dependent, for example 2110 // template <typename T> struct t { 2111 // struct s1 { T f1(); }; 2112 // struct s2 : s1 { using s1::f1; }; 2113 // }; 2114 // template struct t<int>; 2115 // Here, in using s1::f1, s1 refers to t<T>::s1; 2116 // we need to substitute for t<int>::s1. 2117 NestedNameSpecifierLoc QualifierLoc 2118 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2119 TemplateArgs); 2120 if (!QualifierLoc) 2121 return 0; 2122 2123 // The name info is non-dependent, so no transformation 2124 // is required. 2125 DeclarationNameInfo NameInfo = D->getNameInfo(); 2126 2127 // We only need to do redeclaration lookups if we're in a class 2128 // scope (in fact, it's not really even possible in non-class 2129 // scopes). 2130 bool CheckRedeclaration = Owner->isRecord(); 2131 2132 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 2133 Sema::ForRedeclaration); 2134 2135 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 2136 D->getUsingLoc(), 2137 QualifierLoc, 2138 NameInfo, 2139 D->hasTypename()); 2140 2141 CXXScopeSpec SS; 2142 SS.Adopt(QualifierLoc); 2143 if (CheckRedeclaration) { 2144 Prev.setHideTags(false); 2145 SemaRef.LookupQualifiedName(Prev, Owner); 2146 2147 // Check for invalid redeclarations. 2148 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(), 2149 D->hasTypename(), SS, 2150 D->getLocation(), Prev)) 2151 NewUD->setInvalidDecl(); 2152 2153 } 2154 2155 if (!NewUD->isInvalidDecl() && 2156 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, 2157 D->getLocation())) 2158 NewUD->setInvalidDecl(); 2159 2160 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 2161 NewUD->setAccess(D->getAccess()); 2162 Owner->addDecl(NewUD); 2163 2164 // Don't process the shadow decls for an invalid decl. 2165 if (NewUD->isInvalidDecl()) 2166 return NewUD; 2167 2168 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 2169 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD)) 2170 NewUD->setInvalidDecl(); 2171 return NewUD; 2172 } 2173 2174 bool isFunctionScope = Owner->isFunctionOrMethod(); 2175 2176 // Process the shadow decls. 2177 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 2178 I != E; ++I) { 2179 UsingShadowDecl *Shadow = *I; 2180 NamedDecl *InstTarget = 2181 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 2182 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs)); 2183 if (!InstTarget) 2184 return 0; 2185 2186 UsingShadowDecl *PrevDecl = 0; 2187 if (CheckRedeclaration) { 2188 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl)) 2189 continue; 2190 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) { 2191 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( 2192 Shadow->getLocation(), OldPrev, TemplateArgs)); 2193 } 2194 2195 UsingShadowDecl *InstShadow = 2196 SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl); 2197 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 2198 2199 if (isFunctionScope) 2200 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 2201 } 2202 2203 return NewUD; 2204 } 2205 2206 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 2207 // Ignore these; we handle them in bulk when processing the UsingDecl. 2208 return 0; 2209 } 2210 2211 Decl * TemplateDeclInstantiator 2212 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 2213 NestedNameSpecifierLoc QualifierLoc 2214 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2215 TemplateArgs); 2216 if (!QualifierLoc) 2217 return 0; 2218 2219 CXXScopeSpec SS; 2220 SS.Adopt(QualifierLoc); 2221 2222 // Since NameInfo refers to a typename, it cannot be a C++ special name. 2223 // Hence, no transformation is required for it. 2224 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation()); 2225 NamedDecl *UD = 2226 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 2227 D->getUsingLoc(), SS, NameInfo, 0, 2228 /*instantiation*/ true, 2229 /*typename*/ true, D->getTypenameLoc()); 2230 if (UD) 2231 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 2232 2233 return UD; 2234 } 2235 2236 Decl * TemplateDeclInstantiator 2237 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 2238 NestedNameSpecifierLoc QualifierLoc 2239 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs); 2240 if (!QualifierLoc) 2241 return 0; 2242 2243 CXXScopeSpec SS; 2244 SS.Adopt(QualifierLoc); 2245 2246 DeclarationNameInfo NameInfo 2247 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2248 2249 NamedDecl *UD = 2250 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 2251 D->getUsingLoc(), SS, NameInfo, 0, 2252 /*instantiation*/ true, 2253 /*typename*/ false, SourceLocation()); 2254 if (UD) 2255 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 2256 2257 return UD; 2258 } 2259 2260 2261 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 2262 ClassScopeFunctionSpecializationDecl *Decl) { 2263 CXXMethodDecl *OldFD = Decl->getSpecialization(); 2264 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 2265 0, true)); 2266 2267 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName, 2268 Sema::ForRedeclaration); 2269 2270 TemplateArgumentListInfo TemplateArgs; 2271 TemplateArgumentListInfo* TemplateArgsPtr = 0; 2272 if (Decl->hasExplicitTemplateArgs()) { 2273 TemplateArgs = Decl->templateArgs(); 2274 TemplateArgsPtr = &TemplateArgs; 2275 } 2276 2277 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext); 2278 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr, 2279 Previous)) { 2280 NewFD->setInvalidDecl(); 2281 return NewFD; 2282 } 2283 2284 // Associate the specialization with the pattern. 2285 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl()); 2286 assert(Specialization && "Class scope Specialization is null"); 2287 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD); 2288 2289 return NewFD; 2290 } 2291 2292 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( 2293 OMPThreadPrivateDecl *D) { 2294 SmallVector<Expr *, 5> Vars; 2295 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(), 2296 E = D->varlist_end(); 2297 I != E; ++I) { 2298 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take(); 2299 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"); 2300 Vars.push_back(Var); 2301 } 2302 2303 OMPThreadPrivateDecl *TD = 2304 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars); 2305 2306 return TD; 2307 } 2308 2309 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 2310 return VisitFunctionDecl(D, 0); 2311 } 2312 2313 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 2314 return VisitCXXMethodDecl(D, 0); 2315 } 2316 2317 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 2318 llvm_unreachable("There are only CXXRecordDecls in C++"); 2319 } 2320 2321 Decl * 2322 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 2323 ClassTemplateSpecializationDecl *D) { 2324 llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur" 2325 "inside templates"); 2326 } 2327 2328 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 2329 VarTemplateSpecializationDecl *D) { 2330 2331 TemplateArgumentListInfo VarTemplateArgsInfo; 2332 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 2333 assert(VarTemplate && 2334 "A template specialization without specialized template?"); 2335 2336 // Substitute the current template arguments. 2337 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 2338 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 2339 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 2340 2341 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(), 2342 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs)) 2343 return 0; 2344 2345 // Check that the template argument list is well-formed for this template. 2346 SmallVector<TemplateArgument, 4> Converted; 2347 bool ExpansionIntoFixedList = false; 2348 if (SemaRef.CheckTemplateArgumentList( 2349 VarTemplate, VarTemplate->getLocStart(), 2350 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false, 2351 Converted, &ExpansionIntoFixedList)) 2352 return 0; 2353 2354 // Find the variable template specialization declaration that 2355 // corresponds to these arguments. 2356 void *InsertPos = 0; 2357 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization( 2358 Converted.data(), Converted.size(), InsertPos)) 2359 // If we already have a variable template specialization, return it. 2360 return VarSpec; 2361 2362 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos, 2363 VarTemplateArgsInfo, Converted); 2364 } 2365 2366 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 2367 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos, 2368 const TemplateArgumentListInfo &TemplateArgsInfo, 2369 llvm::ArrayRef<TemplateArgument> Converted) { 2370 2371 // If this is the variable for an anonymous struct or union, 2372 // instantiate the anonymous struct/union type first. 2373 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 2374 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 2375 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 2376 return 0; 2377 2378 // Do substitution on the type of the declaration 2379 TypeSourceInfo *DI = 2380 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 2381 D->getTypeSpecStartLoc(), D->getDeclName()); 2382 if (!DI) 2383 return 0; 2384 2385 if (DI->getType()->isFunctionType()) { 2386 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 2387 << D->isStaticDataMember() << DI->getType(); 2388 return 0; 2389 } 2390 2391 // Build the instantiated declaration 2392 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 2393 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2394 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(), 2395 Converted.size()); 2396 Var->setTemplateArgsInfo(TemplateArgsInfo); 2397 if (InsertPos) 2398 VarTemplate->AddSpecialization(Var, InsertPos); 2399 2400 // Substitute the nested name specifier, if any. 2401 if (SubstQualifier(D, Var)) 2402 return 0; 2403 2404 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, 2405 Owner, StartingScope); 2406 2407 return Var; 2408 } 2409 2410 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 2411 llvm_unreachable("@defs is not supported in Objective-C++"); 2412 } 2413 2414 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 2415 // FIXME: We need to be able to instantiate FriendTemplateDecls. 2416 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 2417 DiagnosticsEngine::Error, 2418 "cannot instantiate %0 yet"); 2419 SemaRef.Diag(D->getLocation(), DiagID) 2420 << D->getDeclKindName(); 2421 2422 return 0; 2423 } 2424 2425 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 2426 llvm_unreachable("Unexpected decl"); 2427 } 2428 2429 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 2430 const MultiLevelTemplateArgumentList &TemplateArgs) { 2431 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 2432 if (D->isInvalidDecl()) 2433 return 0; 2434 2435 return Instantiator.Visit(D); 2436 } 2437 2438 /// \brief Instantiates a nested template parameter list in the current 2439 /// instantiation context. 2440 /// 2441 /// \param L The parameter list to instantiate 2442 /// 2443 /// \returns NULL if there was an error 2444 TemplateParameterList * 2445 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 2446 // Get errors for all the parameters before bailing out. 2447 bool Invalid = false; 2448 2449 unsigned N = L->size(); 2450 typedef SmallVector<NamedDecl *, 8> ParamVector; 2451 ParamVector Params; 2452 Params.reserve(N); 2453 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 2454 PI != PE; ++PI) { 2455 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 2456 Params.push_back(D); 2457 Invalid = Invalid || !D || D->isInvalidDecl(); 2458 } 2459 2460 // Clean up if we had an error. 2461 if (Invalid) 2462 return NULL; 2463 2464 TemplateParameterList *InstL 2465 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 2466 L->getLAngleLoc(), &Params.front(), N, 2467 L->getRAngleLoc()); 2468 return InstL; 2469 } 2470 2471 /// \brief Instantiate the declaration of a class template partial 2472 /// specialization. 2473 /// 2474 /// \param ClassTemplate the (instantiated) class template that is partially 2475 // specialized by the instantiation of \p PartialSpec. 2476 /// 2477 /// \param PartialSpec the (uninstantiated) class template partial 2478 /// specialization that we are instantiating. 2479 /// 2480 /// \returns The instantiated partial specialization, if successful; otherwise, 2481 /// NULL to indicate an error. 2482 ClassTemplatePartialSpecializationDecl * 2483 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 2484 ClassTemplateDecl *ClassTemplate, 2485 ClassTemplatePartialSpecializationDecl *PartialSpec) { 2486 // Create a local instantiation scope for this class template partial 2487 // specialization, which will contain the instantiations of the template 2488 // parameters. 2489 LocalInstantiationScope Scope(SemaRef); 2490 2491 // Substitute into the template parameters of the class template partial 2492 // specialization. 2493 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 2494 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2495 if (!InstParams) 2496 return 0; 2497 2498 // Substitute into the template arguments of the class template partial 2499 // specialization. 2500 const ASTTemplateArgumentListInfo *TemplArgInfo 2501 = PartialSpec->getTemplateArgsAsWritten(); 2502 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 2503 TemplArgInfo->RAngleLoc); 2504 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 2505 TemplArgInfo->NumTemplateArgs, 2506 InstTemplateArgs, TemplateArgs)) 2507 return 0; 2508 2509 // Check that the template argument list is well-formed for this 2510 // class template. 2511 SmallVector<TemplateArgument, 4> Converted; 2512 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 2513 PartialSpec->getLocation(), 2514 InstTemplateArgs, 2515 false, 2516 Converted)) 2517 return 0; 2518 2519 // Figure out where to insert this class template partial specialization 2520 // in the member template's set of class template partial specializations. 2521 void *InsertPos = 0; 2522 ClassTemplateSpecializationDecl *PrevDecl 2523 = ClassTemplate->findPartialSpecialization(Converted.data(), 2524 Converted.size(), InsertPos); 2525 2526 // Build the canonical type that describes the converted template 2527 // arguments of the class template partial specialization. 2528 QualType CanonType 2529 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 2530 Converted.data(), 2531 Converted.size()); 2532 2533 // Build the fully-sugared type for this class template 2534 // specialization as the user wrote in the specialization 2535 // itself. This means that we'll pretty-print the type retrieved 2536 // from the specialization's declaration the way that the user 2537 // actually wrote the specialization, rather than formatting the 2538 // name based on the "canonical" representation used to store the 2539 // template arguments in the specialization. 2540 TypeSourceInfo *WrittenTy 2541 = SemaRef.Context.getTemplateSpecializationTypeInfo( 2542 TemplateName(ClassTemplate), 2543 PartialSpec->getLocation(), 2544 InstTemplateArgs, 2545 CanonType); 2546 2547 if (PrevDecl) { 2548 // We've already seen a partial specialization with the same template 2549 // parameters and template arguments. This can happen, for example, when 2550 // substituting the outer template arguments ends up causing two 2551 // class template partial specializations of a member class template 2552 // to have identical forms, e.g., 2553 // 2554 // template<typename T, typename U> 2555 // struct Outer { 2556 // template<typename X, typename Y> struct Inner; 2557 // template<typename Y> struct Inner<T, Y>; 2558 // template<typename Y> struct Inner<U, Y>; 2559 // }; 2560 // 2561 // Outer<int, int> outer; // error: the partial specializations of Inner 2562 // // have the same signature. 2563 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 2564 << WrittenTy->getType(); 2565 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 2566 << SemaRef.Context.getTypeDeclType(PrevDecl); 2567 return 0; 2568 } 2569 2570 2571 // Create the class template partial specialization declaration. 2572 ClassTemplatePartialSpecializationDecl *InstPartialSpec 2573 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, 2574 PartialSpec->getTagKind(), 2575 Owner, 2576 PartialSpec->getLocStart(), 2577 PartialSpec->getLocation(), 2578 InstParams, 2579 ClassTemplate, 2580 Converted.data(), 2581 Converted.size(), 2582 InstTemplateArgs, 2583 CanonType, 2584 0); 2585 // Substitute the nested name specifier, if any. 2586 if (SubstQualifier(PartialSpec, InstPartialSpec)) 2587 return 0; 2588 2589 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 2590 InstPartialSpec->setTypeAsWritten(WrittenTy); 2591 2592 // Add this partial specialization to the set of class template partial 2593 // specializations. 2594 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0); 2595 return InstPartialSpec; 2596 } 2597 2598 /// \brief Instantiate the declaration of a variable template partial 2599 /// specialization. 2600 /// 2601 /// \param VarTemplate the (instantiated) variable template that is partially 2602 /// specialized by the instantiation of \p PartialSpec. 2603 /// 2604 /// \param PartialSpec the (uninstantiated) variable template partial 2605 /// specialization that we are instantiating. 2606 /// 2607 /// \returns The instantiated partial specialization, if successful; otherwise, 2608 /// NULL to indicate an error. 2609 VarTemplatePartialSpecializationDecl * 2610 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 2611 VarTemplateDecl *VarTemplate, 2612 VarTemplatePartialSpecializationDecl *PartialSpec) { 2613 // Create a local instantiation scope for this variable template partial 2614 // specialization, which will contain the instantiations of the template 2615 // parameters. 2616 LocalInstantiationScope Scope(SemaRef); 2617 2618 // Substitute into the template parameters of the variable template partial 2619 // specialization. 2620 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 2621 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2622 if (!InstParams) 2623 return 0; 2624 2625 // Substitute into the template arguments of the variable template partial 2626 // specialization. 2627 const ASTTemplateArgumentListInfo *TemplArgInfo 2628 = PartialSpec->getTemplateArgsAsWritten(); 2629 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 2630 TemplArgInfo->RAngleLoc); 2631 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 2632 TemplArgInfo->NumTemplateArgs, 2633 InstTemplateArgs, TemplateArgs)) 2634 return 0; 2635 2636 // Check that the template argument list is well-formed for this 2637 // class template. 2638 SmallVector<TemplateArgument, 4> Converted; 2639 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 2640 InstTemplateArgs, false, Converted)) 2641 return 0; 2642 2643 // Figure out where to insert this variable template partial specialization 2644 // in the member template's set of variable template partial specializations. 2645 void *InsertPos = 0; 2646 VarTemplateSpecializationDecl *PrevDecl = 2647 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(), 2648 InsertPos); 2649 2650 // Build the canonical type that describes the converted template 2651 // arguments of the variable template partial specialization. 2652 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 2653 TemplateName(VarTemplate), Converted.data(), Converted.size()); 2654 2655 // Build the fully-sugared type for this variable template 2656 // specialization as the user wrote in the specialization 2657 // itself. This means that we'll pretty-print the type retrieved 2658 // from the specialization's declaration the way that the user 2659 // actually wrote the specialization, rather than formatting the 2660 // name based on the "canonical" representation used to store the 2661 // template arguments in the specialization. 2662 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 2663 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 2664 CanonType); 2665 2666 if (PrevDecl) { 2667 // We've already seen a partial specialization with the same template 2668 // parameters and template arguments. This can happen, for example, when 2669 // substituting the outer template arguments ends up causing two 2670 // variable template partial specializations of a member variable template 2671 // to have identical forms, e.g., 2672 // 2673 // template<typename T, typename U> 2674 // struct Outer { 2675 // template<typename X, typename Y> pair<X,Y> p; 2676 // template<typename Y> pair<T, Y> p; 2677 // template<typename Y> pair<U, Y> p; 2678 // }; 2679 // 2680 // Outer<int, int> outer; // error: the partial specializations of Inner 2681 // // have the same signature. 2682 SemaRef.Diag(PartialSpec->getLocation(), 2683 diag::err_var_partial_spec_redeclared) 2684 << WrittenTy->getType(); 2685 SemaRef.Diag(PrevDecl->getLocation(), 2686 diag::note_var_prev_partial_spec_here); 2687 return 0; 2688 } 2689 2690 // Do substitution on the type of the declaration 2691 TypeSourceInfo *DI = SemaRef.SubstType( 2692 PartialSpec->getTypeSourceInfo(), TemplateArgs, 2693 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 2694 if (!DI) 2695 return 0; 2696 2697 if (DI->getType()->isFunctionType()) { 2698 SemaRef.Diag(PartialSpec->getLocation(), 2699 diag::err_variable_instantiates_to_function) 2700 << PartialSpec->isStaticDataMember() << DI->getType(); 2701 return 0; 2702 } 2703 2704 // Create the variable template partial specialization declaration. 2705 VarTemplatePartialSpecializationDecl *InstPartialSpec = 2706 VarTemplatePartialSpecializationDecl::Create( 2707 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 2708 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 2709 DI, PartialSpec->getStorageClass(), Converted.data(), 2710 Converted.size(), InstTemplateArgs); 2711 2712 // Substitute the nested name specifier, if any. 2713 if (SubstQualifier(PartialSpec, InstPartialSpec)) 2714 return 0; 2715 2716 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 2717 InstPartialSpec->setTypeAsWritten(WrittenTy); 2718 2719 // Add this partial specialization to the set of variable template partial 2720 // specializations. The instantiation of the initializer is not necessary. 2721 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0); 2722 2723 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 2724 LateAttrs, Owner, StartingScope); 2725 2726 return InstPartialSpec; 2727 } 2728 2729 TypeSourceInfo* 2730 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 2731 SmallVectorImpl<ParmVarDecl *> &Params) { 2732 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 2733 assert(OldTInfo && "substituting function without type source info"); 2734 assert(Params.empty() && "parameter vector is non-empty at start"); 2735 2736 CXXRecordDecl *ThisContext = 0; 2737 unsigned ThisTypeQuals = 0; 2738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 2739 ThisContext = cast<CXXRecordDecl>(Owner); 2740 ThisTypeQuals = Method->getTypeQualifiers(); 2741 } 2742 2743 TypeSourceInfo *NewTInfo 2744 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 2745 D->getTypeSpecStartLoc(), 2746 D->getDeclName(), 2747 ThisContext, ThisTypeQuals); 2748 if (!NewTInfo) 2749 return 0; 2750 2751 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 2752 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 2753 if (NewTInfo != OldTInfo) { 2754 // Get parameters from the new type info. 2755 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 2756 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 2757 unsigned NewIdx = 0; 2758 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs(); 2759 OldIdx != NumOldParams; ++OldIdx) { 2760 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx); 2761 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 2762 2763 Optional<unsigned> NumArgumentsInExpansion; 2764 if (OldParam->isParameterPack()) 2765 NumArgumentsInExpansion = 2766 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 2767 TemplateArgs); 2768 if (!NumArgumentsInExpansion) { 2769 // Simple case: normal parameter, or a parameter pack that's 2770 // instantiated to a (still-dependent) parameter pack. 2771 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++); 2772 Params.push_back(NewParam); 2773 Scope->InstantiatedLocal(OldParam, NewParam); 2774 } else { 2775 // Parameter pack expansion: make the instantiation an argument pack. 2776 Scope->MakeInstantiatedLocalArgPack(OldParam); 2777 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 2778 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++); 2779 Params.push_back(NewParam); 2780 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 2781 } 2782 } 2783 } 2784 } else { 2785 // The function type itself was not dependent and therefore no 2786 // substitution occurred. However, we still need to instantiate 2787 // the function parameters themselves. 2788 const FunctionProtoType *OldProto = 2789 cast<FunctionProtoType>(OldProtoLoc.getType()); 2790 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) { 2791 ParmVarDecl *OldParam = OldProtoLoc.getArg(i); 2792 if (!OldParam) { 2793 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 2794 D, D->getLocation(), OldProto->getArgType(i))); 2795 continue; 2796 } 2797 2798 ParmVarDecl *Parm = 2799 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 2800 if (!Parm) 2801 return 0; 2802 Params.push_back(Parm); 2803 } 2804 } 2805 } else { 2806 // If the type of this function, after ignoring parentheses, is not 2807 // *directly* a function type, then we're instantiating a function that 2808 // was declared via a typedef or with attributes, e.g., 2809 // 2810 // typedef int functype(int, int); 2811 // functype func; 2812 // int __cdecl meth(int, int); 2813 // 2814 // In this case, we'll just go instantiate the ParmVarDecls that we 2815 // synthesized in the method declaration. 2816 SmallVector<QualType, 4> ParamTypes; 2817 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(), 2818 D->getNumParams(), TemplateArgs, ParamTypes, 2819 &Params)) 2820 return 0; 2821 } 2822 2823 return NewTInfo; 2824 } 2825 2826 /// Introduce the instantiated function parameters into the local 2827 /// instantiation scope, and set the parameter names to those used 2828 /// in the template. 2829 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 2830 const FunctionDecl *PatternDecl, 2831 LocalInstantiationScope &Scope, 2832 const MultiLevelTemplateArgumentList &TemplateArgs) { 2833 unsigned FParamIdx = 0; 2834 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 2835 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 2836 if (!PatternParam->isParameterPack()) { 2837 // Simple case: not a parameter pack. 2838 assert(FParamIdx < Function->getNumParams()); 2839 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 2840 FunctionParam->setDeclName(PatternParam->getDeclName()); 2841 Scope.InstantiatedLocal(PatternParam, FunctionParam); 2842 ++FParamIdx; 2843 continue; 2844 } 2845 2846 // Expand the parameter pack. 2847 Scope.MakeInstantiatedLocalArgPack(PatternParam); 2848 Optional<unsigned> NumArgumentsInExpansion 2849 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 2850 assert(NumArgumentsInExpansion && 2851 "should only be called when all template arguments are known"); 2852 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 2853 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 2854 FunctionParam->setDeclName(PatternParam->getDeclName()); 2855 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 2856 ++FParamIdx; 2857 } 2858 } 2859 } 2860 2861 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New, 2862 const FunctionProtoType *Proto, 2863 const MultiLevelTemplateArgumentList &TemplateArgs) { 2864 assert(Proto->getExceptionSpecType() != EST_Uninstantiated); 2865 2866 // C++11 [expr.prim.general]p3: 2867 // If a declaration declares a member function or member function 2868 // template of a class X, the expression this is a prvalue of type 2869 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 2870 // and the end of the function-definition, member-declarator, or 2871 // declarator. 2872 CXXRecordDecl *ThisContext = 0; 2873 unsigned ThisTypeQuals = 0; 2874 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) { 2875 ThisContext = Method->getParent(); 2876 ThisTypeQuals = Method->getTypeQualifiers(); 2877 } 2878 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals, 2879 SemaRef.getLangOpts().CPlusPlus11); 2880 2881 // The function has an exception specification or a "noreturn" 2882 // attribute. Substitute into each of the exception types. 2883 SmallVector<QualType, 4> Exceptions; 2884 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 2885 // FIXME: Poor location information! 2886 if (const PackExpansionType *PackExpansion 2887 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) { 2888 // We have a pack expansion. Instantiate it. 2889 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2890 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(), 2891 Unexpanded); 2892 assert(!Unexpanded.empty() && 2893 "Pack expansion without parameter packs?"); 2894 2895 bool Expand = false; 2896 bool RetainExpansion = false; 2897 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions(); 2898 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(), 2899 SourceRange(), 2900 Unexpanded, 2901 TemplateArgs, 2902 Expand, 2903 RetainExpansion, 2904 NumExpansions)) 2905 break; 2906 2907 if (!Expand) { 2908 // We can't expand this pack expansion into separate arguments yet; 2909 // just substitute into the pattern and create a new pack expansion 2910 // type. 2911 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2912 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 2913 TemplateArgs, 2914 New->getLocation(), New->getDeclName()); 2915 if (T.isNull()) 2916 break; 2917 2918 T = SemaRef.Context.getPackExpansionType(T, NumExpansions); 2919 Exceptions.push_back(T); 2920 continue; 2921 } 2922 2923 // Substitute into the pack expansion pattern for each template 2924 bool Invalid = false; 2925 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) { 2926 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx); 2927 2928 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 2929 TemplateArgs, 2930 New->getLocation(), New->getDeclName()); 2931 if (T.isNull()) { 2932 Invalid = true; 2933 break; 2934 } 2935 2936 Exceptions.push_back(T); 2937 } 2938 2939 if (Invalid) 2940 break; 2941 2942 continue; 2943 } 2944 2945 QualType T 2946 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 2947 New->getLocation(), New->getDeclName()); 2948 if (T.isNull() || 2949 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 2950 continue; 2951 2952 Exceptions.push_back(T); 2953 } 2954 Expr *NoexceptExpr = 0; 2955 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) { 2956 EnterExpressionEvaluationContext Unevaluated(SemaRef, 2957 Sema::ConstantEvaluated); 2958 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs); 2959 if (E.isUsable()) 2960 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart()); 2961 2962 if (E.isUsable()) { 2963 NoexceptExpr = E.take(); 2964 if (!NoexceptExpr->isTypeDependent() && 2965 !NoexceptExpr->isValueDependent()) 2966 NoexceptExpr 2967 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr, 2968 0, diag::err_noexcept_needs_constant_expression, 2969 /*AllowFold*/ false).take(); 2970 } 2971 } 2972 2973 // Rebuild the function type 2974 const FunctionProtoType *NewProto 2975 = New->getType()->getAs<FunctionProtoType>(); 2976 assert(NewProto && "Template instantiation without function prototype?"); 2977 2978 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo(); 2979 EPI.ExceptionSpecType = Proto->getExceptionSpecType(); 2980 EPI.NumExceptions = Exceptions.size(); 2981 EPI.Exceptions = Exceptions.data(); 2982 EPI.NoexceptExpr = NoexceptExpr; 2983 2984 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 2985 NewProto->getArgTypes(), EPI)); 2986 } 2987 2988 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 2989 FunctionDecl *Decl) { 2990 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 2991 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 2992 return; 2993 2994 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 2995 InstantiatingTemplate::ExceptionSpecification()); 2996 if (Inst.isInvalid()) { 2997 // We hit the instantiation depth limit. Clear the exception specification 2998 // so that our callers don't have to cope with EST_Uninstantiated. 2999 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3000 EPI.ExceptionSpecType = EST_None; 3001 Decl->setType(Context.getFunctionType(Proto->getResultType(), 3002 Proto->getArgTypes(), EPI)); 3003 return; 3004 } 3005 3006 // Enter the scope of this instantiation. We don't use 3007 // PushDeclContext because we don't have a scope. 3008 Sema::ContextRAII savedContext(*this, Decl); 3009 LocalInstantiationScope Scope(*this); 3010 3011 MultiLevelTemplateArgumentList TemplateArgs = 3012 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true); 3013 3014 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 3015 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs); 3016 3017 ::InstantiateExceptionSpec(*this, Decl, 3018 Template->getType()->castAs<FunctionProtoType>(), 3019 TemplateArgs); 3020 } 3021 3022 /// \brief Initializes the common fields of an instantiation function 3023 /// declaration (New) from the corresponding fields of its template (Tmpl). 3024 /// 3025 /// \returns true if there was an error 3026 bool 3027 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 3028 FunctionDecl *Tmpl) { 3029 if (Tmpl->isDeleted()) 3030 New->setDeletedAsWritten(); 3031 3032 // Forward the mangling number from the template to the instantiated decl. 3033 SemaRef.Context.setManglingNumber(New, 3034 SemaRef.Context.getManglingNumber(Tmpl)); 3035 3036 // If we are performing substituting explicitly-specified template arguments 3037 // or deduced template arguments into a function template and we reach this 3038 // point, we are now past the point where SFINAE applies and have committed 3039 // to keeping the new function template specialization. We therefore 3040 // convert the active template instantiation for the function template 3041 // into a template instantiation for this specific function template 3042 // specialization, which is not a SFINAE context, so that we diagnose any 3043 // further errors in the declaration itself. 3044 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 3045 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 3046 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 3047 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 3048 if (FunctionTemplateDecl *FunTmpl 3049 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 3050 assert(FunTmpl->getTemplatedDecl() == Tmpl && 3051 "Deduction from the wrong function template?"); 3052 (void) FunTmpl; 3053 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 3054 ActiveInst.Entity = New; 3055 } 3056 } 3057 3058 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 3059 assert(Proto && "Function template without prototype?"); 3060 3061 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 3062 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3063 3064 // DR1330: In C++11, defer instantiation of a non-trivial 3065 // exception specification. 3066 if (SemaRef.getLangOpts().CPlusPlus11 && 3067 EPI.ExceptionSpecType != EST_None && 3068 EPI.ExceptionSpecType != EST_DynamicNone && 3069 EPI.ExceptionSpecType != EST_BasicNoexcept) { 3070 FunctionDecl *ExceptionSpecTemplate = Tmpl; 3071 if (EPI.ExceptionSpecType == EST_Uninstantiated) 3072 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate; 3073 ExceptionSpecificationType NewEST = EST_Uninstantiated; 3074 if (EPI.ExceptionSpecType == EST_Unevaluated) 3075 NewEST = EST_Unevaluated; 3076 3077 // Mark the function has having an uninstantiated exception specification. 3078 const FunctionProtoType *NewProto 3079 = New->getType()->getAs<FunctionProtoType>(); 3080 assert(NewProto && "Template instantiation without function prototype?"); 3081 EPI = NewProto->getExtProtoInfo(); 3082 EPI.ExceptionSpecType = NewEST; 3083 EPI.ExceptionSpecDecl = New; 3084 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate; 3085 New->setType(SemaRef.Context.getFunctionType( 3086 NewProto->getResultType(), NewProto->getArgTypes(), EPI)); 3087 } else { 3088 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs); 3089 } 3090 } 3091 3092 // Get the definition. Leaves the variable unchanged if undefined. 3093 const FunctionDecl *Definition = Tmpl; 3094 Tmpl->isDefined(Definition); 3095 3096 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 3097 LateAttrs, StartingScope); 3098 3099 return false; 3100 } 3101 3102 /// \brief Initializes common fields of an instantiated method 3103 /// declaration (New) from the corresponding fields of its template 3104 /// (Tmpl). 3105 /// 3106 /// \returns true if there was an error 3107 bool 3108 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 3109 CXXMethodDecl *Tmpl) { 3110 if (InitFunctionInstantiation(New, Tmpl)) 3111 return true; 3112 3113 New->setAccess(Tmpl->getAccess()); 3114 if (Tmpl->isVirtualAsWritten()) 3115 New->setVirtualAsWritten(true); 3116 3117 // FIXME: New needs a pointer to Tmpl 3118 return false; 3119 } 3120 3121 /// \brief Instantiate the definition of the given function from its 3122 /// template. 3123 /// 3124 /// \param PointOfInstantiation the point at which the instantiation was 3125 /// required. Note that this is not precisely a "point of instantiation" 3126 /// for the function, but it's close. 3127 /// 3128 /// \param Function the already-instantiated declaration of a 3129 /// function template specialization or member function of a class template 3130 /// specialization. 3131 /// 3132 /// \param Recursive if true, recursively instantiates any functions that 3133 /// are required by this instantiation. 3134 /// 3135 /// \param DefinitionRequired if true, then we are performing an explicit 3136 /// instantiation where the body of the function is required. Complain if 3137 /// there is no such body. 3138 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 3139 FunctionDecl *Function, 3140 bool Recursive, 3141 bool DefinitionRequired) { 3142 if (Function->isInvalidDecl() || Function->isDefined()) 3143 return; 3144 3145 // Never instantiate an explicit specialization except if it is a class scope 3146 // explicit specialization. 3147 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 3148 !Function->getClassScopeSpecializationPattern()) 3149 return; 3150 3151 // Find the function body that we'll be substituting. 3152 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 3153 assert(PatternDecl && "instantiating a non-template"); 3154 3155 Stmt *Pattern = PatternDecl->getBody(PatternDecl); 3156 assert(PatternDecl && "template definition is not a template"); 3157 if (!Pattern) { 3158 // Try to find a defaulted definition 3159 PatternDecl->isDefined(PatternDecl); 3160 } 3161 assert(PatternDecl && "template definition is not a template"); 3162 3163 // Postpone late parsed template instantiations. 3164 if (PatternDecl->isLateTemplateParsed() && 3165 !LateTemplateParser) { 3166 PendingInstantiations.push_back( 3167 std::make_pair(Function, PointOfInstantiation)); 3168 return; 3169 } 3170 3171 // Call the LateTemplateParser callback if there is a need to late parse 3172 // a templated function definition. 3173 if (!Pattern && PatternDecl->isLateTemplateParsed() && 3174 LateTemplateParser) { 3175 // FIXME: Optimize to allow individual templates to be deserialized. 3176 if (PatternDecl->isFromASTFile()) 3177 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 3178 3179 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl); 3180 assert(LPT && "missing LateParsedTemplate"); 3181 LateTemplateParser(OpaqueParser, *LPT); 3182 Pattern = PatternDecl->getBody(PatternDecl); 3183 } 3184 3185 if (!Pattern && !PatternDecl->isDefaulted()) { 3186 if (DefinitionRequired) { 3187 if (Function->getPrimaryTemplate()) 3188 Diag(PointOfInstantiation, 3189 diag::err_explicit_instantiation_undefined_func_template) 3190 << Function->getPrimaryTemplate(); 3191 else 3192 Diag(PointOfInstantiation, 3193 diag::err_explicit_instantiation_undefined_member) 3194 << 1 << Function->getDeclName() << Function->getDeclContext(); 3195 3196 if (PatternDecl) 3197 Diag(PatternDecl->getLocation(), 3198 diag::note_explicit_instantiation_here); 3199 Function->setInvalidDecl(); 3200 } else if (Function->getTemplateSpecializationKind() 3201 == TSK_ExplicitInstantiationDefinition) { 3202 PendingInstantiations.push_back( 3203 std::make_pair(Function, PointOfInstantiation)); 3204 } 3205 3206 return; 3207 } 3208 3209 // C++1y [temp.explicit]p10: 3210 // Except for inline functions, declarations with types deduced from their 3211 // initializer or return value, and class template specializations, other 3212 // explicit instantiation declarations have the effect of suppressing the 3213 // implicit instantiation of the entity to which they refer. 3214 if (Function->getTemplateSpecializationKind() 3215 == TSK_ExplicitInstantiationDeclaration && 3216 !PatternDecl->isInlined() && 3217 !PatternDecl->getResultType()->getContainedAutoType()) 3218 return; 3219 3220 if (PatternDecl->isInlined()) 3221 Function->setImplicitlyInline(); 3222 3223 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 3224 if (Inst.isInvalid()) 3225 return; 3226 3227 // Copy the inner loc start from the pattern. 3228 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 3229 3230 // If we're performing recursive template instantiation, create our own 3231 // queue of pending implicit instantiations that we will instantiate later, 3232 // while we're still within our own instantiation context. 3233 SmallVector<VTableUse, 16> SavedVTableUses; 3234 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 3235 SavePendingLocalImplicitInstantiationsRAII 3236 SavedPendingLocalImplicitInstantiations(*this); 3237 if (Recursive) { 3238 VTableUses.swap(SavedVTableUses); 3239 PendingInstantiations.swap(SavedPendingInstantiations); 3240 } 3241 3242 EnterExpressionEvaluationContext EvalContext(*this, 3243 Sema::PotentiallyEvaluated); 3244 3245 // Introduce a new scope where local variable instantiations will be 3246 // recorded, unless we're actually a member function within a local 3247 // class, in which case we need to merge our results with the parent 3248 // scope (of the enclosing function). 3249 bool MergeWithParentScope = false; 3250 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 3251 MergeWithParentScope = Rec->isLocalClass(); 3252 3253 LocalInstantiationScope Scope(*this, MergeWithParentScope); 3254 3255 if (PatternDecl->isDefaulted()) 3256 SetDeclDefaulted(Function, PatternDecl->getLocation()); 3257 else { 3258 ActOnStartOfFunctionDef(0, Function); 3259 3260 // Enter the scope of this instantiation. We don't use 3261 // PushDeclContext because we don't have a scope. 3262 Sema::ContextRAII savedContext(*this, Function); 3263 3264 MultiLevelTemplateArgumentList TemplateArgs = 3265 getTemplateInstantiationArgs(Function, 0, false, PatternDecl); 3266 3267 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 3268 TemplateArgs); 3269 3270 // If this is a constructor, instantiate the member initializers. 3271 if (const CXXConstructorDecl *Ctor = 3272 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 3273 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 3274 TemplateArgs); 3275 } 3276 3277 // Instantiate the function body. 3278 StmtResult Body = SubstStmt(Pattern, TemplateArgs); 3279 3280 if (Body.isInvalid()) 3281 Function->setInvalidDecl(); 3282 3283 ActOnFinishFunctionBody(Function, Body.get(), 3284 /*IsInstantiation=*/true); 3285 3286 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 3287 3288 savedContext.pop(); 3289 } 3290 3291 DeclGroupRef DG(Function); 3292 Consumer.HandleTopLevelDecl(DG); 3293 3294 // This class may have local implicit instantiations that need to be 3295 // instantiation within this scope. 3296 PerformPendingInstantiations(/*LocalOnly=*/true); 3297 Scope.Exit(); 3298 3299 if (Recursive) { 3300 // Define any pending vtables. 3301 DefineUsedVTables(); 3302 3303 // Instantiate any pending implicit instantiations found during the 3304 // instantiation of this template. 3305 PerformPendingInstantiations(); 3306 3307 // Restore the set of pending vtables. 3308 assert(VTableUses.empty() && 3309 "VTableUses should be empty before it is discarded."); 3310 VTableUses.swap(SavedVTableUses); 3311 3312 // Restore the set of pending implicit instantiations. 3313 assert(PendingInstantiations.empty() && 3314 "PendingInstantiations should be empty before it is discarded."); 3315 PendingInstantiations.swap(SavedPendingInstantiations); 3316 } 3317 } 3318 3319 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 3320 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 3321 const TemplateArgumentList &TemplateArgList, 3322 const TemplateArgumentListInfo &TemplateArgsInfo, 3323 SmallVectorImpl<TemplateArgument> &Converted, 3324 SourceLocation PointOfInstantiation, void *InsertPos, 3325 LateInstantiatedAttrVec *LateAttrs, 3326 LocalInstantiationScope *StartingScope) { 3327 if (FromVar->isInvalidDecl()) 3328 return 0; 3329 3330 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 3331 if (Inst.isInvalid()) 3332 return 0; 3333 3334 MultiLevelTemplateArgumentList TemplateArgLists; 3335 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 3336 3337 // Instantiate the first declaration of the variable template: for a partial 3338 // specialization of a static data member template, the first declaration may 3339 // or may not be the declaration in the class; if it's in the class, we want 3340 // to instantiate a member in the class (a declaration), and if it's outside, 3341 // we want to instantiate a definition. 3342 FromVar = FromVar->getFirstDecl(); 3343 3344 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 3345 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 3346 MultiLevelList); 3347 3348 // TODO: Set LateAttrs and StartingScope ... 3349 3350 return cast_or_null<VarTemplateSpecializationDecl>( 3351 Instantiator.VisitVarTemplateSpecializationDecl( 3352 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted)); 3353 } 3354 3355 /// \brief Instantiates a variable template specialization by completing it 3356 /// with appropriate type information and initializer. 3357 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 3358 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 3359 const MultiLevelTemplateArgumentList &TemplateArgs) { 3360 3361 // Do substitution on the type of the declaration 3362 TypeSourceInfo *DI = 3363 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 3364 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 3365 if (!DI) 3366 return 0; 3367 3368 // Update the type of this variable template specialization. 3369 VarSpec->setType(DI->getType()); 3370 3371 // Instantiate the initializer. 3372 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 3373 3374 return VarSpec; 3375 } 3376 3377 /// BuildVariableInstantiation - Used after a new variable has been created. 3378 /// Sets basic variable data and decides whether to postpone the 3379 /// variable instantiation. 3380 void Sema::BuildVariableInstantiation( 3381 VarDecl *NewVar, VarDecl *OldVar, 3382 const MultiLevelTemplateArgumentList &TemplateArgs, 3383 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 3384 LocalInstantiationScope *StartingScope, 3385 bool InstantiatingVarTemplate) { 3386 3387 // If we are instantiating a local extern declaration, the 3388 // instantiation belongs lexically to the containing function. 3389 // If we are instantiating a static data member defined 3390 // out-of-line, the instantiation will have the same lexical 3391 // context (which will be a namespace scope) as the template. 3392 if (OldVar->isLocalExternDecl()) { 3393 NewVar->setLocalExternDecl(); 3394 NewVar->setLexicalDeclContext(Owner); 3395 } else if (OldVar->isOutOfLine()) 3396 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 3397 NewVar->setTSCSpec(OldVar->getTSCSpec()); 3398 NewVar->setInitStyle(OldVar->getInitStyle()); 3399 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 3400 NewVar->setConstexpr(OldVar->isConstexpr()); 3401 NewVar->setInitCapture(OldVar->isInitCapture()); 3402 NewVar->setPreviousDeclInSameBlockScope( 3403 OldVar->isPreviousDeclInSameBlockScope()); 3404 NewVar->setAccess(OldVar->getAccess()); 3405 3406 if (!OldVar->isStaticDataMember()) { 3407 if (OldVar->isUsed(false)) 3408 NewVar->setIsUsed(); 3409 NewVar->setReferenced(OldVar->isReferenced()); 3410 } 3411 3412 // See if the old variable had a type-specifier that defined an anonymous tag. 3413 // If it did, mark the new variable as being the declarator for the new 3414 // anonymous tag. 3415 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) { 3416 TagDecl *OldTag = OldTagType->getDecl(); 3417 if (OldTag->getDeclaratorForAnonDecl() == OldVar) { 3418 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl(); 3419 assert(!NewTag->hasNameForLinkage() && 3420 !NewTag->hasDeclaratorForAnonDecl()); 3421 NewTag->setDeclaratorForAnonDecl(NewVar); 3422 } 3423 } 3424 3425 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 3426 3427 if (NewVar->hasAttrs()) 3428 CheckAlignasUnderalignment(NewVar); 3429 3430 LookupResult Previous( 3431 *this, NewVar->getDeclName(), NewVar->getLocation(), 3432 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 3433 : Sema::LookupOrdinaryName, 3434 Sema::ForRedeclaration); 3435 3436 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 3437 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 3438 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 3439 // We have a previous declaration. Use that one, so we merge with the 3440 // right type. 3441 if (NamedDecl *NewPrev = FindInstantiatedDecl( 3442 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 3443 Previous.addDecl(NewPrev); 3444 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 3445 OldVar->hasLinkage()) 3446 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 3447 CheckVariableDeclaration(NewVar, Previous); 3448 3449 if (!InstantiatingVarTemplate) { 3450 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 3451 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 3452 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 3453 } 3454 3455 if (!OldVar->isOutOfLine()) { 3456 if (NewVar->getDeclContext()->isFunctionOrMethod()) 3457 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 3458 } 3459 3460 // Link instantiations of static data members back to the template from 3461 // which they were instantiated. 3462 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate) 3463 NewVar->setInstantiationOfStaticDataMember(OldVar, 3464 TSK_ImplicitInstantiation); 3465 3466 // Forward the mangling number from the template to the instantiated decl. 3467 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 3468 3469 // Delay instantiation of the initializer for variable templates until a 3470 // definition of the variable is needed. 3471 if (!isa<VarTemplateSpecializationDecl>(NewVar) && !InstantiatingVarTemplate) 3472 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 3473 3474 // Diagnose unused local variables with dependent types, where the diagnostic 3475 // will have been deferred. 3476 if (!NewVar->isInvalidDecl() && 3477 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() && 3478 OldVar->getType()->isDependentType()) 3479 DiagnoseUnusedDecl(NewVar); 3480 } 3481 3482 /// \brief Instantiate the initializer of a variable. 3483 void Sema::InstantiateVariableInitializer( 3484 VarDecl *Var, VarDecl *OldVar, 3485 const MultiLevelTemplateArgumentList &TemplateArgs) { 3486 3487 if (Var->getAnyInitializer()) 3488 // We already have an initializer in the class. 3489 return; 3490 3491 if (OldVar->getInit()) { 3492 if (Var->isStaticDataMember() && !OldVar->isOutOfLine()) 3493 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar); 3494 else 3495 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar); 3496 3497 // Instantiate the initializer. 3498 ExprResult Init = 3499 SubstInitializer(OldVar->getInit(), TemplateArgs, 3500 OldVar->getInitStyle() == VarDecl::CallInit); 3501 if (!Init.isInvalid()) { 3502 bool TypeMayContainAuto = true; 3503 if (Init.get()) { 3504 bool DirectInit = OldVar->isDirectInit(); 3505 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto); 3506 } else 3507 ActOnUninitializedDecl(Var, TypeMayContainAuto); 3508 } else { 3509 // FIXME: Not too happy about invalidating the declaration 3510 // because of a bogus initializer. 3511 Var->setInvalidDecl(); 3512 } 3513 3514 PopExpressionEvaluationContext(); 3515 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) && 3516 !Var->isCXXForRangeDecl()) 3517 ActOnUninitializedDecl(Var, false); 3518 } 3519 3520 /// \brief Instantiate the definition of the given variable from its 3521 /// template. 3522 /// 3523 /// \param PointOfInstantiation the point at which the instantiation was 3524 /// required. Note that this is not precisely a "point of instantiation" 3525 /// for the function, but it's close. 3526 /// 3527 /// \param Var the already-instantiated declaration of a static member 3528 /// variable of a class template specialization. 3529 /// 3530 /// \param Recursive if true, recursively instantiates any functions that 3531 /// are required by this instantiation. 3532 /// 3533 /// \param DefinitionRequired if true, then we are performing an explicit 3534 /// instantiation where an out-of-line definition of the member variable 3535 /// is required. Complain if there is no such definition. 3536 void Sema::InstantiateStaticDataMemberDefinition( 3537 SourceLocation PointOfInstantiation, 3538 VarDecl *Var, 3539 bool Recursive, 3540 bool DefinitionRequired) { 3541 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive, 3542 DefinitionRequired); 3543 } 3544 3545 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 3546 VarDecl *Var, bool Recursive, 3547 bool DefinitionRequired) { 3548 if (Var->isInvalidDecl()) 3549 return; 3550 3551 VarTemplateSpecializationDecl *VarSpec = 3552 dyn_cast<VarTemplateSpecializationDecl>(Var); 3553 VarDecl *PatternDecl = 0, *Def = 0; 3554 MultiLevelTemplateArgumentList TemplateArgs = 3555 getTemplateInstantiationArgs(Var); 3556 3557 if (VarSpec) { 3558 // If this is a variable template specialization, make sure that it is 3559 // non-dependent, then find its instantiation pattern. 3560 bool InstantiationDependent = false; 3561 assert(!TemplateSpecializationType::anyDependentTemplateArguments( 3562 VarSpec->getTemplateArgsInfo(), InstantiationDependent) && 3563 "Only instantiate variable template specializations that are " 3564 "not type-dependent"); 3565 (void)InstantiationDependent; 3566 3567 // Find the variable initialization that we'll be substituting. If the 3568 // pattern was instantiated from a member template, look back further to 3569 // find the real pattern. 3570 assert(VarSpec->getSpecializedTemplate() && 3571 "Specialization without specialized template?"); 3572 llvm::PointerUnion<VarTemplateDecl *, 3573 VarTemplatePartialSpecializationDecl *> PatternPtr = 3574 VarSpec->getSpecializedTemplateOrPartial(); 3575 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) { 3576 VarTemplatePartialSpecializationDecl *Tmpl = 3577 PatternPtr.get<VarTemplatePartialSpecializationDecl *>(); 3578 while (VarTemplatePartialSpecializationDecl *From = 3579 Tmpl->getInstantiatedFromMember()) { 3580 if (Tmpl->isMemberSpecialization()) 3581 break; 3582 3583 Tmpl = From; 3584 } 3585 PatternDecl = Tmpl; 3586 } else { 3587 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>(); 3588 while (VarTemplateDecl *From = 3589 Tmpl->getInstantiatedFromMemberTemplate()) { 3590 if (Tmpl->isMemberSpecialization()) 3591 break; 3592 3593 Tmpl = From; 3594 } 3595 PatternDecl = Tmpl->getTemplatedDecl(); 3596 } 3597 3598 // If this is a static data member template, there might be an 3599 // uninstantiated initializer on the declaration. If so, instantiate 3600 // it now. 3601 if (PatternDecl->isStaticDataMember() && 3602 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 3603 !Var->hasInit()) { 3604 // FIXME: Factor out the duplicated instantiation context setup/tear down 3605 // code here. 3606 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 3607 if (Inst.isInvalid()) 3608 return; 3609 3610 // If we're performing recursive template instantiation, create our own 3611 // queue of pending implicit instantiations that we will instantiate 3612 // later, while we're still within our own instantiation context. 3613 SmallVector<VTableUse, 16> SavedVTableUses; 3614 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 3615 if (Recursive) { 3616 VTableUses.swap(SavedVTableUses); 3617 PendingInstantiations.swap(SavedPendingInstantiations); 3618 } 3619 3620 LocalInstantiationScope Local(*this); 3621 3622 // Enter the scope of this instantiation. We don't use 3623 // PushDeclContext because we don't have a scope. 3624 ContextRAII PreviousContext(*this, Var->getDeclContext()); 3625 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 3626 PreviousContext.pop(); 3627 3628 // FIXME: Need to inform the ASTConsumer that we instantiated the 3629 // initializer? 3630 3631 // This variable may have local implicit instantiations that need to be 3632 // instantiated within this scope. 3633 PerformPendingInstantiations(/*LocalOnly=*/true); 3634 3635 Local.Exit(); 3636 3637 if (Recursive) { 3638 // Define any newly required vtables. 3639 DefineUsedVTables(); 3640 3641 // Instantiate any pending implicit instantiations found during the 3642 // instantiation of this template. 3643 PerformPendingInstantiations(); 3644 3645 // Restore the set of pending vtables. 3646 assert(VTableUses.empty() && 3647 "VTableUses should be empty before it is discarded."); 3648 VTableUses.swap(SavedVTableUses); 3649 3650 // Restore the set of pending implicit instantiations. 3651 assert(PendingInstantiations.empty() && 3652 "PendingInstantiations should be empty before it is discarded."); 3653 PendingInstantiations.swap(SavedPendingInstantiations); 3654 } 3655 } 3656 3657 // Find actual definition 3658 Def = PatternDecl->getDefinition(getASTContext()); 3659 } else { 3660 // If this is a static data member, find its out-of-line definition. 3661 assert(Var->isStaticDataMember() && "not a static data member?"); 3662 PatternDecl = Var->getInstantiatedFromStaticDataMember(); 3663 3664 assert(PatternDecl && "data member was not instantiated from a template?"); 3665 assert(PatternDecl->isStaticDataMember() && "not a static data member?"); 3666 Def = PatternDecl->getOutOfLineDefinition(); 3667 } 3668 3669 // If we don't have a definition of the variable template, we won't perform 3670 // any instantiation. Rather, we rely on the user to instantiate this 3671 // definition (or provide a specialization for it) in another translation 3672 // unit. 3673 if (!Def) { 3674 if (DefinitionRequired) { 3675 if (VarSpec) 3676 Diag(PointOfInstantiation, 3677 diag::err_explicit_instantiation_undefined_var_template) << Var; 3678 else 3679 Diag(PointOfInstantiation, 3680 diag::err_explicit_instantiation_undefined_member) 3681 << 2 << Var->getDeclName() << Var->getDeclContext(); 3682 Diag(PatternDecl->getLocation(), 3683 diag::note_explicit_instantiation_here); 3684 if (VarSpec) 3685 Var->setInvalidDecl(); 3686 } else if (Var->getTemplateSpecializationKind() 3687 == TSK_ExplicitInstantiationDefinition) { 3688 PendingInstantiations.push_back( 3689 std::make_pair(Var, PointOfInstantiation)); 3690 } 3691 3692 return; 3693 } 3694 3695 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 3696 3697 // Never instantiate an explicit specialization. 3698 if (TSK == TSK_ExplicitSpecialization) 3699 return; 3700 3701 // C++11 [temp.explicit]p10: 3702 // Except for inline functions, [...] explicit instantiation declarations 3703 // have the effect of suppressing the implicit instantiation of the entity 3704 // to which they refer. 3705 if (TSK == TSK_ExplicitInstantiationDeclaration) 3706 return; 3707 3708 // Make sure to pass the instantiated variable to the consumer at the end. 3709 struct PassToConsumerRAII { 3710 ASTConsumer &Consumer; 3711 VarDecl *Var; 3712 3713 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 3714 : Consumer(Consumer), Var(Var) { } 3715 3716 ~PassToConsumerRAII() { 3717 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 3718 } 3719 } PassToConsumerRAII(Consumer, Var); 3720 3721 // If we already have a definition, we're done. 3722 if (VarDecl *Def = Var->getDefinition()) { 3723 // We may be explicitly instantiating something we've already implicitly 3724 // instantiated. 3725 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 3726 PointOfInstantiation); 3727 return; 3728 } 3729 3730 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 3731 if (Inst.isInvalid()) 3732 return; 3733 3734 // If we're performing recursive template instantiation, create our own 3735 // queue of pending implicit instantiations that we will instantiate later, 3736 // while we're still within our own instantiation context. 3737 SmallVector<VTableUse, 16> SavedVTableUses; 3738 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 3739 SavePendingLocalImplicitInstantiationsRAII 3740 SavedPendingLocalImplicitInstantiations(*this); 3741 if (Recursive) { 3742 VTableUses.swap(SavedVTableUses); 3743 PendingInstantiations.swap(SavedPendingInstantiations); 3744 } 3745 3746 // Enter the scope of this instantiation. We don't use 3747 // PushDeclContext because we don't have a scope. 3748 ContextRAII PreviousContext(*this, Var->getDeclContext()); 3749 LocalInstantiationScope Local(*this); 3750 3751 VarDecl *OldVar = Var; 3752 if (!VarSpec) 3753 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 3754 TemplateArgs)); 3755 else if (Var->isStaticDataMember() && 3756 Var->getLexicalDeclContext()->isRecord()) { 3757 // We need to instantiate the definition of a static data member template, 3758 // and all we have is the in-class declaration of it. Instantiate a separate 3759 // declaration of the definition. 3760 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 3761 TemplateArgs); 3762 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 3763 VarSpec->getSpecializedTemplate(), Def, 0, 3764 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray())); 3765 if (Var) { 3766 llvm::PointerUnion<VarTemplateDecl *, 3767 VarTemplatePartialSpecializationDecl *> PatternPtr = 3768 VarSpec->getSpecializedTemplateOrPartial(); 3769 if (VarTemplatePartialSpecializationDecl *Partial = 3770 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 3771 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 3772 Partial, &VarSpec->getTemplateInstantiationArgs()); 3773 3774 // Merge the definition with the declaration. 3775 LookupResult R(*this, Var->getDeclName(), Var->getLocation(), 3776 LookupOrdinaryName, ForRedeclaration); 3777 R.addDecl(OldVar); 3778 MergeVarDecl(Var, R); 3779 3780 // Attach the initializer. 3781 InstantiateVariableInitializer(Var, Def, TemplateArgs); 3782 } 3783 } else 3784 // Complete the existing variable's definition with an appropriately 3785 // substituted type and initializer. 3786 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 3787 3788 PreviousContext.pop(); 3789 3790 if (Var) { 3791 PassToConsumerRAII.Var = Var; 3792 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 3793 OldVar->getPointOfInstantiation()); 3794 } 3795 3796 // This variable may have local implicit instantiations that need to be 3797 // instantiated within this scope. 3798 PerformPendingInstantiations(/*LocalOnly=*/true); 3799 3800 Local.Exit(); 3801 3802 if (Recursive) { 3803 // Define any newly required vtables. 3804 DefineUsedVTables(); 3805 3806 // Instantiate any pending implicit instantiations found during the 3807 // instantiation of this template. 3808 PerformPendingInstantiations(); 3809 3810 // Restore the set of pending vtables. 3811 assert(VTableUses.empty() && 3812 "VTableUses should be empty before it is discarded."); 3813 VTableUses.swap(SavedVTableUses); 3814 3815 // Restore the set of pending implicit instantiations. 3816 assert(PendingInstantiations.empty() && 3817 "PendingInstantiations should be empty before it is discarded."); 3818 PendingInstantiations.swap(SavedPendingInstantiations); 3819 } 3820 } 3821 3822 void 3823 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 3824 const CXXConstructorDecl *Tmpl, 3825 const MultiLevelTemplateArgumentList &TemplateArgs) { 3826 3827 SmallVector<CXXCtorInitializer*, 4> NewInits; 3828 bool AnyErrors = Tmpl->isInvalidDecl(); 3829 3830 // Instantiate all the initializers. 3831 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 3832 InitsEnd = Tmpl->init_end(); 3833 Inits != InitsEnd; ++Inits) { 3834 CXXCtorInitializer *Init = *Inits; 3835 3836 // Only instantiate written initializers, let Sema re-construct implicit 3837 // ones. 3838 if (!Init->isWritten()) 3839 continue; 3840 3841 SourceLocation EllipsisLoc; 3842 3843 if (Init->isPackExpansion()) { 3844 // This is a pack expansion. We should expand it now. 3845 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 3846 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 3847 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 3848 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 3849 bool ShouldExpand = false; 3850 bool RetainExpansion = false; 3851 Optional<unsigned> NumExpansions; 3852 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 3853 BaseTL.getSourceRange(), 3854 Unexpanded, 3855 TemplateArgs, ShouldExpand, 3856 RetainExpansion, 3857 NumExpansions)) { 3858 AnyErrors = true; 3859 New->setInvalidDecl(); 3860 continue; 3861 } 3862 assert(ShouldExpand && "Partial instantiation of base initializer?"); 3863 3864 // Loop over all of the arguments in the argument pack(s), 3865 for (unsigned I = 0; I != *NumExpansions; ++I) { 3866 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 3867 3868 // Instantiate the initializer. 3869 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 3870 /*CXXDirectInit=*/true); 3871 if (TempInit.isInvalid()) { 3872 AnyErrors = true; 3873 break; 3874 } 3875 3876 // Instantiate the base type. 3877 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 3878 TemplateArgs, 3879 Init->getSourceLocation(), 3880 New->getDeclName()); 3881 if (!BaseTInfo) { 3882 AnyErrors = true; 3883 break; 3884 } 3885 3886 // Build the initializer. 3887 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 3888 BaseTInfo, TempInit.take(), 3889 New->getParent(), 3890 SourceLocation()); 3891 if (NewInit.isInvalid()) { 3892 AnyErrors = true; 3893 break; 3894 } 3895 3896 NewInits.push_back(NewInit.get()); 3897 } 3898 3899 continue; 3900 } 3901 3902 // Instantiate the initializer. 3903 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 3904 /*CXXDirectInit=*/true); 3905 if (TempInit.isInvalid()) { 3906 AnyErrors = true; 3907 continue; 3908 } 3909 3910 MemInitResult NewInit; 3911 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 3912 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 3913 TemplateArgs, 3914 Init->getSourceLocation(), 3915 New->getDeclName()); 3916 if (!TInfo) { 3917 AnyErrors = true; 3918 New->setInvalidDecl(); 3919 continue; 3920 } 3921 3922 if (Init->isBaseInitializer()) 3923 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(), 3924 New->getParent(), EllipsisLoc); 3925 else 3926 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(), 3927 cast<CXXRecordDecl>(CurContext->getParent())); 3928 } else if (Init->isMemberInitializer()) { 3929 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 3930 Init->getMemberLocation(), 3931 Init->getMember(), 3932 TemplateArgs)); 3933 if (!Member) { 3934 AnyErrors = true; 3935 New->setInvalidDecl(); 3936 continue; 3937 } 3938 3939 NewInit = BuildMemberInitializer(Member, TempInit.take(), 3940 Init->getSourceLocation()); 3941 } else if (Init->isIndirectMemberInitializer()) { 3942 IndirectFieldDecl *IndirectMember = 3943 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 3944 Init->getMemberLocation(), 3945 Init->getIndirectMember(), TemplateArgs)); 3946 3947 if (!IndirectMember) { 3948 AnyErrors = true; 3949 New->setInvalidDecl(); 3950 continue; 3951 } 3952 3953 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(), 3954 Init->getSourceLocation()); 3955 } 3956 3957 if (NewInit.isInvalid()) { 3958 AnyErrors = true; 3959 New->setInvalidDecl(); 3960 } else { 3961 NewInits.push_back(NewInit.get()); 3962 } 3963 } 3964 3965 // Assign all the initializers to the new constructor. 3966 ActOnMemInitializers(New, 3967 /*FIXME: ColonLoc */ 3968 SourceLocation(), 3969 NewInits, 3970 AnyErrors); 3971 } 3972 3973 // TODO: this could be templated if the various decl types used the 3974 // same method name. 3975 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 3976 ClassTemplateDecl *Instance) { 3977 Pattern = Pattern->getCanonicalDecl(); 3978 3979 do { 3980 Instance = Instance->getCanonicalDecl(); 3981 if (Pattern == Instance) return true; 3982 Instance = Instance->getInstantiatedFromMemberTemplate(); 3983 } while (Instance); 3984 3985 return false; 3986 } 3987 3988 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 3989 FunctionTemplateDecl *Instance) { 3990 Pattern = Pattern->getCanonicalDecl(); 3991 3992 do { 3993 Instance = Instance->getCanonicalDecl(); 3994 if (Pattern == Instance) return true; 3995 Instance = Instance->getInstantiatedFromMemberTemplate(); 3996 } while (Instance); 3997 3998 return false; 3999 } 4000 4001 static bool 4002 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 4003 ClassTemplatePartialSpecializationDecl *Instance) { 4004 Pattern 4005 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 4006 do { 4007 Instance = cast<ClassTemplatePartialSpecializationDecl>( 4008 Instance->getCanonicalDecl()); 4009 if (Pattern == Instance) 4010 return true; 4011 Instance = Instance->getInstantiatedFromMember(); 4012 } while (Instance); 4013 4014 return false; 4015 } 4016 4017 static bool isInstantiationOf(CXXRecordDecl *Pattern, 4018 CXXRecordDecl *Instance) { 4019 Pattern = Pattern->getCanonicalDecl(); 4020 4021 do { 4022 Instance = Instance->getCanonicalDecl(); 4023 if (Pattern == Instance) return true; 4024 Instance = Instance->getInstantiatedFromMemberClass(); 4025 } while (Instance); 4026 4027 return false; 4028 } 4029 4030 static bool isInstantiationOf(FunctionDecl *Pattern, 4031 FunctionDecl *Instance) { 4032 Pattern = Pattern->getCanonicalDecl(); 4033 4034 do { 4035 Instance = Instance->getCanonicalDecl(); 4036 if (Pattern == Instance) return true; 4037 Instance = Instance->getInstantiatedFromMemberFunction(); 4038 } while (Instance); 4039 4040 return false; 4041 } 4042 4043 static bool isInstantiationOf(EnumDecl *Pattern, 4044 EnumDecl *Instance) { 4045 Pattern = Pattern->getCanonicalDecl(); 4046 4047 do { 4048 Instance = Instance->getCanonicalDecl(); 4049 if (Pattern == Instance) return true; 4050 Instance = Instance->getInstantiatedFromMemberEnum(); 4051 } while (Instance); 4052 4053 return false; 4054 } 4055 4056 static bool isInstantiationOf(UsingShadowDecl *Pattern, 4057 UsingShadowDecl *Instance, 4058 ASTContext &C) { 4059 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 4060 } 4061 4062 static bool isInstantiationOf(UsingDecl *Pattern, 4063 UsingDecl *Instance, 4064 ASTContext &C) { 4065 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 4066 } 4067 4068 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 4069 UsingDecl *Instance, 4070 ASTContext &C) { 4071 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 4072 } 4073 4074 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 4075 UsingDecl *Instance, 4076 ASTContext &C) { 4077 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 4078 } 4079 4080 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 4081 VarDecl *Instance) { 4082 assert(Instance->isStaticDataMember()); 4083 4084 Pattern = Pattern->getCanonicalDecl(); 4085 4086 do { 4087 Instance = Instance->getCanonicalDecl(); 4088 if (Pattern == Instance) return true; 4089 Instance = Instance->getInstantiatedFromStaticDataMember(); 4090 } while (Instance); 4091 4092 return false; 4093 } 4094 4095 // Other is the prospective instantiation 4096 // D is the prospective pattern 4097 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 4098 if (D->getKind() != Other->getKind()) { 4099 if (UnresolvedUsingTypenameDecl *UUD 4100 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 4101 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 4102 return isInstantiationOf(UUD, UD, Ctx); 4103 } 4104 } 4105 4106 if (UnresolvedUsingValueDecl *UUD 4107 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 4108 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 4109 return isInstantiationOf(UUD, UD, Ctx); 4110 } 4111 } 4112 4113 return false; 4114 } 4115 4116 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 4117 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 4118 4119 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 4120 return isInstantiationOf(cast<FunctionDecl>(D), Function); 4121 4122 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 4123 return isInstantiationOf(cast<EnumDecl>(D), Enum); 4124 4125 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 4126 if (Var->isStaticDataMember()) 4127 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 4128 4129 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 4130 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 4131 4132 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 4133 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 4134 4135 if (ClassTemplatePartialSpecializationDecl *PartialSpec 4136 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 4137 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 4138 PartialSpec); 4139 4140 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 4141 if (!Field->getDeclName()) { 4142 // This is an unnamed field. 4143 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 4144 cast<FieldDecl>(D); 4145 } 4146 } 4147 4148 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 4149 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 4150 4151 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 4152 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 4153 4154 return D->getDeclName() && isa<NamedDecl>(Other) && 4155 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 4156 } 4157 4158 template<typename ForwardIterator> 4159 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 4160 NamedDecl *D, 4161 ForwardIterator first, 4162 ForwardIterator last) { 4163 for (; first != last; ++first) 4164 if (isInstantiationOf(Ctx, D, *first)) 4165 return cast<NamedDecl>(*first); 4166 4167 return 0; 4168 } 4169 4170 /// \brief Finds the instantiation of the given declaration context 4171 /// within the current instantiation. 4172 /// 4173 /// \returns NULL if there was an error 4174 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 4175 const MultiLevelTemplateArgumentList &TemplateArgs) { 4176 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 4177 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 4178 return cast_or_null<DeclContext>(ID); 4179 } else return DC; 4180 } 4181 4182 /// \brief Find the instantiation of the given declaration within the 4183 /// current instantiation. 4184 /// 4185 /// This routine is intended to be used when \p D is a declaration 4186 /// referenced from within a template, that needs to mapped into the 4187 /// corresponding declaration within an instantiation. For example, 4188 /// given: 4189 /// 4190 /// \code 4191 /// template<typename T> 4192 /// struct X { 4193 /// enum Kind { 4194 /// KnownValue = sizeof(T) 4195 /// }; 4196 /// 4197 /// bool getKind() const { return KnownValue; } 4198 /// }; 4199 /// 4200 /// template struct X<int>; 4201 /// \endcode 4202 /// 4203 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the 4204 /// \p EnumConstantDecl for \p KnownValue (which refers to 4205 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation 4206 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs 4207 /// this mapping from within the instantiation of <tt>X<int></tt>. 4208 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 4209 const MultiLevelTemplateArgumentList &TemplateArgs) { 4210 DeclContext *ParentDC = D->getDeclContext(); 4211 // FIXME: Parmeters of pointer to functions (y below) that are themselves 4212 // parameters (p below) can have their ParentDC set to the translation-unit 4213 // - thus we can not consistently check if the ParentDC of such a parameter 4214 // is Dependent or/and a FunctionOrMethod. 4215 // For e.g. this code, during Template argument deduction tries to 4216 // find an instantiated decl for (T y) when the ParentDC for y is 4217 // the translation unit. 4218 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 4219 // float baz(float(*)()) { return 0.0; } 4220 // Foo(baz); 4221 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 4222 // it gets here, always has a FunctionOrMethod as its ParentDC?? 4223 // For now: 4224 // - as long as we have a ParmVarDecl whose parent is non-dependent and 4225 // whose type is not instantiation dependent, do nothing to the decl 4226 // - otherwise find its instantiated decl. 4227 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() && 4228 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 4229 return D; 4230 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 4231 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 4232 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) || 4233 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 4234 // D is a local of some kind. Look into the map of local 4235 // declarations to their instantiations. 4236 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 4237 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found 4238 = CurrentInstantiationScope->findInstantiationOf(D); 4239 4240 if (Found) { 4241 if (Decl *FD = Found->dyn_cast<Decl *>()) 4242 return cast<NamedDecl>(FD); 4243 4244 int PackIdx = ArgumentPackSubstitutionIndex; 4245 assert(PackIdx != -1 && "found declaration pack but not pack expanding"); 4246 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 4247 } 4248 4249 // If we're performing a partial substitution during template argument 4250 // deduction, we may not have values for template parameters yet. They 4251 // just map to themselves. 4252 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 4253 isa<TemplateTemplateParmDecl>(D)) 4254 return D; 4255 4256 if (D->isInvalidDecl()) 4257 return 0; 4258 4259 // If we didn't find the decl, then we must have a label decl that hasn't 4260 // been found yet. Lazily instantiate it and return it now. 4261 assert(isa<LabelDecl>(D)); 4262 4263 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 4264 assert(Inst && "Failed to instantiate label??"); 4265 4266 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 4267 return cast<LabelDecl>(Inst); 4268 } 4269 4270 // For variable template specializations, update those that are still 4271 // type-dependent. 4272 if (VarTemplateSpecializationDecl *VarSpec = 4273 dyn_cast<VarTemplateSpecializationDecl>(D)) { 4274 bool InstantiationDependent = false; 4275 const TemplateArgumentListInfo &VarTemplateArgs = 4276 VarSpec->getTemplateArgsInfo(); 4277 if (TemplateSpecializationType::anyDependentTemplateArguments( 4278 VarTemplateArgs, InstantiationDependent)) 4279 D = cast<NamedDecl>( 4280 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs)); 4281 return D; 4282 } 4283 4284 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 4285 if (!Record->isDependentContext()) 4286 return D; 4287 4288 // Determine whether this record is the "templated" declaration describing 4289 // a class template or class template partial specialization. 4290 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 4291 if (ClassTemplate) 4292 ClassTemplate = ClassTemplate->getCanonicalDecl(); 4293 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 4294 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 4295 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 4296 4297 // Walk the current context to find either the record or an instantiation of 4298 // it. 4299 DeclContext *DC = CurContext; 4300 while (!DC->isFileContext()) { 4301 // If we're performing substitution while we're inside the template 4302 // definition, we'll find our own context. We're done. 4303 if (DC->Equals(Record)) 4304 return Record; 4305 4306 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 4307 // Check whether we're in the process of instantiating a class template 4308 // specialization of the template we're mapping. 4309 if (ClassTemplateSpecializationDecl *InstSpec 4310 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 4311 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 4312 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 4313 return InstRecord; 4314 } 4315 4316 // Check whether we're in the process of instantiating a member class. 4317 if (isInstantiationOf(Record, InstRecord)) 4318 return InstRecord; 4319 } 4320 4321 // Move to the outer template scope. 4322 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 4323 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 4324 DC = FD->getLexicalDeclContext(); 4325 continue; 4326 } 4327 } 4328 4329 DC = DC->getParent(); 4330 } 4331 4332 // Fall through to deal with other dependent record types (e.g., 4333 // anonymous unions in class templates). 4334 } 4335 4336 if (!ParentDC->isDependentContext()) 4337 return D; 4338 4339 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 4340 if (!ParentDC) 4341 return 0; 4342 4343 if (ParentDC != D->getDeclContext()) { 4344 // We performed some kind of instantiation in the parent context, 4345 // so now we need to look into the instantiated parent context to 4346 // find the instantiation of the declaration D. 4347 4348 // If our context used to be dependent, we may need to instantiate 4349 // it before performing lookup into that context. 4350 bool IsBeingInstantiated = false; 4351 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 4352 if (!Spec->isDependentContext()) { 4353 QualType T = Context.getTypeDeclType(Spec); 4354 const RecordType *Tag = T->getAs<RecordType>(); 4355 assert(Tag && "type of non-dependent record is not a RecordType"); 4356 if (Tag->isBeingDefined()) 4357 IsBeingInstantiated = true; 4358 if (!Tag->isBeingDefined() && 4359 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 4360 return 0; 4361 4362 ParentDC = Tag->getDecl(); 4363 } 4364 } 4365 4366 NamedDecl *Result = 0; 4367 if (D->getDeclName()) { 4368 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 4369 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 4370 } else { 4371 // Since we don't have a name for the entity we're looking for, 4372 // our only option is to walk through all of the declarations to 4373 // find that name. This will occur in a few cases: 4374 // 4375 // - anonymous struct/union within a template 4376 // - unnamed class/struct/union/enum within a template 4377 // 4378 // FIXME: Find a better way to find these instantiations! 4379 Result = findInstantiationOf(Context, D, 4380 ParentDC->decls_begin(), 4381 ParentDC->decls_end()); 4382 } 4383 4384 if (!Result) { 4385 if (isa<UsingShadowDecl>(D)) { 4386 // UsingShadowDecls can instantiate to nothing because of using hiding. 4387 } else if (Diags.hasErrorOccurred()) { 4388 // We've already complained about something, so most likely this 4389 // declaration failed to instantiate. There's no point in complaining 4390 // further, since this is normal in invalid code. 4391 } else if (IsBeingInstantiated) { 4392 // The class in which this member exists is currently being 4393 // instantiated, and we haven't gotten around to instantiating this 4394 // member yet. This can happen when the code uses forward declarations 4395 // of member classes, and introduces ordering dependencies via 4396 // template instantiation. 4397 Diag(Loc, diag::err_member_not_yet_instantiated) 4398 << D->getDeclName() 4399 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 4400 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 4401 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 4402 // This enumeration constant was found when the template was defined, 4403 // but can't be found in the instantiation. This can happen if an 4404 // unscoped enumeration member is explicitly specialized. 4405 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 4406 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 4407 TemplateArgs)); 4408 assert(Spec->getTemplateSpecializationKind() == 4409 TSK_ExplicitSpecialization); 4410 Diag(Loc, diag::err_enumerator_does_not_exist) 4411 << D->getDeclName() 4412 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 4413 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 4414 << Context.getTypeDeclType(Spec); 4415 } else { 4416 // We should have found something, but didn't. 4417 llvm_unreachable("Unable to find instantiation of declaration!"); 4418 } 4419 } 4420 4421 D = Result; 4422 } 4423 4424 return D; 4425 } 4426 4427 /// \brief Performs template instantiation for all implicit template 4428 /// instantiations we have seen until this point. 4429 void Sema::PerformPendingInstantiations(bool LocalOnly) { 4430 // Load pending instantiations from the external source. 4431 if (!LocalOnly && ExternalSource) { 4432 SmallVector<PendingImplicitInstantiation, 4> Pending; 4433 ExternalSource->ReadPendingInstantiations(Pending); 4434 PendingInstantiations.insert(PendingInstantiations.begin(), 4435 Pending.begin(), Pending.end()); 4436 } 4437 4438 while (!PendingLocalImplicitInstantiations.empty() || 4439 (!LocalOnly && !PendingInstantiations.empty())) { 4440 PendingImplicitInstantiation Inst; 4441 4442 if (PendingLocalImplicitInstantiations.empty()) { 4443 Inst = PendingInstantiations.front(); 4444 PendingInstantiations.pop_front(); 4445 } else { 4446 Inst = PendingLocalImplicitInstantiations.front(); 4447 PendingLocalImplicitInstantiations.pop_front(); 4448 } 4449 4450 // Instantiate function definitions 4451 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 4452 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(), 4453 "instantiating function definition"); 4454 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 4455 TSK_ExplicitInstantiationDefinition; 4456 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true, 4457 DefinitionRequired); 4458 continue; 4459 } 4460 4461 // Instantiate variable definitions 4462 VarDecl *Var = cast<VarDecl>(Inst.first); 4463 4464 assert((Var->isStaticDataMember() || 4465 isa<VarTemplateSpecializationDecl>(Var)) && 4466 "Not a static data member, nor a variable template" 4467 " specialization?"); 4468 4469 // Don't try to instantiate declarations if the most recent redeclaration 4470 // is invalid. 4471 if (Var->getMostRecentDecl()->isInvalidDecl()) 4472 continue; 4473 4474 // Check if the most recent declaration has changed the specialization kind 4475 // and removed the need for implicit instantiation. 4476 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) { 4477 case TSK_Undeclared: 4478 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 4479 case TSK_ExplicitInstantiationDeclaration: 4480 case TSK_ExplicitSpecialization: 4481 continue; // No longer need to instantiate this type. 4482 case TSK_ExplicitInstantiationDefinition: 4483 // We only need an instantiation if the pending instantiation *is* the 4484 // explicit instantiation. 4485 if (Var != Var->getMostRecentDecl()) continue; 4486 case TSK_ImplicitInstantiation: 4487 break; 4488 } 4489 4490 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(), 4491 "instantiating variable definition"); 4492 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 4493 TSK_ExplicitInstantiationDefinition; 4494 4495 // Instantiate static data member definitions or variable template 4496 // specializations. 4497 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 4498 DefinitionRequired); 4499 } 4500 } 4501 4502 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 4503 const MultiLevelTemplateArgumentList &TemplateArgs) { 4504 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(), 4505 E = Pattern->ddiag_end(); I != E; ++I) { 4506 DependentDiagnostic *DD = *I; 4507 4508 switch (DD->getKind()) { 4509 case DependentDiagnostic::Access: 4510 HandleDependentAccessCheck(*DD, TemplateArgs); 4511 break; 4512 } 4513 } 4514 } 4515