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