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