1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/ 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 //===----------------------------------------------------------------------===/ 7 // 8 // This file implements C++ template instantiation for declarations. 9 // 10 //===----------------------------------------------------------------------===/ 11 #include "clang/Sema/SemaInternal.h" 12 #include "clang/AST/ASTConsumer.h" 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/ASTMutationListener.h" 15 #include "clang/AST/DeclTemplate.h" 16 #include "clang/AST/DeclVisitor.h" 17 #include "clang/AST/DependentDiagnostic.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/PrettyDeclStackTrace.h" 21 #include "clang/AST/TypeLoc.h" 22 #include "clang/Sema/Initialization.h" 23 #include "clang/Sema/Lookup.h" 24 #include "clang/Sema/Template.h" 25 #include "clang/Sema/TemplateInstCallback.h" 26 #include "llvm/Support/TimeProfiler.h" 27 28 using namespace clang; 29 30 static bool isDeclWithinFunction(const Decl *D) { 31 const DeclContext *DC = D->getDeclContext(); 32 if (DC->isFunctionOrMethod()) 33 return true; 34 35 if (DC->isRecord()) 36 return cast<CXXRecordDecl>(DC)->isLocalClass(); 37 38 return false; 39 } 40 41 template<typename DeclT> 42 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl, 43 const MultiLevelTemplateArgumentList &TemplateArgs) { 44 if (!OldDecl->getQualifierLoc()) 45 return false; 46 47 assert((NewDecl->getFriendObjectKind() || 48 !OldDecl->getLexicalDeclContext()->isDependentContext()) && 49 "non-friend with qualified name defined in dependent context"); 50 Sema::ContextRAII SavedContext( 51 SemaRef, 52 const_cast<DeclContext *>(NewDecl->getFriendObjectKind() 53 ? NewDecl->getLexicalDeclContext() 54 : OldDecl->getLexicalDeclContext())); 55 56 NestedNameSpecifierLoc NewQualifierLoc 57 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 58 TemplateArgs); 59 60 if (!NewQualifierLoc) 61 return true; 62 63 NewDecl->setQualifierInfo(NewQualifierLoc); 64 return false; 65 } 66 67 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 68 DeclaratorDecl *NewDecl) { 69 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); 70 } 71 72 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 73 TagDecl *NewDecl) { 74 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); 75 } 76 77 // Include attribute instantiation code. 78 #include "clang/Sema/AttrTemplateInstantiate.inc" 79 80 static void instantiateDependentAlignedAttr( 81 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 82 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) { 83 if (Aligned->isAlignmentExpr()) { 84 // The alignment expression is a constant expression. 85 EnterExpressionEvaluationContext Unevaluated( 86 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 87 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs); 88 if (!Result.isInvalid()) 89 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(), 90 Aligned->getSpellingListIndex(), IsPackExpansion); 91 } else { 92 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(), 93 TemplateArgs, Aligned->getLocation(), 94 DeclarationName()); 95 if (Result) 96 S.AddAlignedAttr(Aligned->getLocation(), New, Result, 97 Aligned->getSpellingListIndex(), IsPackExpansion); 98 } 99 } 100 101 static void instantiateDependentAlignedAttr( 102 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 103 const AlignedAttr *Aligned, Decl *New) { 104 if (!Aligned->isPackExpansion()) { 105 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 106 return; 107 } 108 109 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 110 if (Aligned->isAlignmentExpr()) 111 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(), 112 Unexpanded); 113 else 114 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(), 115 Unexpanded); 116 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); 117 118 // Determine whether we can expand this attribute pack yet. 119 bool Expand = true, RetainExpansion = false; 120 Optional<unsigned> NumExpansions; 121 // FIXME: Use the actual location of the ellipsis. 122 SourceLocation EllipsisLoc = Aligned->getLocation(); 123 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(), 124 Unexpanded, TemplateArgs, Expand, 125 RetainExpansion, NumExpansions)) 126 return; 127 128 if (!Expand) { 129 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1); 130 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true); 131 } else { 132 for (unsigned I = 0; I != *NumExpansions; ++I) { 133 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I); 134 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 135 } 136 } 137 } 138 139 static void instantiateDependentAssumeAlignedAttr( 140 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 141 const AssumeAlignedAttr *Aligned, Decl *New) { 142 // The alignment expression is a constant expression. 143 EnterExpressionEvaluationContext Unevaluated( 144 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 145 146 Expr *E, *OE = nullptr; 147 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs); 148 if (Result.isInvalid()) 149 return; 150 E = Result.getAs<Expr>(); 151 152 if (Aligned->getOffset()) { 153 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs); 154 if (Result.isInvalid()) 155 return; 156 OE = Result.getAs<Expr>(); 157 } 158 159 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE, 160 Aligned->getSpellingListIndex()); 161 } 162 163 static void instantiateDependentAlignValueAttr( 164 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 165 const AlignValueAttr *Aligned, Decl *New) { 166 // The alignment expression is a constant expression. 167 EnterExpressionEvaluationContext Unevaluated( 168 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 169 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs); 170 if (!Result.isInvalid()) 171 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(), 172 Aligned->getSpellingListIndex()); 173 } 174 175 static void instantiateDependentAllocAlignAttr( 176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 177 const AllocAlignAttr *Align, Decl *New) { 178 Expr *Param = IntegerLiteral::Create( 179 S.getASTContext(), 180 llvm::APInt(64, Align->getParamIndex().getSourceIndex()), 181 S.getASTContext().UnsignedLongLongTy, Align->getLocation()); 182 S.AddAllocAlignAttr(Align->getLocation(), New, Param, 183 Align->getSpellingListIndex()); 184 } 185 186 static Expr *instantiateDependentFunctionAttrCondition( 187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 188 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) { 189 Expr *Cond = nullptr; 190 { 191 Sema::ContextRAII SwitchContext(S, New); 192 EnterExpressionEvaluationContext Unevaluated( 193 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 194 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs); 195 if (Result.isInvalid()) 196 return nullptr; 197 Cond = Result.getAs<Expr>(); 198 } 199 if (!Cond->isTypeDependent()) { 200 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 201 if (Converted.isInvalid()) 202 return nullptr; 203 Cond = Converted.get(); 204 } 205 206 SmallVector<PartialDiagnosticAt, 8> Diags; 207 if (OldCond->isValueDependent() && !Cond->isValueDependent() && 208 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) { 209 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A; 210 for (const auto &P : Diags) 211 S.Diag(P.first, P.second); 212 return nullptr; 213 } 214 return Cond; 215 } 216 217 static void instantiateDependentEnableIfAttr( 218 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 219 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) { 220 Expr *Cond = instantiateDependentFunctionAttrCondition( 221 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New); 222 223 if (Cond) 224 New->addAttr(new (S.getASTContext()) EnableIfAttr( 225 EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(), 226 EIA->getSpellingListIndex())); 227 } 228 229 static void instantiateDependentDiagnoseIfAttr( 230 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 231 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) { 232 Expr *Cond = instantiateDependentFunctionAttrCondition( 233 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New); 234 235 if (Cond) 236 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr( 237 DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(), 238 DIA->getDiagnosticType(), DIA->getArgDependent(), New, 239 DIA->getSpellingListIndex())); 240 } 241 242 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using 243 // template A as the base and arguments from TemplateArgs. 244 static void instantiateDependentCUDALaunchBoundsAttr( 245 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 246 const CUDALaunchBoundsAttr &Attr, Decl *New) { 247 // The alignment expression is a constant expression. 248 EnterExpressionEvaluationContext Unevaluated( 249 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 250 251 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs); 252 if (Result.isInvalid()) 253 return; 254 Expr *MaxThreads = Result.getAs<Expr>(); 255 256 Expr *MinBlocks = nullptr; 257 if (Attr.getMinBlocks()) { 258 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs); 259 if (Result.isInvalid()) 260 return; 261 MinBlocks = Result.getAs<Expr>(); 262 } 263 264 S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks, 265 Attr.getSpellingListIndex()); 266 } 267 268 static void 269 instantiateDependentModeAttr(Sema &S, 270 const MultiLevelTemplateArgumentList &TemplateArgs, 271 const ModeAttr &Attr, Decl *New) { 272 S.AddModeAttr(Attr.getRange(), New, Attr.getMode(), 273 Attr.getSpellingListIndex(), /*InInstantiation=*/true); 274 } 275 276 /// Instantiation of 'declare simd' attribute and its arguments. 277 static void instantiateOMPDeclareSimdDeclAttr( 278 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 279 const OMPDeclareSimdDeclAttr &Attr, Decl *New) { 280 // Allow 'this' in clauses with varlists. 281 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New)) 282 New = FTD->getTemplatedDecl(); 283 auto *FD = cast<FunctionDecl>(New); 284 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext()); 285 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps; 286 SmallVector<unsigned, 4> LinModifiers; 287 288 auto &&Subst = [&](Expr *E) -> ExprResult { 289 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 290 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 291 Sema::ContextRAII SavedContext(S, FD); 292 LocalInstantiationScope Local(S); 293 if (FD->getNumParams() > PVD->getFunctionScopeIndex()) 294 Local.InstantiatedLocal( 295 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex())); 296 return S.SubstExpr(E, TemplateArgs); 297 } 298 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(), 299 FD->isCXXInstanceMember()); 300 return S.SubstExpr(E, TemplateArgs); 301 }; 302 303 ExprResult Simdlen; 304 if (auto *E = Attr.getSimdlen()) 305 Simdlen = Subst(E); 306 307 if (Attr.uniforms_size() > 0) { 308 for(auto *E : Attr.uniforms()) { 309 ExprResult Inst = Subst(E); 310 if (Inst.isInvalid()) 311 continue; 312 Uniforms.push_back(Inst.get()); 313 } 314 } 315 316 auto AI = Attr.alignments_begin(); 317 for (auto *E : Attr.aligneds()) { 318 ExprResult Inst = Subst(E); 319 if (Inst.isInvalid()) 320 continue; 321 Aligneds.push_back(Inst.get()); 322 Inst = ExprEmpty(); 323 if (*AI) 324 Inst = S.SubstExpr(*AI, TemplateArgs); 325 Alignments.push_back(Inst.get()); 326 ++AI; 327 } 328 329 auto SI = Attr.steps_begin(); 330 for (auto *E : Attr.linears()) { 331 ExprResult Inst = Subst(E); 332 if (Inst.isInvalid()) 333 continue; 334 Linears.push_back(Inst.get()); 335 Inst = ExprEmpty(); 336 if (*SI) 337 Inst = S.SubstExpr(*SI, TemplateArgs); 338 Steps.push_back(Inst.get()); 339 ++SI; 340 } 341 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end()); 342 (void)S.ActOnOpenMPDeclareSimdDirective( 343 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(), 344 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps, 345 Attr.getRange()); 346 } 347 348 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr( 349 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 350 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) { 351 // Both min and max expression are constant expressions. 352 EnterExpressionEvaluationContext Unevaluated( 353 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 354 355 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs); 356 if (Result.isInvalid()) 357 return; 358 Expr *MinExpr = Result.getAs<Expr>(); 359 360 Result = S.SubstExpr(Attr.getMax(), TemplateArgs); 361 if (Result.isInvalid()) 362 return; 363 Expr *MaxExpr = Result.getAs<Expr>(); 364 365 S.addAMDGPUFlatWorkGroupSizeAttr(Attr.getLocation(), New, MinExpr, MaxExpr, 366 Attr.getSpellingListIndex()); 367 } 368 369 static ExplicitSpecifier 370 instantiateExplicitSpecifier(Sema &S, 371 const MultiLevelTemplateArgumentList &TemplateArgs, 372 ExplicitSpecifier ES, FunctionDecl *New) { 373 if (!ES.getExpr()) 374 return ES; 375 Expr *OldCond = ES.getExpr(); 376 Expr *Cond = nullptr; 377 { 378 EnterExpressionEvaluationContext Unevaluated( 379 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 380 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs); 381 if (SubstResult.isInvalid()) { 382 return ExplicitSpecifier::Invalid(); 383 } 384 Cond = SubstResult.get(); 385 } 386 ExplicitSpecifier Result(Cond, ES.getKind()); 387 if (!Cond->isTypeDependent()) 388 S.tryResolveExplicitSpecifier(Result); 389 return Result; 390 } 391 392 static void instantiateDependentAMDGPUWavesPerEUAttr( 393 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 394 const AMDGPUWavesPerEUAttr &Attr, Decl *New) { 395 // Both min and max expression are constant expressions. 396 EnterExpressionEvaluationContext Unevaluated( 397 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 398 399 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs); 400 if (Result.isInvalid()) 401 return; 402 Expr *MinExpr = Result.getAs<Expr>(); 403 404 Expr *MaxExpr = nullptr; 405 if (auto Max = Attr.getMax()) { 406 Result = S.SubstExpr(Max, TemplateArgs); 407 if (Result.isInvalid()) 408 return; 409 MaxExpr = Result.getAs<Expr>(); 410 } 411 412 S.addAMDGPUWavesPerEUAttr(Attr.getLocation(), New, MinExpr, MaxExpr, 413 Attr.getSpellingListIndex()); 414 } 415 416 void Sema::InstantiateAttrsForDecl( 417 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl, 418 Decl *New, LateInstantiatedAttrVec *LateAttrs, 419 LocalInstantiationScope *OuterMostScope) { 420 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) { 421 for (const auto *TmplAttr : Tmpl->attrs()) { 422 // FIXME: If any of the special case versions from InstantiateAttrs become 423 // applicable to template declaration, we'll need to add them here. 424 CXXThisScopeRAII ThisScope( 425 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()), 426 Qualifiers(), ND->isCXXInstanceMember()); 427 428 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl( 429 TmplAttr, Context, *this, TemplateArgs); 430 if (NewAttr) 431 New->addAttr(NewAttr); 432 } 433 } 434 } 435 436 static Sema::RetainOwnershipKind 437 attrToRetainOwnershipKind(const Attr *A) { 438 switch (A->getKind()) { 439 case clang::attr::CFConsumed: 440 return Sema::RetainOwnershipKind::CF; 441 case clang::attr::OSConsumed: 442 return Sema::RetainOwnershipKind::OS; 443 case clang::attr::NSConsumed: 444 return Sema::RetainOwnershipKind::NS; 445 default: 446 llvm_unreachable("Wrong argument supplied"); 447 } 448 } 449 450 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 451 const Decl *Tmpl, Decl *New, 452 LateInstantiatedAttrVec *LateAttrs, 453 LocalInstantiationScope *OuterMostScope) { 454 for (const auto *TmplAttr : Tmpl->attrs()) { 455 // FIXME: This should be generalized to more than just the AlignedAttr. 456 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr); 457 if (Aligned && Aligned->isAlignmentDependent()) { 458 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New); 459 continue; 460 } 461 462 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr); 463 if (AssumeAligned) { 464 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New); 465 continue; 466 } 467 468 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr); 469 if (AlignValue) { 470 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New); 471 continue; 472 } 473 474 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) { 475 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New); 476 continue; 477 } 478 479 480 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) { 481 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl, 482 cast<FunctionDecl>(New)); 483 continue; 484 } 485 486 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) { 487 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl, 488 cast<FunctionDecl>(New)); 489 continue; 490 } 491 492 if (const CUDALaunchBoundsAttr *CUDALaunchBounds = 493 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) { 494 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs, 495 *CUDALaunchBounds, New); 496 continue; 497 } 498 499 if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) { 500 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New); 501 continue; 502 } 503 504 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) { 505 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New); 506 continue; 507 } 508 509 if (const AMDGPUFlatWorkGroupSizeAttr *AMDGPUFlatWorkGroupSize = 510 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) { 511 instantiateDependentAMDGPUFlatWorkGroupSizeAttr( 512 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New); 513 } 514 515 if (const AMDGPUWavesPerEUAttr *AMDGPUFlatWorkGroupSize = 516 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) { 517 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs, 518 *AMDGPUFlatWorkGroupSize, New); 519 } 520 521 // Existing DLL attribute on the instantiation takes precedence. 522 if (TmplAttr->getKind() == attr::DLLExport || 523 TmplAttr->getKind() == attr::DLLImport) { 524 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) { 525 continue; 526 } 527 } 528 529 if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) { 530 AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(), 531 ABIAttr->getSpellingListIndex()); 532 continue; 533 } 534 535 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) || 536 isa<CFConsumedAttr>(TmplAttr)) { 537 AddXConsumedAttr(New, TmplAttr->getRange(), 538 TmplAttr->getSpellingListIndex(), 539 attrToRetainOwnershipKind(TmplAttr), 540 /*template instantiation=*/true); 541 continue; 542 } 543 544 assert(!TmplAttr->isPackExpansion()); 545 if (TmplAttr->isLateParsed() && LateAttrs) { 546 // Late parsed attributes must be instantiated and attached after the 547 // enclosing class has been instantiated. See Sema::InstantiateClass. 548 LocalInstantiationScope *Saved = nullptr; 549 if (CurrentInstantiationScope) 550 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); 551 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); 552 } else { 553 // Allow 'this' within late-parsed attributes. 554 NamedDecl *ND = dyn_cast<NamedDecl>(New); 555 CXXRecordDecl *ThisContext = 556 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); 557 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), 558 ND && ND->isCXXInstanceMember()); 559 560 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, 561 *this, TemplateArgs); 562 if (NewAttr) 563 New->addAttr(NewAttr); 564 } 565 } 566 } 567 568 /// Get the previous declaration of a declaration for the purposes of template 569 /// instantiation. If this finds a previous declaration, then the previous 570 /// declaration of the instantiation of D should be an instantiation of the 571 /// result of this function. 572 template<typename DeclT> 573 static DeclT *getPreviousDeclForInstantiation(DeclT *D) { 574 DeclT *Result = D->getPreviousDecl(); 575 576 // If the declaration is within a class, and the previous declaration was 577 // merged from a different definition of that class, then we don't have a 578 // previous declaration for the purpose of template instantiation. 579 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) && 580 D->getLexicalDeclContext() != Result->getLexicalDeclContext()) 581 return nullptr; 582 583 return Result; 584 } 585 586 Decl * 587 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 588 llvm_unreachable("Translation units cannot be instantiated"); 589 } 590 591 Decl * 592 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) { 593 llvm_unreachable("pragma comment cannot be instantiated"); 594 } 595 596 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl( 597 PragmaDetectMismatchDecl *D) { 598 llvm_unreachable("pragma comment cannot be instantiated"); 599 } 600 601 Decl * 602 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) { 603 llvm_unreachable("extern \"C\" context cannot be instantiated"); 604 } 605 606 Decl * 607 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 608 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 609 D->getIdentifier()); 610 Owner->addDecl(Inst); 611 return Inst; 612 } 613 614 Decl * 615 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 616 llvm_unreachable("Namespaces cannot be instantiated"); 617 } 618 619 Decl * 620 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 621 NamespaceAliasDecl *Inst 622 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 623 D->getNamespaceLoc(), 624 D->getAliasLoc(), 625 D->getIdentifier(), 626 D->getQualifierLoc(), 627 D->getTargetNameLoc(), 628 D->getNamespace()); 629 Owner->addDecl(Inst); 630 return Inst; 631 } 632 633 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 634 bool IsTypeAlias) { 635 bool Invalid = false; 636 TypeSourceInfo *DI = D->getTypeSourceInfo(); 637 if (DI->getType()->isInstantiationDependentType() || 638 DI->getType()->isVariablyModifiedType()) { 639 DI = SemaRef.SubstType(DI, TemplateArgs, 640 D->getLocation(), D->getDeclName()); 641 if (!DI) { 642 Invalid = true; 643 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 644 } 645 } else { 646 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 647 } 648 649 // HACK: g++ has a bug where it gets the value kind of ?: wrong. 650 // libstdc++ relies upon this bug in its implementation of common_type. 651 // If we happen to be processing that implementation, fake up the g++ ?: 652 // semantics. See LWG issue 2141 for more information on the bug. 653 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>(); 654 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 655 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) && 656 DT->isReferenceType() && 657 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() && 658 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") && 659 D->getIdentifier() && D->getIdentifier()->isStr("type") && 660 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc())) 661 // Fold it to the (non-reference) type which g++ would have produced. 662 DI = SemaRef.Context.getTrivialTypeSourceInfo( 663 DI->getType().getNonReferenceType()); 664 665 // Create the new typedef 666 TypedefNameDecl *Typedef; 667 if (IsTypeAlias) 668 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(), 669 D->getLocation(), D->getIdentifier(), DI); 670 else 671 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(), 672 D->getLocation(), D->getIdentifier(), DI); 673 if (Invalid) 674 Typedef->setInvalidDecl(); 675 676 // If the old typedef was the name for linkage purposes of an anonymous 677 // tag decl, re-establish that relationship for the new typedef. 678 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 679 TagDecl *oldTag = oldTagType->getDecl(); 680 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) { 681 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 682 assert(!newTag->hasNameForLinkage()); 683 newTag->setTypedefNameForAnonDecl(Typedef); 684 } 685 } 686 687 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) { 688 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 689 TemplateArgs); 690 if (!InstPrev) 691 return nullptr; 692 693 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev); 694 695 // If the typedef types are not identical, reject them. 696 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); 697 698 Typedef->setPreviousDecl(InstPrevTypedef); 699 } 700 701 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); 702 703 Typedef->setAccess(D->getAccess()); 704 705 return Typedef; 706 } 707 708 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 709 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); 710 if (Typedef) 711 Owner->addDecl(Typedef); 712 return Typedef; 713 } 714 715 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { 716 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); 717 if (Typedef) 718 Owner->addDecl(Typedef); 719 return Typedef; 720 } 721 722 Decl * 723 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 724 // Create a local instantiation scope for this type alias template, which 725 // will contain the instantiations of the template parameters. 726 LocalInstantiationScope Scope(SemaRef); 727 728 TemplateParameterList *TempParams = D->getTemplateParameters(); 729 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 730 if (!InstParams) 731 return nullptr; 732 733 TypeAliasDecl *Pattern = D->getTemplatedDecl(); 734 735 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr; 736 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) { 737 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 738 if (!Found.empty()) { 739 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front()); 740 } 741 } 742 743 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( 744 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); 745 if (!AliasInst) 746 return nullptr; 747 748 TypeAliasTemplateDecl *Inst 749 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 750 D->getDeclName(), InstParams, AliasInst); 751 AliasInst->setDescribedAliasTemplate(Inst); 752 if (PrevAliasTemplate) 753 Inst->setPreviousDecl(PrevAliasTemplate); 754 755 Inst->setAccess(D->getAccess()); 756 757 if (!PrevAliasTemplate) 758 Inst->setInstantiatedFromMemberTemplate(D); 759 760 Owner->addDecl(Inst); 761 762 return Inst; 763 } 764 765 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) { 766 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(), 767 D->getIdentifier()); 768 NewBD->setReferenced(D->isReferenced()); 769 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD); 770 return NewBD; 771 } 772 773 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) { 774 // Transform the bindings first. 775 SmallVector<BindingDecl*, 16> NewBindings; 776 for (auto *OldBD : D->bindings()) 777 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD))); 778 ArrayRef<BindingDecl*> NewBindingArray = NewBindings; 779 780 auto *NewDD = cast_or_null<DecompositionDecl>( 781 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray)); 782 783 if (!NewDD || NewDD->isInvalidDecl()) 784 for (auto *NewBD : NewBindings) 785 NewBD->setInvalidDecl(); 786 787 return NewDD; 788 } 789 790 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 791 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false); 792 } 793 794 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, 795 bool InstantiatingVarTemplate, 796 ArrayRef<BindingDecl*> *Bindings) { 797 798 // Do substitution on the type of the declaration 799 TypeSourceInfo *DI = SemaRef.SubstType( 800 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(), 801 D->getDeclName(), /*AllowDeducedTST*/true); 802 if (!DI) 803 return nullptr; 804 805 if (DI->getType()->isFunctionType()) { 806 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 807 << D->isStaticDataMember() << DI->getType(); 808 return nullptr; 809 } 810 811 DeclContext *DC = Owner; 812 if (D->isLocalExternDecl()) 813 SemaRef.adjustContextForLocalExternDecl(DC); 814 815 // Build the instantiated declaration. 816 VarDecl *Var; 817 if (Bindings) 818 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 819 D->getLocation(), DI->getType(), DI, 820 D->getStorageClass(), *Bindings); 821 else 822 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 823 D->getLocation(), D->getIdentifier(), DI->getType(), 824 DI, D->getStorageClass()); 825 826 // In ARC, infer 'retaining' for variables of retainable type. 827 if (SemaRef.getLangOpts().ObjCAutoRefCount && 828 SemaRef.inferObjCARCLifetime(Var)) 829 Var->setInvalidDecl(); 830 831 // Substitute the nested name specifier, if any. 832 if (SubstQualifier(D, Var)) 833 return nullptr; 834 835 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 836 StartingScope, InstantiatingVarTemplate); 837 838 if (D->isNRVOVariable()) { 839 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType(); 840 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict)) 841 Var->setNRVOVariable(true); 842 } 843 844 Var->setImplicit(D->isImplicit()); 845 846 if (Var->isStaticLocal()) 847 SemaRef.CheckStaticLocalForDllExport(Var); 848 849 return Var; 850 } 851 852 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { 853 AccessSpecDecl* AD 854 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner, 855 D->getAccessSpecifierLoc(), D->getColonLoc()); 856 Owner->addHiddenDecl(AD); 857 return AD; 858 } 859 860 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 861 bool Invalid = false; 862 TypeSourceInfo *DI = D->getTypeSourceInfo(); 863 if (DI->getType()->isInstantiationDependentType() || 864 DI->getType()->isVariablyModifiedType()) { 865 DI = SemaRef.SubstType(DI, TemplateArgs, 866 D->getLocation(), D->getDeclName()); 867 if (!DI) { 868 DI = D->getTypeSourceInfo(); 869 Invalid = true; 870 } else if (DI->getType()->isFunctionType()) { 871 // C++ [temp.arg.type]p3: 872 // If a declaration acquires a function type through a type 873 // dependent on a template-parameter and this causes a 874 // declaration that does not use the syntactic form of a 875 // function declarator to have function type, the program is 876 // ill-formed. 877 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 878 << DI->getType(); 879 Invalid = true; 880 } 881 } else { 882 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 883 } 884 885 Expr *BitWidth = D->getBitWidth(); 886 if (Invalid) 887 BitWidth = nullptr; 888 else if (BitWidth) { 889 // The bit-width expression is a constant expression. 890 EnterExpressionEvaluationContext Unevaluated( 891 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 892 893 ExprResult InstantiatedBitWidth 894 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 895 if (InstantiatedBitWidth.isInvalid()) { 896 Invalid = true; 897 BitWidth = nullptr; 898 } else 899 BitWidth = InstantiatedBitWidth.getAs<Expr>(); 900 } 901 902 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 903 DI->getType(), DI, 904 cast<RecordDecl>(Owner), 905 D->getLocation(), 906 D->isMutable(), 907 BitWidth, 908 D->getInClassInitStyle(), 909 D->getInnerLocStart(), 910 D->getAccess(), 911 nullptr); 912 if (!Field) { 913 cast<Decl>(Owner)->setInvalidDecl(); 914 return nullptr; 915 } 916 917 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope); 918 919 if (Field->hasAttrs()) 920 SemaRef.CheckAlignasUnderalignment(Field); 921 922 if (Invalid) 923 Field->setInvalidDecl(); 924 925 if (!Field->getDeclName()) { 926 // Keep track of where this decl came from. 927 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 928 } 929 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 930 if (Parent->isAnonymousStructOrUnion() && 931 Parent->getRedeclContext()->isFunctionOrMethod()) 932 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 933 } 934 935 Field->setImplicit(D->isImplicit()); 936 Field->setAccess(D->getAccess()); 937 Owner->addDecl(Field); 938 939 return Field; 940 } 941 942 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) { 943 bool Invalid = false; 944 TypeSourceInfo *DI = D->getTypeSourceInfo(); 945 946 if (DI->getType()->isVariablyModifiedType()) { 947 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified) 948 << D; 949 Invalid = true; 950 } else if (DI->getType()->isInstantiationDependentType()) { 951 DI = SemaRef.SubstType(DI, TemplateArgs, 952 D->getLocation(), D->getDeclName()); 953 if (!DI) { 954 DI = D->getTypeSourceInfo(); 955 Invalid = true; 956 } else if (DI->getType()->isFunctionType()) { 957 // C++ [temp.arg.type]p3: 958 // If a declaration acquires a function type through a type 959 // dependent on a template-parameter and this causes a 960 // declaration that does not use the syntactic form of a 961 // function declarator to have function type, the program is 962 // ill-formed. 963 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 964 << DI->getType(); 965 Invalid = true; 966 } 967 } else { 968 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 969 } 970 971 MSPropertyDecl *Property = MSPropertyDecl::Create( 972 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(), 973 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId()); 974 975 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs, 976 StartingScope); 977 978 if (Invalid) 979 Property->setInvalidDecl(); 980 981 Property->setAccess(D->getAccess()); 982 Owner->addDecl(Property); 983 984 return Property; 985 } 986 987 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 988 NamedDecl **NamedChain = 989 new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; 990 991 int i = 0; 992 for (auto *PI : D->chain()) { 993 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI, 994 TemplateArgs); 995 if (!Next) 996 return nullptr; 997 998 NamedChain[i++] = Next; 999 } 1000 1001 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType(); 1002 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 1003 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T, 1004 {NamedChain, D->getChainingSize()}); 1005 1006 for (const auto *Attr : D->attrs()) 1007 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 1008 1009 IndirectField->setImplicit(D->isImplicit()); 1010 IndirectField->setAccess(D->getAccess()); 1011 Owner->addDecl(IndirectField); 1012 return IndirectField; 1013 } 1014 1015 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 1016 // Handle friend type expressions by simply substituting template 1017 // parameters into the pattern type and checking the result. 1018 if (TypeSourceInfo *Ty = D->getFriendType()) { 1019 TypeSourceInfo *InstTy; 1020 // If this is an unsupported friend, don't bother substituting template 1021 // arguments into it. The actual type referred to won't be used by any 1022 // parts of Clang, and may not be valid for instantiating. Just use the 1023 // same info for the instantiated friend. 1024 if (D->isUnsupportedFriend()) { 1025 InstTy = Ty; 1026 } else { 1027 InstTy = SemaRef.SubstType(Ty, TemplateArgs, 1028 D->getLocation(), DeclarationName()); 1029 } 1030 if (!InstTy) 1031 return nullptr; 1032 1033 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(), 1034 D->getFriendLoc(), InstTy); 1035 if (!FD) 1036 return nullptr; 1037 1038 FD->setAccess(AS_public); 1039 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 1040 Owner->addDecl(FD); 1041 return FD; 1042 } 1043 1044 NamedDecl *ND = D->getFriendDecl(); 1045 assert(ND && "friend decl must be a decl or a type!"); 1046 1047 // All of the Visit implementations for the various potential friend 1048 // declarations have to be carefully written to work for friend 1049 // objects, with the most important detail being that the target 1050 // decl should almost certainly not be placed in Owner. 1051 Decl *NewND = Visit(ND); 1052 if (!NewND) return nullptr; 1053 1054 FriendDecl *FD = 1055 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1056 cast<NamedDecl>(NewND), D->getFriendLoc()); 1057 FD->setAccess(AS_public); 1058 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 1059 Owner->addDecl(FD); 1060 return FD; 1061 } 1062 1063 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 1064 Expr *AssertExpr = D->getAssertExpr(); 1065 1066 // The expression in a static assertion is a constant expression. 1067 EnterExpressionEvaluationContext Unevaluated( 1068 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1069 1070 ExprResult InstantiatedAssertExpr 1071 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 1072 if (InstantiatedAssertExpr.isInvalid()) 1073 return nullptr; 1074 1075 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(), 1076 InstantiatedAssertExpr.get(), 1077 D->getMessage(), 1078 D->getRParenLoc(), 1079 D->isFailed()); 1080 } 1081 1082 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 1083 EnumDecl *PrevDecl = nullptr; 1084 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { 1085 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 1086 PatternPrev, 1087 TemplateArgs); 1088 if (!Prev) return nullptr; 1089 PrevDecl = cast<EnumDecl>(Prev); 1090 } 1091 1092 EnumDecl *Enum = 1093 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(), 1094 D->getLocation(), D->getIdentifier(), PrevDecl, 1095 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed()); 1096 if (D->isFixed()) { 1097 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { 1098 // If we have type source information for the underlying type, it means it 1099 // has been explicitly set by the user. Perform substitution on it before 1100 // moving on. 1101 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 1102 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc, 1103 DeclarationName()); 1104 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI)) 1105 Enum->setIntegerType(SemaRef.Context.IntTy); 1106 else 1107 Enum->setIntegerTypeSourceInfo(NewTI); 1108 } else { 1109 assert(!D->getIntegerType()->isDependentType() 1110 && "Dependent type without type source info"); 1111 Enum->setIntegerType(D->getIntegerType()); 1112 } 1113 } 1114 1115 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); 1116 1117 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation); 1118 Enum->setAccess(D->getAccess()); 1119 // Forward the mangling number from the template to the instantiated decl. 1120 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D)); 1121 // See if the old tag was defined along with a declarator. 1122 // If it did, mark the new tag as being associated with that declarator. 1123 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D)) 1124 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD); 1125 // See if the old tag was defined along with a typedef. 1126 // If it did, mark the new tag as being associated with that typedef. 1127 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D)) 1128 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND); 1129 if (SubstQualifier(D, Enum)) return nullptr; 1130 Owner->addDecl(Enum); 1131 1132 EnumDecl *Def = D->getDefinition(); 1133 if (Def && Def != D) { 1134 // If this is an out-of-line definition of an enum member template, check 1135 // that the underlying types match in the instantiation of both 1136 // declarations. 1137 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { 1138 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 1139 QualType DefnUnderlying = 1140 SemaRef.SubstType(TI->getType(), TemplateArgs, 1141 UnderlyingLoc, DeclarationName()); 1142 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(), 1143 DefnUnderlying, /*IsFixed=*/true, Enum); 1144 } 1145 } 1146 1147 // C++11 [temp.inst]p1: The implicit instantiation of a class template 1148 // specialization causes the implicit instantiation of the declarations, but 1149 // not the definitions of scoped member enumerations. 1150 // 1151 // DR1484 clarifies that enumeration definitions inside of a template 1152 // declaration aren't considered entities that can be separately instantiated 1153 // from the rest of the entity they are declared inside of. 1154 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) { 1155 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 1156 InstantiateEnumDefinition(Enum, Def); 1157 } 1158 1159 return Enum; 1160 } 1161 1162 void TemplateDeclInstantiator::InstantiateEnumDefinition( 1163 EnumDecl *Enum, EnumDecl *Pattern) { 1164 Enum->startDefinition(); 1165 1166 // Update the location to refer to the definition. 1167 Enum->setLocation(Pattern->getLocation()); 1168 1169 SmallVector<Decl*, 4> Enumerators; 1170 1171 EnumConstantDecl *LastEnumConst = nullptr; 1172 for (auto *EC : Pattern->enumerators()) { 1173 // The specified value for the enumerator. 1174 ExprResult Value((Expr *)nullptr); 1175 if (Expr *UninstValue = EC->getInitExpr()) { 1176 // The enumerator's value expression is a constant expression. 1177 EnterExpressionEvaluationContext Unevaluated( 1178 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1179 1180 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 1181 } 1182 1183 // Drop the initial value and continue. 1184 bool isInvalid = false; 1185 if (Value.isInvalid()) { 1186 Value = nullptr; 1187 isInvalid = true; 1188 } 1189 1190 EnumConstantDecl *EnumConst 1191 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 1192 EC->getLocation(), EC->getIdentifier(), 1193 Value.get()); 1194 1195 if (isInvalid) { 1196 if (EnumConst) 1197 EnumConst->setInvalidDecl(); 1198 Enum->setInvalidDecl(); 1199 } 1200 1201 if (EnumConst) { 1202 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst); 1203 1204 EnumConst->setAccess(Enum->getAccess()); 1205 Enum->addDecl(EnumConst); 1206 Enumerators.push_back(EnumConst); 1207 LastEnumConst = EnumConst; 1208 1209 if (Pattern->getDeclContext()->isFunctionOrMethod() && 1210 !Enum->isScoped()) { 1211 // If the enumeration is within a function or method, record the enum 1212 // constant as a local. 1213 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst); 1214 } 1215 } 1216 } 1217 1218 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum, 1219 Enumerators, nullptr, ParsedAttributesView()); 1220 } 1221 1222 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 1223 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls."); 1224 } 1225 1226 Decl * 1227 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) { 1228 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated."); 1229 } 1230 1231 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 1232 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1233 1234 // Create a local instantiation scope for this class template, which 1235 // will contain the instantiations of the template parameters. 1236 LocalInstantiationScope Scope(SemaRef); 1237 TemplateParameterList *TempParams = D->getTemplateParameters(); 1238 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1239 if (!InstParams) 1240 return nullptr; 1241 1242 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 1243 1244 // Instantiate the qualifier. We have to do this first in case 1245 // we're a friend declaration, because if we are then we need to put 1246 // the new declaration in the appropriate context. 1247 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); 1248 if (QualifierLoc) { 1249 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1250 TemplateArgs); 1251 if (!QualifierLoc) 1252 return nullptr; 1253 } 1254 1255 CXXRecordDecl *PrevDecl = nullptr; 1256 ClassTemplateDecl *PrevClassTemplate = nullptr; 1257 1258 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) { 1259 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 1260 if (!Found.empty()) { 1261 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front()); 1262 if (PrevClassTemplate) 1263 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 1264 } 1265 } 1266 1267 // If this isn't a friend, then it's a member template, in which 1268 // case we just want to build the instantiation in the 1269 // specialization. If it is a friend, we want to build it in 1270 // the appropriate context. 1271 DeclContext *DC = Owner; 1272 if (isFriend) { 1273 if (QualifierLoc) { 1274 CXXScopeSpec SS; 1275 SS.Adopt(QualifierLoc); 1276 DC = SemaRef.computeDeclContext(SS); 1277 if (!DC) return nullptr; 1278 } else { 1279 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 1280 Pattern->getDeclContext(), 1281 TemplateArgs); 1282 } 1283 1284 // Look for a previous declaration of the template in the owning 1285 // context. 1286 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 1287 Sema::LookupOrdinaryName, 1288 SemaRef.forRedeclarationInCurContext()); 1289 SemaRef.LookupQualifiedName(R, DC); 1290 1291 if (R.isSingleResult()) { 1292 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 1293 if (PrevClassTemplate) 1294 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 1295 } 1296 1297 if (!PrevClassTemplate && QualifierLoc) { 1298 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 1299 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 1300 << QualifierLoc.getSourceRange(); 1301 return nullptr; 1302 } 1303 1304 bool AdoptedPreviousTemplateParams = false; 1305 if (PrevClassTemplate) { 1306 bool Complain = true; 1307 1308 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 1309 // template for struct std::tr1::__detail::_Map_base, where the 1310 // template parameters of the friend declaration don't match the 1311 // template parameters of the original declaration. In this one 1312 // case, we don't complain about the ill-formed friend 1313 // declaration. 1314 if (isFriend && Pattern->getIdentifier() && 1315 Pattern->getIdentifier()->isStr("_Map_base") && 1316 DC->isNamespace() && 1317 cast<NamespaceDecl>(DC)->getIdentifier() && 1318 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 1319 DeclContext *DCParent = DC->getParent(); 1320 if (DCParent->isNamespace() && 1321 cast<NamespaceDecl>(DCParent)->getIdentifier() && 1322 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 1323 if (cast<Decl>(DCParent)->isInStdNamespace()) 1324 Complain = false; 1325 } 1326 } 1327 1328 TemplateParameterList *PrevParams 1329 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters(); 1330 1331 // Make sure the parameter lists match. 1332 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 1333 Complain, 1334 Sema::TPL_TemplateMatch)) { 1335 if (Complain) 1336 return nullptr; 1337 1338 AdoptedPreviousTemplateParams = true; 1339 InstParams = PrevParams; 1340 } 1341 1342 // Do some additional validation, then merge default arguments 1343 // from the existing declarations. 1344 if (!AdoptedPreviousTemplateParams && 1345 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 1346 Sema::TPC_ClassTemplate)) 1347 return nullptr; 1348 } 1349 } 1350 1351 CXXRecordDecl *RecordInst = CXXRecordDecl::Create( 1352 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(), 1353 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl, 1354 /*DelayTypeCreation=*/true); 1355 1356 if (QualifierLoc) 1357 RecordInst->setQualifierInfo(QualifierLoc); 1358 1359 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs, 1360 StartingScope); 1361 1362 ClassTemplateDecl *Inst 1363 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 1364 D->getIdentifier(), InstParams, RecordInst); 1365 assert(!(isFriend && Owner->isDependentContext())); 1366 Inst->setPreviousDecl(PrevClassTemplate); 1367 1368 RecordInst->setDescribedClassTemplate(Inst); 1369 1370 if (isFriend) { 1371 if (PrevClassTemplate) 1372 Inst->setAccess(PrevClassTemplate->getAccess()); 1373 else 1374 Inst->setAccess(D->getAccess()); 1375 1376 Inst->setObjectOfFriendDecl(); 1377 // TODO: do we want to track the instantiation progeny of this 1378 // friend target decl? 1379 } else { 1380 Inst->setAccess(D->getAccess()); 1381 if (!PrevClassTemplate) 1382 Inst->setInstantiatedFromMemberTemplate(D); 1383 } 1384 1385 // Trigger creation of the type for the instantiation. 1386 SemaRef.Context.getInjectedClassNameType(RecordInst, 1387 Inst->getInjectedClassNameSpecialization()); 1388 1389 // Finish handling of friends. 1390 if (isFriend) { 1391 DC->makeDeclVisibleInContext(Inst); 1392 Inst->setLexicalDeclContext(Owner); 1393 RecordInst->setLexicalDeclContext(Owner); 1394 return Inst; 1395 } 1396 1397 if (D->isOutOfLine()) { 1398 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 1399 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); 1400 } 1401 1402 Owner->addDecl(Inst); 1403 1404 if (!PrevClassTemplate) { 1405 // Queue up any out-of-line partial specializations of this member 1406 // class template; the client will force their instantiation once 1407 // the enclosing class has been instantiated. 1408 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 1409 D->getPartialSpecializations(PartialSpecs); 1410 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 1411 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 1412 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I])); 1413 } 1414 1415 return Inst; 1416 } 1417 1418 Decl * 1419 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 1420 ClassTemplatePartialSpecializationDecl *D) { 1421 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 1422 1423 // Lookup the already-instantiated declaration in the instantiation 1424 // of the class template and return that. 1425 DeclContext::lookup_result Found 1426 = Owner->lookup(ClassTemplate->getDeclName()); 1427 if (Found.empty()) 1428 return nullptr; 1429 1430 ClassTemplateDecl *InstClassTemplate 1431 = dyn_cast<ClassTemplateDecl>(Found.front()); 1432 if (!InstClassTemplate) 1433 return nullptr; 1434 1435 if (ClassTemplatePartialSpecializationDecl *Result 1436 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) 1437 return Result; 1438 1439 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D); 1440 } 1441 1442 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) { 1443 assert(D->getTemplatedDecl()->isStaticDataMember() && 1444 "Only static data member templates are allowed."); 1445 1446 // Create a local instantiation scope for this variable template, which 1447 // will contain the instantiations of the template parameters. 1448 LocalInstantiationScope Scope(SemaRef); 1449 TemplateParameterList *TempParams = D->getTemplateParameters(); 1450 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1451 if (!InstParams) 1452 return nullptr; 1453 1454 VarDecl *Pattern = D->getTemplatedDecl(); 1455 VarTemplateDecl *PrevVarTemplate = nullptr; 1456 1457 if (getPreviousDeclForInstantiation(Pattern)) { 1458 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 1459 if (!Found.empty()) 1460 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 1461 } 1462 1463 VarDecl *VarInst = 1464 cast_or_null<VarDecl>(VisitVarDecl(Pattern, 1465 /*InstantiatingVarTemplate=*/true)); 1466 if (!VarInst) return nullptr; 1467 1468 DeclContext *DC = Owner; 1469 1470 VarTemplateDecl *Inst = VarTemplateDecl::Create( 1471 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams, 1472 VarInst); 1473 VarInst->setDescribedVarTemplate(Inst); 1474 Inst->setPreviousDecl(PrevVarTemplate); 1475 1476 Inst->setAccess(D->getAccess()); 1477 if (!PrevVarTemplate) 1478 Inst->setInstantiatedFromMemberTemplate(D); 1479 1480 if (D->isOutOfLine()) { 1481 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 1482 VarInst->setLexicalDeclContext(D->getLexicalDeclContext()); 1483 } 1484 1485 Owner->addDecl(Inst); 1486 1487 if (!PrevVarTemplate) { 1488 // Queue up any out-of-line partial specializations of this member 1489 // variable template; the client will force their instantiation once 1490 // the enclosing class has been instantiated. 1491 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 1492 D->getPartialSpecializations(PartialSpecs); 1493 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 1494 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 1495 OutOfLineVarPartialSpecs.push_back( 1496 std::make_pair(Inst, PartialSpecs[I])); 1497 } 1498 1499 return Inst; 1500 } 1501 1502 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl( 1503 VarTemplatePartialSpecializationDecl *D) { 1504 assert(D->isStaticDataMember() && 1505 "Only static data member templates are allowed."); 1506 1507 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 1508 1509 // Lookup the already-instantiated declaration and return that. 1510 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName()); 1511 assert(!Found.empty() && "Instantiation found nothing?"); 1512 1513 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 1514 assert(InstVarTemplate && "Instantiation did not find a variable template?"); 1515 1516 if (VarTemplatePartialSpecializationDecl *Result = 1517 InstVarTemplate->findPartialSpecInstantiatedFromMember(D)) 1518 return Result; 1519 1520 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D); 1521 } 1522 1523 Decl * 1524 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 1525 // Create a local instantiation scope for this function template, which 1526 // will contain the instantiations of the template parameters and then get 1527 // merged with the local instantiation scope for the function template 1528 // itself. 1529 LocalInstantiationScope Scope(SemaRef); 1530 1531 TemplateParameterList *TempParams = D->getTemplateParameters(); 1532 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1533 if (!InstParams) 1534 return nullptr; 1535 1536 FunctionDecl *Instantiated = nullptr; 1537 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 1538 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 1539 InstParams)); 1540 else 1541 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 1542 D->getTemplatedDecl(), 1543 InstParams)); 1544 1545 if (!Instantiated) 1546 return nullptr; 1547 1548 // Link the instantiated function template declaration to the function 1549 // template from which it was instantiated. 1550 FunctionTemplateDecl *InstTemplate 1551 = Instantiated->getDescribedFunctionTemplate(); 1552 InstTemplate->setAccess(D->getAccess()); 1553 assert(InstTemplate && 1554 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 1555 1556 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 1557 1558 // Link the instantiation back to the pattern *unless* this is a 1559 // non-definition friend declaration. 1560 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 1561 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 1562 InstTemplate->setInstantiatedFromMemberTemplate(D); 1563 1564 // Make declarations visible in the appropriate context. 1565 if (!isFriend) { 1566 Owner->addDecl(InstTemplate); 1567 } else if (InstTemplate->getDeclContext()->isRecord() && 1568 !getPreviousDeclForInstantiation(D)) { 1569 SemaRef.CheckFriendAccess(InstTemplate); 1570 } 1571 1572 return InstTemplate; 1573 } 1574 1575 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 1576 CXXRecordDecl *PrevDecl = nullptr; 1577 if (D->isInjectedClassName()) 1578 PrevDecl = cast<CXXRecordDecl>(Owner); 1579 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { 1580 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 1581 PatternPrev, 1582 TemplateArgs); 1583 if (!Prev) return nullptr; 1584 PrevDecl = cast<CXXRecordDecl>(Prev); 1585 } 1586 1587 CXXRecordDecl *Record = CXXRecordDecl::Create( 1588 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(), 1589 D->getLocation(), D->getIdentifier(), PrevDecl); 1590 1591 // Substitute the nested name specifier, if any. 1592 if (SubstQualifier(D, Record)) 1593 return nullptr; 1594 1595 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs, 1596 StartingScope); 1597 1598 Record->setImplicit(D->isImplicit()); 1599 // FIXME: Check against AS_none is an ugly hack to work around the issue that 1600 // the tag decls introduced by friend class declarations don't have an access 1601 // specifier. Remove once this area of the code gets sorted out. 1602 if (D->getAccess() != AS_none) 1603 Record->setAccess(D->getAccess()); 1604 if (!D->isInjectedClassName()) 1605 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 1606 1607 // If the original function was part of a friend declaration, 1608 // inherit its namespace state. 1609 if (D->getFriendObjectKind()) 1610 Record->setObjectOfFriendDecl(); 1611 1612 // Make sure that anonymous structs and unions are recorded. 1613 if (D->isAnonymousStructOrUnion()) 1614 Record->setAnonymousStructOrUnion(true); 1615 1616 if (D->isLocalClass()) 1617 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 1618 1619 // Forward the mangling number from the template to the instantiated decl. 1620 SemaRef.Context.setManglingNumber(Record, 1621 SemaRef.Context.getManglingNumber(D)); 1622 1623 // See if the old tag was defined along with a declarator. 1624 // If it did, mark the new tag as being associated with that declarator. 1625 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D)) 1626 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD); 1627 1628 // See if the old tag was defined along with a typedef. 1629 // If it did, mark the new tag as being associated with that typedef. 1630 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D)) 1631 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND); 1632 1633 Owner->addDecl(Record); 1634 1635 // DR1484 clarifies that the members of a local class are instantiated as part 1636 // of the instantiation of their enclosing entity. 1637 if (D->isCompleteDefinition() && D->isLocalClass()) { 1638 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef); 1639 1640 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs, 1641 TSK_ImplicitInstantiation, 1642 /*Complain=*/true); 1643 1644 // For nested local classes, we will instantiate the members when we 1645 // reach the end of the outermost (non-nested) local class. 1646 if (!D->isCXXClassMember()) 1647 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs, 1648 TSK_ImplicitInstantiation); 1649 1650 // This class may have local implicit instantiations that need to be 1651 // performed within this scope. 1652 LocalInstantiations.perform(); 1653 } 1654 1655 SemaRef.DiagnoseUnusedNestedTypedefs(Record); 1656 1657 return Record; 1658 } 1659 1660 /// Adjust the given function type for an instantiation of the 1661 /// given declaration, to cope with modifications to the function's type that 1662 /// aren't reflected in the type-source information. 1663 /// 1664 /// \param D The declaration we're instantiating. 1665 /// \param TInfo The already-instantiated type. 1666 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, 1667 FunctionDecl *D, 1668 TypeSourceInfo *TInfo) { 1669 const FunctionProtoType *OrigFunc 1670 = D->getType()->castAs<FunctionProtoType>(); 1671 const FunctionProtoType *NewFunc 1672 = TInfo->getType()->castAs<FunctionProtoType>(); 1673 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo()) 1674 return TInfo->getType(); 1675 1676 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo(); 1677 NewEPI.ExtInfo = OrigFunc->getExtInfo(); 1678 return Context.getFunctionType(NewFunc->getReturnType(), 1679 NewFunc->getParamTypes(), NewEPI); 1680 } 1681 1682 /// Normal class members are of more specific types and therefore 1683 /// don't make it here. This function serves three purposes: 1684 /// 1) instantiating function templates 1685 /// 2) substituting friend declarations 1686 /// 3) substituting deduction guide declarations for nested class templates 1687 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 1688 TemplateParameterList *TemplateParams) { 1689 // Check whether there is already a function template specialization for 1690 // this declaration. 1691 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1692 if (FunctionTemplate && !TemplateParams) { 1693 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1694 1695 void *InsertPos = nullptr; 1696 FunctionDecl *SpecFunc 1697 = FunctionTemplate->findSpecialization(Innermost, InsertPos); 1698 1699 // If we already have a function template specialization, return it. 1700 if (SpecFunc) 1701 return SpecFunc; 1702 } 1703 1704 bool isFriend; 1705 if (FunctionTemplate) 1706 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1707 else 1708 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1709 1710 bool MergeWithParentScope = (TemplateParams != nullptr) || 1711 Owner->isFunctionOrMethod() || 1712 !(isa<Decl>(Owner) && 1713 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1714 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1715 1716 ExplicitSpecifier InstantiatedExplicitSpecifier; 1717 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) { 1718 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier( 1719 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide); 1720 if (InstantiatedExplicitSpecifier.isInvalid()) 1721 return nullptr; 1722 } 1723 1724 SmallVector<ParmVarDecl *, 4> Params; 1725 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1726 if (!TInfo) 1727 return nullptr; 1728 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 1729 1730 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1731 if (QualifierLoc) { 1732 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1733 TemplateArgs); 1734 if (!QualifierLoc) 1735 return nullptr; 1736 } 1737 1738 // If we're instantiating a local function declaration, put the result 1739 // in the enclosing namespace; otherwise we need to find the instantiated 1740 // context. 1741 DeclContext *DC; 1742 if (D->isLocalExternDecl()) { 1743 DC = Owner; 1744 SemaRef.adjustContextForLocalExternDecl(DC); 1745 } else if (isFriend && QualifierLoc) { 1746 CXXScopeSpec SS; 1747 SS.Adopt(QualifierLoc); 1748 DC = SemaRef.computeDeclContext(SS); 1749 if (!DC) return nullptr; 1750 } else { 1751 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 1752 TemplateArgs); 1753 } 1754 1755 DeclarationNameInfo NameInfo 1756 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1757 1758 FunctionDecl *Function; 1759 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) { 1760 Function = CXXDeductionGuideDecl::Create( 1761 SemaRef.Context, DC, D->getInnerLocStart(), 1762 InstantiatedExplicitSpecifier, NameInfo, T, TInfo, 1763 D->getSourceRange().getEnd()); 1764 if (DGuide->isCopyDeductionCandidate()) 1765 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate(); 1766 Function->setAccess(D->getAccess()); 1767 } else { 1768 Function = FunctionDecl::Create( 1769 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo, 1770 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(), 1771 D->hasWrittenPrototype(), D->isConstexpr()); 1772 Function->setRangeEnd(D->getSourceRange().getEnd()); 1773 } 1774 1775 if (D->isInlined()) 1776 Function->setImplicitlyInline(); 1777 1778 if (QualifierLoc) 1779 Function->setQualifierInfo(QualifierLoc); 1780 1781 if (D->isLocalExternDecl()) 1782 Function->setLocalExternDecl(); 1783 1784 DeclContext *LexicalDC = Owner; 1785 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) { 1786 assert(D->getDeclContext()->isFileContext()); 1787 LexicalDC = D->getDeclContext(); 1788 } 1789 1790 Function->setLexicalDeclContext(LexicalDC); 1791 1792 // Attach the parameters 1793 for (unsigned P = 0; P < Params.size(); ++P) 1794 if (Params[P]) 1795 Params[P]->setOwningFunction(Function); 1796 Function->setParams(Params); 1797 1798 if (TemplateParams) { 1799 // Our resulting instantiation is actually a function template, since we 1800 // are substituting only the outer template parameters. For example, given 1801 // 1802 // template<typename T> 1803 // struct X { 1804 // template<typename U> friend void f(T, U); 1805 // }; 1806 // 1807 // X<int> x; 1808 // 1809 // We are instantiating the friend function template "f" within X<int>, 1810 // which means substituting int for T, but leaving "f" as a friend function 1811 // template. 1812 // Build the function template itself. 1813 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1814 Function->getLocation(), 1815 Function->getDeclName(), 1816 TemplateParams, Function); 1817 Function->setDescribedFunctionTemplate(FunctionTemplate); 1818 1819 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1820 1821 if (isFriend && D->isThisDeclarationADefinition()) { 1822 FunctionTemplate->setInstantiatedFromMemberTemplate( 1823 D->getDescribedFunctionTemplate()); 1824 } 1825 } else if (FunctionTemplate) { 1826 // Record this function template specialization. 1827 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1828 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1829 TemplateArgumentList::CreateCopy(SemaRef.Context, 1830 Innermost), 1831 /*InsertPos=*/nullptr); 1832 } else if (isFriend && D->isThisDeclarationADefinition()) { 1833 // Do not connect the friend to the template unless it's actually a 1834 // definition. We don't want non-template functions to be marked as being 1835 // template instantiations. 1836 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1837 } 1838 1839 if (isFriend) 1840 Function->setObjectOfFriendDecl(); 1841 1842 if (InitFunctionInstantiation(Function, D)) 1843 Function->setInvalidDecl(); 1844 1845 bool IsExplicitSpecialization = false; 1846 1847 LookupResult Previous( 1848 SemaRef, Function->getDeclName(), SourceLocation(), 1849 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 1850 : Sema::LookupOrdinaryName, 1851 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration 1852 : SemaRef.forRedeclarationInCurContext()); 1853 1854 if (DependentFunctionTemplateSpecializationInfo *Info 1855 = D->getDependentSpecializationInfo()) { 1856 assert(isFriend && "non-friend has dependent specialization info?"); 1857 1858 // Instantiate the explicit template arguments. 1859 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1860 Info->getRAngleLoc()); 1861 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1862 ExplicitArgs, TemplateArgs)) 1863 return nullptr; 1864 1865 // Map the candidate templates to their instantiations. 1866 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1867 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1868 Info->getTemplate(I), 1869 TemplateArgs); 1870 if (!Temp) return nullptr; 1871 1872 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1873 } 1874 1875 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1876 &ExplicitArgs, 1877 Previous)) 1878 Function->setInvalidDecl(); 1879 1880 IsExplicitSpecialization = true; 1881 } else if (const ASTTemplateArgumentListInfo *Info = 1882 D->getTemplateSpecializationArgsAsWritten()) { 1883 // The name of this function was written as a template-id. 1884 SemaRef.LookupQualifiedName(Previous, DC); 1885 1886 // Instantiate the explicit template arguments. 1887 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1888 Info->getRAngleLoc()); 1889 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1890 ExplicitArgs, TemplateArgs)) 1891 return nullptr; 1892 1893 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1894 &ExplicitArgs, 1895 Previous)) 1896 Function->setInvalidDecl(); 1897 1898 IsExplicitSpecialization = true; 1899 } else if (TemplateParams || !FunctionTemplate) { 1900 // Look only into the namespace where the friend would be declared to 1901 // find a previous declaration. This is the innermost enclosing namespace, 1902 // as described in ActOnFriendFunctionDecl. 1903 SemaRef.LookupQualifiedName(Previous, DC); 1904 1905 // In C++, the previous declaration we find might be a tag type 1906 // (class or enum). In this case, the new declaration will hide the 1907 // tag type. Note that this does does not apply if we're declaring a 1908 // typedef (C++ [dcl.typedef]p4). 1909 if (Previous.isSingleTagDecl()) 1910 Previous.clear(); 1911 } 1912 1913 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous, 1914 IsExplicitSpecialization); 1915 1916 NamedDecl *PrincipalDecl = (TemplateParams 1917 ? cast<NamedDecl>(FunctionTemplate) 1918 : Function); 1919 1920 // If the original function was part of a friend declaration, 1921 // inherit its namespace state and add it to the owner. 1922 if (isFriend) { 1923 Function->setObjectOfFriendDecl(); 1924 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate()) 1925 FT->setObjectOfFriendDecl(); 1926 DC->makeDeclVisibleInContext(PrincipalDecl); 1927 1928 bool QueuedInstantiation = false; 1929 1930 // C++11 [temp.friend]p4 (DR329): 1931 // When a function is defined in a friend function declaration in a class 1932 // template, the function is instantiated when the function is odr-used. 1933 // The same restrictions on multiple declarations and definitions that 1934 // apply to non-template function declarations and definitions also apply 1935 // to these implicit definitions. 1936 if (D->isThisDeclarationADefinition()) { 1937 SemaRef.CheckForFunctionRedefinition(Function); 1938 if (!Function->isInvalidDecl()) { 1939 for (auto R : Function->redecls()) { 1940 if (R == Function) 1941 continue; 1942 1943 // If some prior declaration of this function has been used, we need 1944 // to instantiate its definition. 1945 if (!QueuedInstantiation && R->isUsed(false)) { 1946 if (MemberSpecializationInfo *MSInfo = 1947 Function->getMemberSpecializationInfo()) { 1948 if (MSInfo->getPointOfInstantiation().isInvalid()) { 1949 SourceLocation Loc = R->getLocation(); // FIXME 1950 MSInfo->setPointOfInstantiation(Loc); 1951 SemaRef.PendingLocalImplicitInstantiations.push_back( 1952 std::make_pair(Function, Loc)); 1953 QueuedInstantiation = true; 1954 } 1955 } 1956 } 1957 } 1958 } 1959 } 1960 1961 // Check the template parameter list against the previous declaration. The 1962 // goal here is to pick up default arguments added since the friend was 1963 // declared; we know the template parameter lists match, since otherwise 1964 // we would not have picked this template as the previous declaration. 1965 if (TemplateParams && FunctionTemplate->getPreviousDecl()) { 1966 SemaRef.CheckTemplateParameterList( 1967 TemplateParams, 1968 FunctionTemplate->getPreviousDecl()->getTemplateParameters(), 1969 Function->isThisDeclarationADefinition() 1970 ? Sema::TPC_FriendFunctionTemplateDefinition 1971 : Sema::TPC_FriendFunctionTemplate); 1972 } 1973 } 1974 1975 if (Function->isLocalExternDecl() && !Function->getPreviousDecl()) 1976 DC->makeDeclVisibleInContext(PrincipalDecl); 1977 1978 if (Function->isOverloadedOperator() && !DC->isRecord() && 1979 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1980 PrincipalDecl->setNonMemberOperator(); 1981 1982 assert(!D->isDefaulted() && "only methods should be defaulted"); 1983 return Function; 1984 } 1985 1986 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl( 1987 CXXMethodDecl *D, TemplateParameterList *TemplateParams, 1988 Optional<const ASTTemplateArgumentListInfo *> 1989 ClassScopeSpecializationArgs) { 1990 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1991 if (FunctionTemplate && !TemplateParams) { 1992 // We are creating a function template specialization from a function 1993 // template. Check whether there is already a function template 1994 // specialization for this particular set of template arguments. 1995 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1996 1997 void *InsertPos = nullptr; 1998 FunctionDecl *SpecFunc 1999 = FunctionTemplate->findSpecialization(Innermost, InsertPos); 2000 2001 // If we already have a function template specialization, return it. 2002 if (SpecFunc) 2003 return SpecFunc; 2004 } 2005 2006 bool isFriend; 2007 if (FunctionTemplate) 2008 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 2009 else 2010 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 2011 2012 bool MergeWithParentScope = (TemplateParams != nullptr) || 2013 !(isa<Decl>(Owner) && 2014 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 2015 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 2016 2017 // Instantiate enclosing template arguments for friends. 2018 SmallVector<TemplateParameterList *, 4> TempParamLists; 2019 unsigned NumTempParamLists = 0; 2020 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 2021 TempParamLists.resize(NumTempParamLists); 2022 for (unsigned I = 0; I != NumTempParamLists; ++I) { 2023 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 2024 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2025 if (!InstParams) 2026 return nullptr; 2027 TempParamLists[I] = InstParams; 2028 } 2029 } 2030 2031 ExplicitSpecifier InstantiatedExplicitSpecifier = 2032 instantiateExplicitSpecifier(SemaRef, TemplateArgs, 2033 ExplicitSpecifier::getFromDecl(D), D); 2034 if (InstantiatedExplicitSpecifier.isInvalid()) 2035 return nullptr; 2036 2037 SmallVector<ParmVarDecl *, 4> Params; 2038 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 2039 if (!TInfo) 2040 return nullptr; 2041 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 2042 2043 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 2044 if (QualifierLoc) { 2045 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 2046 TemplateArgs); 2047 if (!QualifierLoc) 2048 return nullptr; 2049 } 2050 2051 DeclContext *DC = Owner; 2052 if (isFriend) { 2053 if (QualifierLoc) { 2054 CXXScopeSpec SS; 2055 SS.Adopt(QualifierLoc); 2056 DC = SemaRef.computeDeclContext(SS); 2057 2058 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 2059 return nullptr; 2060 } else { 2061 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 2062 D->getDeclContext(), 2063 TemplateArgs); 2064 } 2065 if (!DC) return nullptr; 2066 } 2067 2068 // Build the instantiated method declaration. 2069 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 2070 CXXMethodDecl *Method = nullptr; 2071 2072 SourceLocation StartLoc = D->getInnerLocStart(); 2073 DeclarationNameInfo NameInfo 2074 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2075 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 2076 Method = CXXConstructorDecl::Create( 2077 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2078 InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false, 2079 Constructor->isConstexpr()); 2080 Method->setRangeEnd(Constructor->getEndLoc()); 2081 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 2082 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 2083 StartLoc, NameInfo, T, TInfo, 2084 Destructor->isInlineSpecified(), 2085 false); 2086 Method->setRangeEnd(Destructor->getEndLoc()); 2087 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 2088 Method = CXXConversionDecl::Create( 2089 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2090 Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier, 2091 Conversion->isConstexpr(), Conversion->getEndLoc()); 2092 } else { 2093 StorageClass SC = D->isStatic() ? SC_Static : SC_None; 2094 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo, 2095 T, TInfo, SC, D->isInlineSpecified(), 2096 D->isConstexpr(), D->getEndLoc()); 2097 } 2098 2099 if (D->isInlined()) 2100 Method->setImplicitlyInline(); 2101 2102 if (QualifierLoc) 2103 Method->setQualifierInfo(QualifierLoc); 2104 2105 if (TemplateParams) { 2106 // Our resulting instantiation is actually a function template, since we 2107 // are substituting only the outer template parameters. For example, given 2108 // 2109 // template<typename T> 2110 // struct X { 2111 // template<typename U> void f(T, U); 2112 // }; 2113 // 2114 // X<int> x; 2115 // 2116 // We are instantiating the member template "f" within X<int>, which means 2117 // substituting int for T, but leaving "f" as a member function template. 2118 // Build the function template itself. 2119 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 2120 Method->getLocation(), 2121 Method->getDeclName(), 2122 TemplateParams, Method); 2123 if (isFriend) { 2124 FunctionTemplate->setLexicalDeclContext(Owner); 2125 FunctionTemplate->setObjectOfFriendDecl(); 2126 } else if (D->isOutOfLine()) 2127 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 2128 Method->setDescribedFunctionTemplate(FunctionTemplate); 2129 } else if (FunctionTemplate) { 2130 // Record this function template specialization. 2131 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 2132 Method->setFunctionTemplateSpecialization(FunctionTemplate, 2133 TemplateArgumentList::CreateCopy(SemaRef.Context, 2134 Innermost), 2135 /*InsertPos=*/nullptr); 2136 } else if (!isFriend) { 2137 // Record that this is an instantiation of a member function. 2138 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 2139 } 2140 2141 // If we are instantiating a member function defined 2142 // out-of-line, the instantiation will have the same lexical 2143 // context (which will be a namespace scope) as the template. 2144 if (isFriend) { 2145 if (NumTempParamLists) 2146 Method->setTemplateParameterListsInfo( 2147 SemaRef.Context, 2148 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists)); 2149 2150 Method->setLexicalDeclContext(Owner); 2151 Method->setObjectOfFriendDecl(); 2152 } else if (D->isOutOfLine()) 2153 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 2154 2155 // Attach the parameters 2156 for (unsigned P = 0; P < Params.size(); ++P) 2157 Params[P]->setOwningFunction(Method); 2158 Method->setParams(Params); 2159 2160 if (InitMethodInstantiation(Method, D)) 2161 Method->setInvalidDecl(); 2162 2163 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 2164 Sema::ForExternalRedeclaration); 2165 2166 bool IsExplicitSpecialization = false; 2167 2168 // If the name of this function was written as a template-id, instantiate 2169 // the explicit template arguments. 2170 if (DependentFunctionTemplateSpecializationInfo *Info 2171 = D->getDependentSpecializationInfo()) { 2172 assert(isFriend && "non-friend has dependent specialization info?"); 2173 2174 // Instantiate the explicit template arguments. 2175 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2176 Info->getRAngleLoc()); 2177 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 2178 ExplicitArgs, TemplateArgs)) 2179 return nullptr; 2180 2181 // Map the candidate templates to their instantiations. 2182 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 2183 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 2184 Info->getTemplate(I), 2185 TemplateArgs); 2186 if (!Temp) return nullptr; 2187 2188 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 2189 } 2190 2191 if (SemaRef.CheckFunctionTemplateSpecialization(Method, 2192 &ExplicitArgs, 2193 Previous)) 2194 Method->setInvalidDecl(); 2195 2196 IsExplicitSpecialization = true; 2197 } else if (const ASTTemplateArgumentListInfo *Info = 2198 ClassScopeSpecializationArgs.getValueOr( 2199 D->getTemplateSpecializationArgsAsWritten())) { 2200 SemaRef.LookupQualifiedName(Previous, DC); 2201 2202 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2203 Info->getRAngleLoc()); 2204 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 2205 ExplicitArgs, TemplateArgs)) 2206 return nullptr; 2207 2208 if (SemaRef.CheckFunctionTemplateSpecialization(Method, 2209 &ExplicitArgs, 2210 Previous)) 2211 Method->setInvalidDecl(); 2212 2213 IsExplicitSpecialization = true; 2214 } else if (ClassScopeSpecializationArgs) { 2215 // Class-scope explicit specialization written without explicit template 2216 // arguments. 2217 SemaRef.LookupQualifiedName(Previous, DC); 2218 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous)) 2219 Method->setInvalidDecl(); 2220 2221 IsExplicitSpecialization = true; 2222 } else if (!FunctionTemplate || TemplateParams || isFriend) { 2223 SemaRef.LookupQualifiedName(Previous, Record); 2224 2225 // In C++, the previous declaration we find might be a tag type 2226 // (class or enum). In this case, the new declaration will hide the 2227 // tag type. Note that this does does not apply if we're declaring a 2228 // typedef (C++ [dcl.typedef]p4). 2229 if (Previous.isSingleTagDecl()) 2230 Previous.clear(); 2231 } 2232 2233 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, 2234 IsExplicitSpecialization); 2235 2236 if (D->isPure()) 2237 SemaRef.CheckPureMethod(Method, SourceRange()); 2238 2239 // Propagate access. For a non-friend declaration, the access is 2240 // whatever we're propagating from. For a friend, it should be the 2241 // previous declaration we just found. 2242 if (isFriend && Method->getPreviousDecl()) 2243 Method->setAccess(Method->getPreviousDecl()->getAccess()); 2244 else 2245 Method->setAccess(D->getAccess()); 2246 if (FunctionTemplate) 2247 FunctionTemplate->setAccess(Method->getAccess()); 2248 2249 SemaRef.CheckOverrideControl(Method); 2250 2251 // If a function is defined as defaulted or deleted, mark it as such now. 2252 if (D->isExplicitlyDefaulted()) 2253 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 2254 if (D->isDeletedAsWritten()) 2255 SemaRef.SetDeclDeleted(Method, Method->getLocation()); 2256 2257 // If this is an explicit specialization, mark the implicitly-instantiated 2258 // template specialization as being an explicit specialization too. 2259 // FIXME: Is this necessary? 2260 if (IsExplicitSpecialization && !isFriend) 2261 SemaRef.CompleteMemberSpecialization(Method, Previous); 2262 2263 // If there's a function template, let our caller handle it. 2264 if (FunctionTemplate) { 2265 // do nothing 2266 2267 // Don't hide a (potentially) valid declaration with an invalid one. 2268 } else if (Method->isInvalidDecl() && !Previous.empty()) { 2269 // do nothing 2270 2271 // Otherwise, check access to friends and make them visible. 2272 } else if (isFriend) { 2273 // We only need to re-check access for methods which we didn't 2274 // manage to match during parsing. 2275 if (!D->getPreviousDecl()) 2276 SemaRef.CheckFriendAccess(Method); 2277 2278 Record->makeDeclVisibleInContext(Method); 2279 2280 // Otherwise, add the declaration. We don't need to do this for 2281 // class-scope specializations because we'll have matched them with 2282 // the appropriate template. 2283 } else { 2284 Owner->addDecl(Method); 2285 } 2286 2287 // PR17480: Honor the used attribute to instantiate member function 2288 // definitions 2289 if (Method->hasAttr<UsedAttr>()) { 2290 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) { 2291 SourceLocation Loc; 2292 if (const MemberSpecializationInfo *MSInfo = 2293 A->getMemberSpecializationInfo()) 2294 Loc = MSInfo->getPointOfInstantiation(); 2295 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A)) 2296 Loc = Spec->getPointOfInstantiation(); 2297 SemaRef.MarkFunctionReferenced(Loc, Method); 2298 } 2299 } 2300 2301 return Method; 2302 } 2303 2304 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 2305 return VisitCXXMethodDecl(D); 2306 } 2307 2308 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 2309 return VisitCXXMethodDecl(D); 2310 } 2311 2312 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 2313 return VisitCXXMethodDecl(D); 2314 } 2315 2316 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 2317 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None, 2318 /*ExpectParameterPack=*/ false); 2319 } 2320 2321 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 2322 TemplateTypeParmDecl *D) { 2323 // TODO: don't always clone when decls are refcounted. 2324 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 2325 2326 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create( 2327 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(), 2328 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(), 2329 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack()); 2330 Inst->setAccess(AS_public); 2331 2332 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2333 TypeSourceInfo *InstantiatedDefaultArg = 2334 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, 2335 D->getDefaultArgumentLoc(), D->getDeclName()); 2336 if (InstantiatedDefaultArg) 2337 Inst->setDefaultArgument(InstantiatedDefaultArg); 2338 } 2339 2340 // Introduce this template parameter's instantiation into the instantiation 2341 // scope. 2342 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 2343 2344 return Inst; 2345 } 2346 2347 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 2348 NonTypeTemplateParmDecl *D) { 2349 // Substitute into the type of the non-type template parameter. 2350 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 2351 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 2352 SmallVector<QualType, 4> ExpandedParameterPackTypes; 2353 bool IsExpandedParameterPack = false; 2354 TypeSourceInfo *DI; 2355 QualType T; 2356 bool Invalid = false; 2357 2358 if (D->isExpandedParameterPack()) { 2359 // The non-type template parameter pack is an already-expanded pack 2360 // expansion of types. Substitute into each of the expanded types. 2361 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 2362 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 2363 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 2364 TypeSourceInfo *NewDI = 2365 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs, 2366 D->getLocation(), D->getDeclName()); 2367 if (!NewDI) 2368 return nullptr; 2369 2370 QualType NewT = 2371 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2372 if (NewT.isNull()) 2373 return nullptr; 2374 2375 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2376 ExpandedParameterPackTypes.push_back(NewT); 2377 } 2378 2379 IsExpandedParameterPack = true; 2380 DI = D->getTypeSourceInfo(); 2381 T = DI->getType(); 2382 } else if (D->isPackExpansion()) { 2383 // The non-type template parameter pack's type is a pack expansion of types. 2384 // Determine whether we need to expand this parameter pack into separate 2385 // types. 2386 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); 2387 TypeLoc Pattern = Expansion.getPatternLoc(); 2388 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2389 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 2390 2391 // Determine whether the set of unexpanded parameter packs can and should 2392 // be expanded. 2393 bool Expand = true; 2394 bool RetainExpansion = false; 2395 Optional<unsigned> OrigNumExpansions 2396 = Expansion.getTypePtr()->getNumExpansions(); 2397 Optional<unsigned> NumExpansions = OrigNumExpansions; 2398 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 2399 Pattern.getSourceRange(), 2400 Unexpanded, 2401 TemplateArgs, 2402 Expand, RetainExpansion, 2403 NumExpansions)) 2404 return nullptr; 2405 2406 if (Expand) { 2407 for (unsigned I = 0; I != *NumExpansions; ++I) { 2408 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2409 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 2410 D->getLocation(), 2411 D->getDeclName()); 2412 if (!NewDI) 2413 return nullptr; 2414 2415 QualType NewT = 2416 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2417 if (NewT.isNull()) 2418 return nullptr; 2419 2420 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2421 ExpandedParameterPackTypes.push_back(NewT); 2422 } 2423 2424 // Note that we have an expanded parameter pack. The "type" of this 2425 // expanded parameter pack is the original expansion type, but callers 2426 // will end up using the expanded parameter pack types for type-checking. 2427 IsExpandedParameterPack = true; 2428 DI = D->getTypeSourceInfo(); 2429 T = DI->getType(); 2430 } else { 2431 // We cannot fully expand the pack expansion now, so substitute into the 2432 // pattern and create a new pack expansion type. 2433 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2434 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 2435 D->getLocation(), 2436 D->getDeclName()); 2437 if (!NewPattern) 2438 return nullptr; 2439 2440 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation()); 2441 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 2442 NumExpansions); 2443 if (!DI) 2444 return nullptr; 2445 2446 T = DI->getType(); 2447 } 2448 } else { 2449 // Simple case: substitution into a parameter that is not a parameter pack. 2450 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 2451 D->getLocation(), D->getDeclName()); 2452 if (!DI) 2453 return nullptr; 2454 2455 // Check that this type is acceptable for a non-type template parameter. 2456 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation()); 2457 if (T.isNull()) { 2458 T = SemaRef.Context.IntTy; 2459 Invalid = true; 2460 } 2461 } 2462 2463 NonTypeTemplateParmDecl *Param; 2464 if (IsExpandedParameterPack) 2465 Param = NonTypeTemplateParmDecl::Create( 2466 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2467 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2468 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes, 2469 ExpandedParameterPackTypesAsWritten); 2470 else 2471 Param = NonTypeTemplateParmDecl::Create( 2472 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2473 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2474 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI); 2475 2476 Param->setAccess(AS_public); 2477 if (Invalid) 2478 Param->setInvalidDecl(); 2479 2480 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2481 EnterExpressionEvaluationContext ConstantEvaluated( 2482 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 2483 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs); 2484 if (!Value.isInvalid()) 2485 Param->setDefaultArgument(Value.get()); 2486 } 2487 2488 // Introduce this template parameter's instantiation into the instantiation 2489 // scope. 2490 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2491 return Param; 2492 } 2493 2494 static void collectUnexpandedParameterPacks( 2495 Sema &S, 2496 TemplateParameterList *Params, 2497 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 2498 for (const auto &P : *Params) { 2499 if (P->isTemplateParameterPack()) 2500 continue; 2501 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) 2502 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), 2503 Unexpanded); 2504 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P)) 2505 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), 2506 Unexpanded); 2507 } 2508 } 2509 2510 Decl * 2511 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 2512 TemplateTemplateParmDecl *D) { 2513 // Instantiate the template parameter list of the template template parameter. 2514 TemplateParameterList *TempParams = D->getTemplateParameters(); 2515 TemplateParameterList *InstParams; 2516 SmallVector<TemplateParameterList*, 8> ExpandedParams; 2517 2518 bool IsExpandedParameterPack = false; 2519 2520 if (D->isExpandedParameterPack()) { 2521 // The template template parameter pack is an already-expanded pack 2522 // expansion of template parameters. Substitute into each of the expanded 2523 // parameters. 2524 ExpandedParams.reserve(D->getNumExpansionTemplateParameters()); 2525 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 2526 I != N; ++I) { 2527 LocalInstantiationScope Scope(SemaRef); 2528 TemplateParameterList *Expansion = 2529 SubstTemplateParams(D->getExpansionTemplateParameters(I)); 2530 if (!Expansion) 2531 return nullptr; 2532 ExpandedParams.push_back(Expansion); 2533 } 2534 2535 IsExpandedParameterPack = true; 2536 InstParams = TempParams; 2537 } else if (D->isPackExpansion()) { 2538 // The template template parameter pack expands to a pack of template 2539 // template parameters. Determine whether we need to expand this parameter 2540 // pack into separate parameters. 2541 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2542 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), 2543 Unexpanded); 2544 2545 // Determine whether the set of unexpanded parameter packs can and should 2546 // be expanded. 2547 bool Expand = true; 2548 bool RetainExpansion = false; 2549 Optional<unsigned> NumExpansions; 2550 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), 2551 TempParams->getSourceRange(), 2552 Unexpanded, 2553 TemplateArgs, 2554 Expand, RetainExpansion, 2555 NumExpansions)) 2556 return nullptr; 2557 2558 if (Expand) { 2559 for (unsigned I = 0; I != *NumExpansions; ++I) { 2560 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2561 LocalInstantiationScope Scope(SemaRef); 2562 TemplateParameterList *Expansion = SubstTemplateParams(TempParams); 2563 if (!Expansion) 2564 return nullptr; 2565 ExpandedParams.push_back(Expansion); 2566 } 2567 2568 // Note that we have an expanded parameter pack. The "type" of this 2569 // expanded parameter pack is the original expansion type, but callers 2570 // will end up using the expanded parameter pack types for type-checking. 2571 IsExpandedParameterPack = true; 2572 InstParams = TempParams; 2573 } else { 2574 // We cannot fully expand the pack expansion now, so just substitute 2575 // into the pattern. 2576 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2577 2578 LocalInstantiationScope Scope(SemaRef); 2579 InstParams = SubstTemplateParams(TempParams); 2580 if (!InstParams) 2581 return nullptr; 2582 } 2583 } else { 2584 // Perform the actual substitution of template parameters within a new, 2585 // local instantiation scope. 2586 LocalInstantiationScope Scope(SemaRef); 2587 InstParams = SubstTemplateParams(TempParams); 2588 if (!InstParams) 2589 return nullptr; 2590 } 2591 2592 // Build the template template parameter. 2593 TemplateTemplateParmDecl *Param; 2594 if (IsExpandedParameterPack) 2595 Param = TemplateTemplateParmDecl::Create( 2596 SemaRef.Context, Owner, D->getLocation(), 2597 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2598 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams); 2599 else 2600 Param = TemplateTemplateParmDecl::Create( 2601 SemaRef.Context, Owner, D->getLocation(), 2602 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2603 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams); 2604 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2605 NestedNameSpecifierLoc QualifierLoc = 2606 D->getDefaultArgument().getTemplateQualifierLoc(); 2607 QualifierLoc = 2608 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs); 2609 TemplateName TName = SemaRef.SubstTemplateName( 2610 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(), 2611 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); 2612 if (!TName.isNull()) 2613 Param->setDefaultArgument( 2614 SemaRef.Context, 2615 TemplateArgumentLoc(TemplateArgument(TName), 2616 D->getDefaultArgument().getTemplateQualifierLoc(), 2617 D->getDefaultArgument().getTemplateNameLoc())); 2618 } 2619 Param->setAccess(AS_public); 2620 2621 // Introduce this template parameter's instantiation into the instantiation 2622 // scope. 2623 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2624 2625 return Param; 2626 } 2627 2628 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 2629 // Using directives are never dependent (and never contain any types or 2630 // expressions), so they require no explicit instantiation work. 2631 2632 UsingDirectiveDecl *Inst 2633 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 2634 D->getNamespaceKeyLocation(), 2635 D->getQualifierLoc(), 2636 D->getIdentLocation(), 2637 D->getNominatedNamespace(), 2638 D->getCommonAncestor()); 2639 2640 // Add the using directive to its declaration context 2641 // only if this is not a function or method. 2642 if (!Owner->isFunctionOrMethod()) 2643 Owner->addDecl(Inst); 2644 2645 return Inst; 2646 } 2647 2648 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 2649 2650 // The nested name specifier may be dependent, for example 2651 // template <typename T> struct t { 2652 // struct s1 { T f1(); }; 2653 // struct s2 : s1 { using s1::f1; }; 2654 // }; 2655 // template struct t<int>; 2656 // Here, in using s1::f1, s1 refers to t<T>::s1; 2657 // we need to substitute for t<int>::s1. 2658 NestedNameSpecifierLoc QualifierLoc 2659 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2660 TemplateArgs); 2661 if (!QualifierLoc) 2662 return nullptr; 2663 2664 // For an inheriting constructor declaration, the name of the using 2665 // declaration is the name of a constructor in this class, not in the 2666 // base class. 2667 DeclarationNameInfo NameInfo = D->getNameInfo(); 2668 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 2669 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext)) 2670 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName( 2671 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD)))); 2672 2673 // We only need to do redeclaration lookups if we're in a class 2674 // scope (in fact, it's not really even possible in non-class 2675 // scopes). 2676 bool CheckRedeclaration = Owner->isRecord(); 2677 2678 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 2679 Sema::ForVisibleRedeclaration); 2680 2681 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 2682 D->getUsingLoc(), 2683 QualifierLoc, 2684 NameInfo, 2685 D->hasTypename()); 2686 2687 CXXScopeSpec SS; 2688 SS.Adopt(QualifierLoc); 2689 if (CheckRedeclaration) { 2690 Prev.setHideTags(false); 2691 SemaRef.LookupQualifiedName(Prev, Owner); 2692 2693 // Check for invalid redeclarations. 2694 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(), 2695 D->hasTypename(), SS, 2696 D->getLocation(), Prev)) 2697 NewUD->setInvalidDecl(); 2698 2699 } 2700 2701 if (!NewUD->isInvalidDecl() && 2702 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), 2703 SS, NameInfo, D->getLocation())) 2704 NewUD->setInvalidDecl(); 2705 2706 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 2707 NewUD->setAccess(D->getAccess()); 2708 Owner->addDecl(NewUD); 2709 2710 // Don't process the shadow decls for an invalid decl. 2711 if (NewUD->isInvalidDecl()) 2712 return NewUD; 2713 2714 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 2715 SemaRef.CheckInheritingConstructorUsingDecl(NewUD); 2716 2717 bool isFunctionScope = Owner->isFunctionOrMethod(); 2718 2719 // Process the shadow decls. 2720 for (auto *Shadow : D->shadows()) { 2721 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so 2722 // reconstruct it in the case where it matters. 2723 NamedDecl *OldTarget = Shadow->getTargetDecl(); 2724 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow)) 2725 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl()) 2726 OldTarget = BaseShadow; 2727 2728 NamedDecl *InstTarget = 2729 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 2730 Shadow->getLocation(), OldTarget, TemplateArgs)); 2731 if (!InstTarget) 2732 return nullptr; 2733 2734 UsingShadowDecl *PrevDecl = nullptr; 2735 if (CheckRedeclaration) { 2736 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl)) 2737 continue; 2738 } else if (UsingShadowDecl *OldPrev = 2739 getPreviousDeclForInstantiation(Shadow)) { 2740 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( 2741 Shadow->getLocation(), OldPrev, TemplateArgs)); 2742 } 2743 2744 UsingShadowDecl *InstShadow = 2745 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget, 2746 PrevDecl); 2747 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 2748 2749 if (isFunctionScope) 2750 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 2751 } 2752 2753 return NewUD; 2754 } 2755 2756 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 2757 // Ignore these; we handle them in bulk when processing the UsingDecl. 2758 return nullptr; 2759 } 2760 2761 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl( 2762 ConstructorUsingShadowDecl *D) { 2763 // Ignore these; we handle them in bulk when processing the UsingDecl. 2764 return nullptr; 2765 } 2766 2767 template <typename T> 2768 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl( 2769 T *D, bool InstantiatingPackElement) { 2770 // If this is a pack expansion, expand it now. 2771 if (D->isPackExpansion() && !InstantiatingPackElement) { 2772 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2773 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded); 2774 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded); 2775 2776 // Determine whether the set of unexpanded parameter packs can and should 2777 // be expanded. 2778 bool Expand = true; 2779 bool RetainExpansion = false; 2780 Optional<unsigned> NumExpansions; 2781 if (SemaRef.CheckParameterPacksForExpansion( 2782 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs, 2783 Expand, RetainExpansion, NumExpansions)) 2784 return nullptr; 2785 2786 // This declaration cannot appear within a function template signature, 2787 // so we can't have a partial argument list for a parameter pack. 2788 assert(!RetainExpansion && 2789 "should never need to retain an expansion for UsingPackDecl"); 2790 2791 if (!Expand) { 2792 // We cannot fully expand the pack expansion now, so substitute into the 2793 // pattern and create a new pack expansion. 2794 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2795 return instantiateUnresolvedUsingDecl(D, true); 2796 } 2797 2798 // Within a function, we don't have any normal way to check for conflicts 2799 // between shadow declarations from different using declarations in the 2800 // same pack expansion, but this is always ill-formed because all expansions 2801 // must produce (conflicting) enumerators. 2802 // 2803 // Sadly we can't just reject this in the template definition because it 2804 // could be valid if the pack is empty or has exactly one expansion. 2805 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) { 2806 SemaRef.Diag(D->getEllipsisLoc(), 2807 diag::err_using_decl_redeclaration_expansion); 2808 return nullptr; 2809 } 2810 2811 // Instantiate the slices of this pack and build a UsingPackDecl. 2812 SmallVector<NamedDecl*, 8> Expansions; 2813 for (unsigned I = 0; I != *NumExpansions; ++I) { 2814 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2815 Decl *Slice = instantiateUnresolvedUsingDecl(D, true); 2816 if (!Slice) 2817 return nullptr; 2818 // Note that we can still get unresolved using declarations here, if we 2819 // had arguments for all packs but the pattern also contained other 2820 // template arguments (this only happens during partial substitution, eg 2821 // into the body of a generic lambda in a function template). 2822 Expansions.push_back(cast<NamedDecl>(Slice)); 2823 } 2824 2825 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 2826 if (isDeclWithinFunction(D)) 2827 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 2828 return NewD; 2829 } 2830 2831 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D); 2832 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation(); 2833 2834 NestedNameSpecifierLoc QualifierLoc 2835 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2836 TemplateArgs); 2837 if (!QualifierLoc) 2838 return nullptr; 2839 2840 CXXScopeSpec SS; 2841 SS.Adopt(QualifierLoc); 2842 2843 DeclarationNameInfo NameInfo 2844 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2845 2846 // Produce a pack expansion only if we're not instantiating a particular 2847 // slice of a pack expansion. 2848 bool InstantiatingSlice = D->getEllipsisLoc().isValid() && 2849 SemaRef.ArgumentPackSubstitutionIndex != -1; 2850 SourceLocation EllipsisLoc = 2851 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc(); 2852 2853 NamedDecl *UD = SemaRef.BuildUsingDeclaration( 2854 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(), 2855 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc, 2856 ParsedAttributesView(), 2857 /*IsInstantiation*/ true); 2858 if (UD) 2859 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D); 2860 2861 return UD; 2862 } 2863 2864 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl( 2865 UnresolvedUsingTypenameDecl *D) { 2866 return instantiateUnresolvedUsingDecl(D); 2867 } 2868 2869 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl( 2870 UnresolvedUsingValueDecl *D) { 2871 return instantiateUnresolvedUsingDecl(D); 2872 } 2873 2874 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) { 2875 SmallVector<NamedDecl*, 8> Expansions; 2876 for (auto *UD : D->expansions()) { 2877 if (NamedDecl *NewUD = 2878 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs)) 2879 Expansions.push_back(NewUD); 2880 else 2881 return nullptr; 2882 } 2883 2884 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 2885 if (isDeclWithinFunction(D)) 2886 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 2887 return NewD; 2888 } 2889 2890 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 2891 ClassScopeFunctionSpecializationDecl *Decl) { 2892 CXXMethodDecl *OldFD = Decl->getSpecialization(); 2893 return cast_or_null<CXXMethodDecl>( 2894 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten())); 2895 } 2896 2897 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( 2898 OMPThreadPrivateDecl *D) { 2899 SmallVector<Expr *, 5> Vars; 2900 for (auto *I : D->varlists()) { 2901 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 2902 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"); 2903 Vars.push_back(Var); 2904 } 2905 2906 OMPThreadPrivateDecl *TD = 2907 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars); 2908 2909 TD->setAccess(AS_public); 2910 Owner->addDecl(TD); 2911 2912 return TD; 2913 } 2914 2915 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) { 2916 SmallVector<Expr *, 5> Vars; 2917 for (auto *I : D->varlists()) { 2918 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 2919 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr"); 2920 Vars.push_back(Var); 2921 } 2922 SmallVector<OMPClause *, 4> Clauses; 2923 // Copy map clauses from the original mapper. 2924 for (OMPClause *C : D->clauselists()) { 2925 auto *AC = cast<OMPAllocatorClause>(C); 2926 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs); 2927 if (!NewE.isUsable()) 2928 continue; 2929 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause( 2930 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc()); 2931 Clauses.push_back(IC); 2932 } 2933 2934 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective( 2935 D->getLocation(), Vars, Clauses, Owner); 2936 if (Res.get().isNull()) 2937 return nullptr; 2938 return Res.get().getSingleDecl(); 2939 } 2940 2941 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) { 2942 llvm_unreachable( 2943 "Requires directive cannot be instantiated within a dependent context"); 2944 } 2945 2946 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl( 2947 OMPDeclareReductionDecl *D) { 2948 // Instantiate type and check if it is allowed. 2949 const bool RequiresInstantiation = 2950 D->getType()->isDependentType() || 2951 D->getType()->isInstantiationDependentType() || 2952 D->getType()->containsUnexpandedParameterPack(); 2953 QualType SubstReductionType; 2954 if (RequiresInstantiation) { 2955 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType( 2956 D->getLocation(), 2957 ParsedType::make(SemaRef.SubstType( 2958 D->getType(), TemplateArgs, D->getLocation(), DeclarationName()))); 2959 } else { 2960 SubstReductionType = D->getType(); 2961 } 2962 if (SubstReductionType.isNull()) 2963 return nullptr; 2964 bool IsCorrect = !SubstReductionType.isNull(); 2965 // Create instantiated copy. 2966 std::pair<QualType, SourceLocation> ReductionTypes[] = { 2967 std::make_pair(SubstReductionType, D->getLocation())}; 2968 auto *PrevDeclInScope = D->getPrevDeclInScope(); 2969 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 2970 PrevDeclInScope = cast<OMPDeclareReductionDecl>( 2971 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 2972 ->get<Decl *>()); 2973 } 2974 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart( 2975 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(), 2976 PrevDeclInScope); 2977 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl()); 2978 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD); 2979 if (!RequiresInstantiation) { 2980 if (Expr *Combiner = D->getCombiner()) { 2981 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut()); 2982 NewDRD->setCombiner(Combiner); 2983 if (Expr *Init = D->getInitializer()) { 2984 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv()); 2985 NewDRD->setInitializer(Init, D->getInitializerKind()); 2986 } 2987 } 2988 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd( 2989 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl()); 2990 return NewDRD; 2991 } 2992 Expr *SubstCombiner = nullptr; 2993 Expr *SubstInitializer = nullptr; 2994 // Combiners instantiation sequence. 2995 if (D->getCombiner()) { 2996 SemaRef.ActOnOpenMPDeclareReductionCombinerStart( 2997 /*S=*/nullptr, NewDRD); 2998 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 2999 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(), 3000 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl()); 3001 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3002 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(), 3003 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl()); 3004 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3005 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3006 ThisContext); 3007 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get(); 3008 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner); 3009 // Initializers instantiation sequence. 3010 if (D->getInitializer()) { 3011 VarDecl *OmpPrivParm = 3012 SemaRef.ActOnOpenMPDeclareReductionInitializerStart( 3013 /*S=*/nullptr, NewDRD); 3014 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3015 cast<DeclRefExpr>(D->getInitOrig())->getDecl(), 3016 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl()); 3017 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3018 cast<DeclRefExpr>(D->getInitPriv())->getDecl(), 3019 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl()); 3020 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) { 3021 SubstInitializer = 3022 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get(); 3023 } else { 3024 IsCorrect = IsCorrect && OmpPrivParm->hasInit(); 3025 } 3026 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd( 3027 NewDRD, SubstInitializer, OmpPrivParm); 3028 } 3029 IsCorrect = 3030 IsCorrect && SubstCombiner && 3031 (!D->getInitializer() || 3032 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit && 3033 SubstInitializer) || 3034 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit && 3035 !SubstInitializer && !SubstInitializer)); 3036 } else { 3037 IsCorrect = false; 3038 } 3039 3040 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD, 3041 IsCorrect); 3042 3043 return NewDRD; 3044 } 3045 3046 Decl * 3047 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) { 3048 // Instantiate type and check if it is allowed. 3049 const bool RequiresInstantiation = 3050 D->getType()->isDependentType() || 3051 D->getType()->isInstantiationDependentType() || 3052 D->getType()->containsUnexpandedParameterPack(); 3053 QualType SubstMapperTy; 3054 DeclarationName VN = D->getVarName(); 3055 if (RequiresInstantiation) { 3056 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType( 3057 D->getLocation(), 3058 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs, 3059 D->getLocation(), VN))); 3060 } else { 3061 SubstMapperTy = D->getType(); 3062 } 3063 if (SubstMapperTy.isNull()) 3064 return nullptr; 3065 // Create an instantiated copy of mapper. 3066 auto *PrevDeclInScope = D->getPrevDeclInScope(); 3067 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 3068 PrevDeclInScope = cast<OMPDeclareMapperDecl>( 3069 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 3070 ->get<Decl *>()); 3071 } 3072 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart( 3073 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(), 3074 VN, D->getAccess(), PrevDeclInScope); 3075 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD); 3076 SmallVector<OMPClause *, 6> Clauses; 3077 bool IsCorrect = true; 3078 if (!RequiresInstantiation) { 3079 // Copy the mapper variable. 3080 NewDMD->setMapperVarRef(D->getMapperVarRef()); 3081 // Copy map clauses from the original mapper. 3082 for (OMPClause *C : D->clauselists()) 3083 Clauses.push_back(C); 3084 } else { 3085 // Instantiate the mapper variable. 3086 DeclarationNameInfo DirName; 3087 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr, 3088 (*D->clauselist_begin())->getBeginLoc()); 3089 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl( 3090 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN); 3091 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3092 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(), 3093 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl()); 3094 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3095 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3096 ThisContext); 3097 // Instantiate map clauses. 3098 for (OMPClause *C : D->clauselists()) { 3099 auto *OldC = cast<OMPMapClause>(C); 3100 SmallVector<Expr *, 4> NewVars; 3101 for (Expr *OE : OldC->varlists()) { 3102 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get(); 3103 if (!NE) { 3104 IsCorrect = false; 3105 break; 3106 } 3107 NewVars.push_back(NE); 3108 } 3109 if (!IsCorrect) 3110 break; 3111 NestedNameSpecifierLoc NewQualifierLoc = 3112 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(), 3113 TemplateArgs); 3114 CXXScopeSpec SS; 3115 SS.Adopt(NewQualifierLoc); 3116 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo( 3117 OldC->getMapperIdInfo(), TemplateArgs); 3118 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(), 3119 OldC->getEndLoc()); 3120 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause( 3121 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS, 3122 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(), 3123 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs); 3124 Clauses.push_back(NewC); 3125 } 3126 SemaRef.EndOpenMPDSABlock(nullptr); 3127 } 3128 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr, 3129 Clauses); 3130 if (!IsCorrect) 3131 return nullptr; 3132 return NewDMD; 3133 } 3134 3135 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl( 3136 OMPCapturedExprDecl * /*D*/) { 3137 llvm_unreachable("Should not be met in templates"); 3138 } 3139 3140 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 3141 return VisitFunctionDecl(D, nullptr); 3142 } 3143 3144 Decl * 3145 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { 3146 Decl *Inst = VisitFunctionDecl(D, nullptr); 3147 if (Inst && !D->getDescribedFunctionTemplate()) 3148 Owner->addDecl(Inst); 3149 return Inst; 3150 } 3151 3152 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 3153 return VisitCXXMethodDecl(D, nullptr); 3154 } 3155 3156 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 3157 llvm_unreachable("There are only CXXRecordDecls in C++"); 3158 } 3159 3160 Decl * 3161 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 3162 ClassTemplateSpecializationDecl *D) { 3163 // As a MS extension, we permit class-scope explicit specialization 3164 // of member class templates. 3165 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 3166 assert(ClassTemplate->getDeclContext()->isRecord() && 3167 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 3168 "can only instantiate an explicit specialization " 3169 "for a member class template"); 3170 3171 // Lookup the already-instantiated declaration in the instantiation 3172 // of the class template. 3173 ClassTemplateDecl *InstClassTemplate = 3174 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl( 3175 D->getLocation(), ClassTemplate, TemplateArgs)); 3176 if (!InstClassTemplate) 3177 return nullptr; 3178 3179 // Substitute into the template arguments of the class template explicit 3180 // specialization. 3181 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). 3182 castAs<TemplateSpecializationTypeLoc>(); 3183 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), 3184 Loc.getRAngleLoc()); 3185 SmallVector<TemplateArgumentLoc, 4> ArgLocs; 3186 for (unsigned I = 0; I != Loc.getNumArgs(); ++I) 3187 ArgLocs.push_back(Loc.getArgLoc(I)); 3188 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(), 3189 InstTemplateArgs, TemplateArgs)) 3190 return nullptr; 3191 3192 // Check that the template argument list is well-formed for this 3193 // class template. 3194 SmallVector<TemplateArgument, 4> Converted; 3195 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, 3196 D->getLocation(), 3197 InstTemplateArgs, 3198 false, 3199 Converted)) 3200 return nullptr; 3201 3202 // Figure out where to insert this class template explicit specialization 3203 // in the member template's set of class template explicit specializations. 3204 void *InsertPos = nullptr; 3205 ClassTemplateSpecializationDecl *PrevDecl = 3206 InstClassTemplate->findSpecialization(Converted, InsertPos); 3207 3208 // Check whether we've already seen a conflicting instantiation of this 3209 // declaration (for instance, if there was a prior implicit instantiation). 3210 bool Ignored; 3211 if (PrevDecl && 3212 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(), 3213 D->getSpecializationKind(), 3214 PrevDecl, 3215 PrevDecl->getSpecializationKind(), 3216 PrevDecl->getPointOfInstantiation(), 3217 Ignored)) 3218 return nullptr; 3219 3220 // If PrevDecl was a definition and D is also a definition, diagnose. 3221 // This happens in cases like: 3222 // 3223 // template<typename T, typename U> 3224 // struct Outer { 3225 // template<typename X> struct Inner; 3226 // template<> struct Inner<T> {}; 3227 // template<> struct Inner<U> {}; 3228 // }; 3229 // 3230 // Outer<int, int> outer; // error: the explicit specializations of Inner 3231 // // have the same signature. 3232 if (PrevDecl && PrevDecl->getDefinition() && 3233 D->isThisDeclarationADefinition()) { 3234 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; 3235 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), 3236 diag::note_previous_definition); 3237 return nullptr; 3238 } 3239 3240 // Create the class template partial specialization declaration. 3241 ClassTemplateSpecializationDecl *InstD = 3242 ClassTemplateSpecializationDecl::Create( 3243 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(), 3244 D->getLocation(), InstClassTemplate, Converted, PrevDecl); 3245 3246 // Add this partial specialization to the set of class template partial 3247 // specializations. 3248 if (!PrevDecl) 3249 InstClassTemplate->AddSpecialization(InstD, InsertPos); 3250 3251 // Substitute the nested name specifier, if any. 3252 if (SubstQualifier(D, InstD)) 3253 return nullptr; 3254 3255 // Build the canonical type that describes the converted template 3256 // arguments of the class template explicit specialization. 3257 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3258 TemplateName(InstClassTemplate), Converted, 3259 SemaRef.Context.getRecordType(InstD)); 3260 3261 // Build the fully-sugared type for this class template 3262 // specialization as the user wrote in the specialization 3263 // itself. This means that we'll pretty-print the type retrieved 3264 // from the specialization's declaration the way that the user 3265 // actually wrote the specialization, rather than formatting the 3266 // name based on the "canonical" representation used to store the 3267 // template arguments in the specialization. 3268 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3269 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs, 3270 CanonType); 3271 3272 InstD->setAccess(D->getAccess()); 3273 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 3274 InstD->setSpecializationKind(D->getSpecializationKind()); 3275 InstD->setTypeAsWritten(WrittenTy); 3276 InstD->setExternLoc(D->getExternLoc()); 3277 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); 3278 3279 Owner->addDecl(InstD); 3280 3281 // Instantiate the members of the class-scope explicit specialization eagerly. 3282 // We don't have support for lazy instantiation of an explicit specialization 3283 // yet, and MSVC eagerly instantiates in this case. 3284 // FIXME: This is wrong in standard C++. 3285 if (D->isThisDeclarationADefinition() && 3286 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs, 3287 TSK_ImplicitInstantiation, 3288 /*Complain=*/true)) 3289 return nullptr; 3290 3291 return InstD; 3292 } 3293 3294 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3295 VarTemplateSpecializationDecl *D) { 3296 3297 TemplateArgumentListInfo VarTemplateArgsInfo; 3298 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 3299 assert(VarTemplate && 3300 "A template specialization without specialized template?"); 3301 3302 VarTemplateDecl *InstVarTemplate = 3303 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl( 3304 D->getLocation(), VarTemplate, TemplateArgs)); 3305 if (!InstVarTemplate) 3306 return nullptr; 3307 3308 // Substitute the current template arguments. 3309 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 3310 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 3311 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 3312 3313 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(), 3314 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs)) 3315 return nullptr; 3316 3317 // Check that the template argument list is well-formed for this template. 3318 SmallVector<TemplateArgument, 4> Converted; 3319 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(), 3320 VarTemplateArgsInfo, false, Converted)) 3321 return nullptr; 3322 3323 // Check whether we've already seen a declaration of this specialization. 3324 void *InsertPos = nullptr; 3325 VarTemplateSpecializationDecl *PrevDecl = 3326 InstVarTemplate->findSpecialization(Converted, InsertPos); 3327 3328 // Check whether we've already seen a conflicting instantiation of this 3329 // declaration (for instance, if there was a prior implicit instantiation). 3330 bool Ignored; 3331 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl( 3332 D->getLocation(), D->getSpecializationKind(), PrevDecl, 3333 PrevDecl->getSpecializationKind(), 3334 PrevDecl->getPointOfInstantiation(), Ignored)) 3335 return nullptr; 3336 3337 return VisitVarTemplateSpecializationDecl( 3338 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl); 3339 } 3340 3341 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3342 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos, 3343 const TemplateArgumentListInfo &TemplateArgsInfo, 3344 ArrayRef<TemplateArgument> Converted, 3345 VarTemplateSpecializationDecl *PrevDecl) { 3346 3347 // Do substitution on the type of the declaration 3348 TypeSourceInfo *DI = 3349 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 3350 D->getTypeSpecStartLoc(), D->getDeclName()); 3351 if (!DI) 3352 return nullptr; 3353 3354 if (DI->getType()->isFunctionType()) { 3355 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 3356 << D->isStaticDataMember() << DI->getType(); 3357 return nullptr; 3358 } 3359 3360 // Build the instantiated declaration 3361 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 3362 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 3363 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted); 3364 Var->setTemplateArgsInfo(TemplateArgsInfo); 3365 if (InsertPos) 3366 VarTemplate->AddSpecialization(Var, InsertPos); 3367 3368 // Substitute the nested name specifier, if any. 3369 if (SubstQualifier(D, Var)) 3370 return nullptr; 3371 3372 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 3373 StartingScope, false, PrevDecl); 3374 3375 return Var; 3376 } 3377 3378 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 3379 llvm_unreachable("@defs is not supported in Objective-C++"); 3380 } 3381 3382 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 3383 // FIXME: We need to be able to instantiate FriendTemplateDecls. 3384 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 3385 DiagnosticsEngine::Error, 3386 "cannot instantiate %0 yet"); 3387 SemaRef.Diag(D->getLocation(), DiagID) 3388 << D->getDeclKindName(); 3389 3390 return nullptr; 3391 } 3392 3393 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 3394 llvm_unreachable("Unexpected decl"); 3395 } 3396 3397 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 3398 const MultiLevelTemplateArgumentList &TemplateArgs) { 3399 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3400 if (D->isInvalidDecl()) 3401 return nullptr; 3402 3403 return Instantiator.Visit(D); 3404 } 3405 3406 /// Instantiates a nested template parameter list in the current 3407 /// instantiation context. 3408 /// 3409 /// \param L The parameter list to instantiate 3410 /// 3411 /// \returns NULL if there was an error 3412 TemplateParameterList * 3413 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 3414 // Get errors for all the parameters before bailing out. 3415 bool Invalid = false; 3416 3417 unsigned N = L->size(); 3418 typedef SmallVector<NamedDecl *, 8> ParamVector; 3419 ParamVector Params; 3420 Params.reserve(N); 3421 for (auto &P : *L) { 3422 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P)); 3423 Params.push_back(D); 3424 Invalid = Invalid || !D || D->isInvalidDecl(); 3425 } 3426 3427 // Clean up if we had an error. 3428 if (Invalid) 3429 return nullptr; 3430 3431 // Note: we substitute into associated constraints later 3432 Expr *const UninstantiatedRequiresClause = L->getRequiresClause(); 3433 3434 TemplateParameterList *InstL 3435 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 3436 L->getLAngleLoc(), Params, 3437 L->getRAngleLoc(), 3438 UninstantiatedRequiresClause); 3439 return InstL; 3440 } 3441 3442 TemplateParameterList * 3443 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 3444 const MultiLevelTemplateArgumentList &TemplateArgs) { 3445 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3446 return Instantiator.SubstTemplateParams(Params); 3447 } 3448 3449 /// Instantiate the declaration of a class template partial 3450 /// specialization. 3451 /// 3452 /// \param ClassTemplate the (instantiated) class template that is partially 3453 // specialized by the instantiation of \p PartialSpec. 3454 /// 3455 /// \param PartialSpec the (uninstantiated) class template partial 3456 /// specialization that we are instantiating. 3457 /// 3458 /// \returns The instantiated partial specialization, if successful; otherwise, 3459 /// NULL to indicate an error. 3460 ClassTemplatePartialSpecializationDecl * 3461 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 3462 ClassTemplateDecl *ClassTemplate, 3463 ClassTemplatePartialSpecializationDecl *PartialSpec) { 3464 // Create a local instantiation scope for this class template partial 3465 // specialization, which will contain the instantiations of the template 3466 // parameters. 3467 LocalInstantiationScope Scope(SemaRef); 3468 3469 // Substitute into the template parameters of the class template partial 3470 // specialization. 3471 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 3472 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 3473 if (!InstParams) 3474 return nullptr; 3475 3476 // Substitute into the template arguments of the class template partial 3477 // specialization. 3478 const ASTTemplateArgumentListInfo *TemplArgInfo 3479 = PartialSpec->getTemplateArgsAsWritten(); 3480 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 3481 TemplArgInfo->RAngleLoc); 3482 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 3483 TemplArgInfo->NumTemplateArgs, 3484 InstTemplateArgs, TemplateArgs)) 3485 return nullptr; 3486 3487 // Check that the template argument list is well-formed for this 3488 // class template. 3489 SmallVector<TemplateArgument, 4> Converted; 3490 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 3491 PartialSpec->getLocation(), 3492 InstTemplateArgs, 3493 false, 3494 Converted)) 3495 return nullptr; 3496 3497 // Check these arguments are valid for a template partial specialization. 3498 if (SemaRef.CheckTemplatePartialSpecializationArgs( 3499 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(), 3500 Converted)) 3501 return nullptr; 3502 3503 // Figure out where to insert this class template partial specialization 3504 // in the member template's set of class template partial specializations. 3505 void *InsertPos = nullptr; 3506 ClassTemplateSpecializationDecl *PrevDecl 3507 = ClassTemplate->findPartialSpecialization(Converted, InsertPos); 3508 3509 // Build the canonical type that describes the converted template 3510 // arguments of the class template partial specialization. 3511 QualType CanonType 3512 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 3513 Converted); 3514 3515 // Build the fully-sugared type for this class template 3516 // specialization as the user wrote in the specialization 3517 // itself. This means that we'll pretty-print the type retrieved 3518 // from the specialization's declaration the way that the user 3519 // actually wrote the specialization, rather than formatting the 3520 // name based on the "canonical" representation used to store the 3521 // template arguments in the specialization. 3522 TypeSourceInfo *WrittenTy 3523 = SemaRef.Context.getTemplateSpecializationTypeInfo( 3524 TemplateName(ClassTemplate), 3525 PartialSpec->getLocation(), 3526 InstTemplateArgs, 3527 CanonType); 3528 3529 if (PrevDecl) { 3530 // We've already seen a partial specialization with the same template 3531 // parameters and template arguments. This can happen, for example, when 3532 // substituting the outer template arguments ends up causing two 3533 // class template partial specializations of a member class template 3534 // to have identical forms, e.g., 3535 // 3536 // template<typename T, typename U> 3537 // struct Outer { 3538 // template<typename X, typename Y> struct Inner; 3539 // template<typename Y> struct Inner<T, Y>; 3540 // template<typename Y> struct Inner<U, Y>; 3541 // }; 3542 // 3543 // Outer<int, int> outer; // error: the partial specializations of Inner 3544 // // have the same signature. 3545 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 3546 << WrittenTy->getType(); 3547 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 3548 << SemaRef.Context.getTypeDeclType(PrevDecl); 3549 return nullptr; 3550 } 3551 3552 3553 // Create the class template partial specialization declaration. 3554 ClassTemplatePartialSpecializationDecl *InstPartialSpec = 3555 ClassTemplatePartialSpecializationDecl::Create( 3556 SemaRef.Context, PartialSpec->getTagKind(), Owner, 3557 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams, 3558 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr); 3559 // Substitute the nested name specifier, if any. 3560 if (SubstQualifier(PartialSpec, InstPartialSpec)) 3561 return nullptr; 3562 3563 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 3564 InstPartialSpec->setTypeAsWritten(WrittenTy); 3565 3566 // Check the completed partial specialization. 3567 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 3568 3569 // Add this partial specialization to the set of class template partial 3570 // specializations. 3571 ClassTemplate->AddPartialSpecialization(InstPartialSpec, 3572 /*InsertPos=*/nullptr); 3573 return InstPartialSpec; 3574 } 3575 3576 /// Instantiate the declaration of a variable template partial 3577 /// specialization. 3578 /// 3579 /// \param VarTemplate the (instantiated) variable template that is partially 3580 /// specialized by the instantiation of \p PartialSpec. 3581 /// 3582 /// \param PartialSpec the (uninstantiated) variable template partial 3583 /// specialization that we are instantiating. 3584 /// 3585 /// \returns The instantiated partial specialization, if successful; otherwise, 3586 /// NULL to indicate an error. 3587 VarTemplatePartialSpecializationDecl * 3588 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 3589 VarTemplateDecl *VarTemplate, 3590 VarTemplatePartialSpecializationDecl *PartialSpec) { 3591 // Create a local instantiation scope for this variable template partial 3592 // specialization, which will contain the instantiations of the template 3593 // parameters. 3594 LocalInstantiationScope Scope(SemaRef); 3595 3596 // Substitute into the template parameters of the variable template partial 3597 // specialization. 3598 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 3599 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 3600 if (!InstParams) 3601 return nullptr; 3602 3603 // Substitute into the template arguments of the variable template partial 3604 // specialization. 3605 const ASTTemplateArgumentListInfo *TemplArgInfo 3606 = PartialSpec->getTemplateArgsAsWritten(); 3607 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 3608 TemplArgInfo->RAngleLoc); 3609 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 3610 TemplArgInfo->NumTemplateArgs, 3611 InstTemplateArgs, TemplateArgs)) 3612 return nullptr; 3613 3614 // Check that the template argument list is well-formed for this 3615 // class template. 3616 SmallVector<TemplateArgument, 4> Converted; 3617 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 3618 InstTemplateArgs, false, Converted)) 3619 return nullptr; 3620 3621 // Check these arguments are valid for a template partial specialization. 3622 if (SemaRef.CheckTemplatePartialSpecializationArgs( 3623 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(), 3624 Converted)) 3625 return nullptr; 3626 3627 // Figure out where to insert this variable template partial specialization 3628 // in the member template's set of variable template partial specializations. 3629 void *InsertPos = nullptr; 3630 VarTemplateSpecializationDecl *PrevDecl = 3631 VarTemplate->findPartialSpecialization(Converted, InsertPos); 3632 3633 // Build the canonical type that describes the converted template 3634 // arguments of the variable template partial specialization. 3635 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3636 TemplateName(VarTemplate), Converted); 3637 3638 // Build the fully-sugared type for this variable template 3639 // specialization as the user wrote in the specialization 3640 // itself. This means that we'll pretty-print the type retrieved 3641 // from the specialization's declaration the way that the user 3642 // actually wrote the specialization, rather than formatting the 3643 // name based on the "canonical" representation used to store the 3644 // template arguments in the specialization. 3645 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3646 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 3647 CanonType); 3648 3649 if (PrevDecl) { 3650 // We've already seen a partial specialization with the same template 3651 // parameters and template arguments. This can happen, for example, when 3652 // substituting the outer template arguments ends up causing two 3653 // variable template partial specializations of a member variable template 3654 // to have identical forms, e.g., 3655 // 3656 // template<typename T, typename U> 3657 // struct Outer { 3658 // template<typename X, typename Y> pair<X,Y> p; 3659 // template<typename Y> pair<T, Y> p; 3660 // template<typename Y> pair<U, Y> p; 3661 // }; 3662 // 3663 // Outer<int, int> outer; // error: the partial specializations of Inner 3664 // // have the same signature. 3665 SemaRef.Diag(PartialSpec->getLocation(), 3666 diag::err_var_partial_spec_redeclared) 3667 << WrittenTy->getType(); 3668 SemaRef.Diag(PrevDecl->getLocation(), 3669 diag::note_var_prev_partial_spec_here); 3670 return nullptr; 3671 } 3672 3673 // Do substitution on the type of the declaration 3674 TypeSourceInfo *DI = SemaRef.SubstType( 3675 PartialSpec->getTypeSourceInfo(), TemplateArgs, 3676 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 3677 if (!DI) 3678 return nullptr; 3679 3680 if (DI->getType()->isFunctionType()) { 3681 SemaRef.Diag(PartialSpec->getLocation(), 3682 diag::err_variable_instantiates_to_function) 3683 << PartialSpec->isStaticDataMember() << DI->getType(); 3684 return nullptr; 3685 } 3686 3687 // Create the variable template partial specialization declaration. 3688 VarTemplatePartialSpecializationDecl *InstPartialSpec = 3689 VarTemplatePartialSpecializationDecl::Create( 3690 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 3691 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 3692 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs); 3693 3694 // Substitute the nested name specifier, if any. 3695 if (SubstQualifier(PartialSpec, InstPartialSpec)) 3696 return nullptr; 3697 3698 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 3699 InstPartialSpec->setTypeAsWritten(WrittenTy); 3700 3701 // Check the completed partial specialization. 3702 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 3703 3704 // Add this partial specialization to the set of variable template partial 3705 // specializations. The instantiation of the initializer is not necessary. 3706 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr); 3707 3708 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 3709 LateAttrs, Owner, StartingScope); 3710 3711 return InstPartialSpec; 3712 } 3713 3714 TypeSourceInfo* 3715 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 3716 SmallVectorImpl<ParmVarDecl *> &Params) { 3717 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 3718 assert(OldTInfo && "substituting function without type source info"); 3719 assert(Params.empty() && "parameter vector is non-empty at start"); 3720 3721 CXXRecordDecl *ThisContext = nullptr; 3722 Qualifiers ThisTypeQuals; 3723 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 3724 ThisContext = cast<CXXRecordDecl>(Owner); 3725 ThisTypeQuals = Method->getMethodQualifiers(); 3726 } 3727 3728 TypeSourceInfo *NewTInfo 3729 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 3730 D->getTypeSpecStartLoc(), 3731 D->getDeclName(), 3732 ThisContext, ThisTypeQuals); 3733 if (!NewTInfo) 3734 return nullptr; 3735 3736 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 3737 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 3738 if (NewTInfo != OldTInfo) { 3739 // Get parameters from the new type info. 3740 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 3741 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 3742 unsigned NewIdx = 0; 3743 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); 3744 OldIdx != NumOldParams; ++OldIdx) { 3745 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); 3746 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 3747 3748 Optional<unsigned> NumArgumentsInExpansion; 3749 if (OldParam->isParameterPack()) 3750 NumArgumentsInExpansion = 3751 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 3752 TemplateArgs); 3753 if (!NumArgumentsInExpansion) { 3754 // Simple case: normal parameter, or a parameter pack that's 3755 // instantiated to a (still-dependent) parameter pack. 3756 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 3757 Params.push_back(NewParam); 3758 Scope->InstantiatedLocal(OldParam, NewParam); 3759 } else { 3760 // Parameter pack expansion: make the instantiation an argument pack. 3761 Scope->MakeInstantiatedLocalArgPack(OldParam); 3762 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 3763 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 3764 Params.push_back(NewParam); 3765 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 3766 } 3767 } 3768 } 3769 } else { 3770 // The function type itself was not dependent and therefore no 3771 // substitution occurred. However, we still need to instantiate 3772 // the function parameters themselves. 3773 const FunctionProtoType *OldProto = 3774 cast<FunctionProtoType>(OldProtoLoc.getType()); 3775 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; 3776 ++i) { 3777 ParmVarDecl *OldParam = OldProtoLoc.getParam(i); 3778 if (!OldParam) { 3779 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 3780 D, D->getLocation(), OldProto->getParamType(i))); 3781 continue; 3782 } 3783 3784 ParmVarDecl *Parm = 3785 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 3786 if (!Parm) 3787 return nullptr; 3788 Params.push_back(Parm); 3789 } 3790 } 3791 } else { 3792 // If the type of this function, after ignoring parentheses, is not 3793 // *directly* a function type, then we're instantiating a function that 3794 // was declared via a typedef or with attributes, e.g., 3795 // 3796 // typedef int functype(int, int); 3797 // functype func; 3798 // int __cdecl meth(int, int); 3799 // 3800 // In this case, we'll just go instantiate the ParmVarDecls that we 3801 // synthesized in the method declaration. 3802 SmallVector<QualType, 4> ParamTypes; 3803 Sema::ExtParameterInfoBuilder ExtParamInfos; 3804 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr, 3805 TemplateArgs, ParamTypes, &Params, 3806 ExtParamInfos)) 3807 return nullptr; 3808 } 3809 3810 return NewTInfo; 3811 } 3812 3813 /// Introduce the instantiated function parameters into the local 3814 /// instantiation scope, and set the parameter names to those used 3815 /// in the template. 3816 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 3817 const FunctionDecl *PatternDecl, 3818 LocalInstantiationScope &Scope, 3819 const MultiLevelTemplateArgumentList &TemplateArgs) { 3820 unsigned FParamIdx = 0; 3821 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 3822 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 3823 if (!PatternParam->isParameterPack()) { 3824 // Simple case: not a parameter pack. 3825 assert(FParamIdx < Function->getNumParams()); 3826 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 3827 FunctionParam->setDeclName(PatternParam->getDeclName()); 3828 // If the parameter's type is not dependent, update it to match the type 3829 // in the pattern. They can differ in top-level cv-qualifiers, and we want 3830 // the pattern's type here. If the type is dependent, they can't differ, 3831 // per core issue 1668. Substitute into the type from the pattern, in case 3832 // it's instantiation-dependent. 3833 // FIXME: Updating the type to work around this is at best fragile. 3834 if (!PatternDecl->getType()->isDependentType()) { 3835 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs, 3836 FunctionParam->getLocation(), 3837 FunctionParam->getDeclName()); 3838 if (T.isNull()) 3839 return true; 3840 FunctionParam->setType(T); 3841 } 3842 3843 Scope.InstantiatedLocal(PatternParam, FunctionParam); 3844 ++FParamIdx; 3845 continue; 3846 } 3847 3848 // Expand the parameter pack. 3849 Scope.MakeInstantiatedLocalArgPack(PatternParam); 3850 Optional<unsigned> NumArgumentsInExpansion 3851 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 3852 if (NumArgumentsInExpansion) { 3853 QualType PatternType = 3854 PatternParam->getType()->castAs<PackExpansionType>()->getPattern(); 3855 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 3856 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 3857 FunctionParam->setDeclName(PatternParam->getDeclName()); 3858 if (!PatternDecl->getType()->isDependentType()) { 3859 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg); 3860 QualType T = S.SubstType(PatternType, TemplateArgs, 3861 FunctionParam->getLocation(), 3862 FunctionParam->getDeclName()); 3863 if (T.isNull()) 3864 return true; 3865 FunctionParam->setType(T); 3866 } 3867 3868 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 3869 ++FParamIdx; 3870 } 3871 } 3872 } 3873 3874 return false; 3875 } 3876 3877 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 3878 FunctionDecl *Decl) { 3879 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 3880 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 3881 return; 3882 3883 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 3884 InstantiatingTemplate::ExceptionSpecification()); 3885 if (Inst.isInvalid()) { 3886 // We hit the instantiation depth limit. Clear the exception specification 3887 // so that our callers don't have to cope with EST_Uninstantiated. 3888 UpdateExceptionSpec(Decl, EST_None); 3889 return; 3890 } 3891 if (Inst.isAlreadyInstantiating()) { 3892 // This exception specification indirectly depends on itself. Reject. 3893 // FIXME: Corresponding rule in the standard? 3894 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl; 3895 UpdateExceptionSpec(Decl, EST_None); 3896 return; 3897 } 3898 3899 // Enter the scope of this instantiation. We don't use 3900 // PushDeclContext because we don't have a scope. 3901 Sema::ContextRAII savedContext(*this, Decl); 3902 LocalInstantiationScope Scope(*this); 3903 3904 MultiLevelTemplateArgumentList TemplateArgs = 3905 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true); 3906 3907 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 3908 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope, 3909 TemplateArgs)) { 3910 UpdateExceptionSpec(Decl, EST_None); 3911 return; 3912 } 3913 3914 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(), 3915 TemplateArgs); 3916 } 3917 3918 /// Initializes the common fields of an instantiation function 3919 /// declaration (New) from the corresponding fields of its template (Tmpl). 3920 /// 3921 /// \returns true if there was an error 3922 bool 3923 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 3924 FunctionDecl *Tmpl) { 3925 if (Tmpl->isDeleted()) 3926 New->setDeletedAsWritten(); 3927 3928 New->setImplicit(Tmpl->isImplicit()); 3929 3930 // Forward the mangling number from the template to the instantiated decl. 3931 SemaRef.Context.setManglingNumber(New, 3932 SemaRef.Context.getManglingNumber(Tmpl)); 3933 3934 // If we are performing substituting explicitly-specified template arguments 3935 // or deduced template arguments into a function template and we reach this 3936 // point, we are now past the point where SFINAE applies and have committed 3937 // to keeping the new function template specialization. We therefore 3938 // convert the active template instantiation for the function template 3939 // into a template instantiation for this specific function template 3940 // specialization, which is not a SFINAE context, so that we diagnose any 3941 // further errors in the declaration itself. 3942 typedef Sema::CodeSynthesisContext ActiveInstType; 3943 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back(); 3944 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 3945 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 3946 if (FunctionTemplateDecl *FunTmpl 3947 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 3948 assert(FunTmpl->getTemplatedDecl() == Tmpl && 3949 "Deduction from the wrong function template?"); 3950 (void) FunTmpl; 3951 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 3952 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 3953 ActiveInst.Entity = New; 3954 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 3955 } 3956 } 3957 3958 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 3959 assert(Proto && "Function template without prototype?"); 3960 3961 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 3962 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3963 3964 // DR1330: In C++11, defer instantiation of a non-trivial 3965 // exception specification. 3966 // DR1484: Local classes and their members are instantiated along with the 3967 // containing function. 3968 if (SemaRef.getLangOpts().CPlusPlus11 && 3969 EPI.ExceptionSpec.Type != EST_None && 3970 EPI.ExceptionSpec.Type != EST_DynamicNone && 3971 EPI.ExceptionSpec.Type != EST_BasicNoexcept && 3972 !Tmpl->isLexicallyWithinFunctionOrMethod()) { 3973 FunctionDecl *ExceptionSpecTemplate = Tmpl; 3974 if (EPI.ExceptionSpec.Type == EST_Uninstantiated) 3975 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; 3976 ExceptionSpecificationType NewEST = EST_Uninstantiated; 3977 if (EPI.ExceptionSpec.Type == EST_Unevaluated) 3978 NewEST = EST_Unevaluated; 3979 3980 // Mark the function has having an uninstantiated exception specification. 3981 const FunctionProtoType *NewProto 3982 = New->getType()->getAs<FunctionProtoType>(); 3983 assert(NewProto && "Template instantiation without function prototype?"); 3984 EPI = NewProto->getExtProtoInfo(); 3985 EPI.ExceptionSpec.Type = NewEST; 3986 EPI.ExceptionSpec.SourceDecl = New; 3987 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; 3988 New->setType(SemaRef.Context.getFunctionType( 3989 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 3990 } else { 3991 Sema::ContextRAII SwitchContext(SemaRef, New); 3992 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs); 3993 } 3994 } 3995 3996 // Get the definition. Leaves the variable unchanged if undefined. 3997 const FunctionDecl *Definition = Tmpl; 3998 Tmpl->isDefined(Definition); 3999 4000 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 4001 LateAttrs, StartingScope); 4002 4003 return false; 4004 } 4005 4006 /// Initializes common fields of an instantiated method 4007 /// declaration (New) from the corresponding fields of its template 4008 /// (Tmpl). 4009 /// 4010 /// \returns true if there was an error 4011 bool 4012 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 4013 CXXMethodDecl *Tmpl) { 4014 if (InitFunctionInstantiation(New, Tmpl)) 4015 return true; 4016 4017 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11) 4018 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New)); 4019 4020 New->setAccess(Tmpl->getAccess()); 4021 if (Tmpl->isVirtualAsWritten()) 4022 New->setVirtualAsWritten(true); 4023 4024 // FIXME: New needs a pointer to Tmpl 4025 return false; 4026 } 4027 4028 /// Instantiate (or find existing instantiation of) a function template with a 4029 /// given set of template arguments. 4030 /// 4031 /// Usually this should not be used, and template argument deduction should be 4032 /// used in its place. 4033 FunctionDecl * 4034 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 4035 const TemplateArgumentList *Args, 4036 SourceLocation Loc) { 4037 FunctionDecl *FD = FTD->getTemplatedDecl(); 4038 4039 sema::TemplateDeductionInfo Info(Loc); 4040 InstantiatingTemplate Inst( 4041 *this, Loc, FTD, Args->asArray(), 4042 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); 4043 if (Inst.isInvalid()) 4044 return nullptr; 4045 4046 ContextRAII SavedContext(*this, FD); 4047 MultiLevelTemplateArgumentList MArgs(*Args); 4048 4049 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs)); 4050 } 4051 4052 /// In the MS ABI, we need to instantiate default arguments of dllexported 4053 /// default constructors along with the constructor definition. This allows IR 4054 /// gen to emit a constructor closure which calls the default constructor with 4055 /// its default arguments. 4056 static void InstantiateDefaultCtorDefaultArgs(Sema &S, 4057 CXXConstructorDecl *Ctor) { 4058 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4059 Ctor->isDefaultConstructor()); 4060 unsigned NumParams = Ctor->getNumParams(); 4061 if (NumParams == 0) 4062 return; 4063 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>(); 4064 if (!Attr) 4065 return; 4066 for (unsigned I = 0; I != NumParams; ++I) { 4067 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor, 4068 Ctor->getParamDecl(I)); 4069 S.DiscardCleanupsInEvaluationContext(); 4070 } 4071 } 4072 4073 /// Instantiate the definition of the given function from its 4074 /// template. 4075 /// 4076 /// \param PointOfInstantiation the point at which the instantiation was 4077 /// required. Note that this is not precisely a "point of instantiation" 4078 /// for the function, but it's close. 4079 /// 4080 /// \param Function the already-instantiated declaration of a 4081 /// function template specialization or member function of a class template 4082 /// specialization. 4083 /// 4084 /// \param Recursive if true, recursively instantiates any functions that 4085 /// are required by this instantiation. 4086 /// 4087 /// \param DefinitionRequired if true, then we are performing an explicit 4088 /// instantiation where the body of the function is required. Complain if 4089 /// there is no such body. 4090 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 4091 FunctionDecl *Function, 4092 bool Recursive, 4093 bool DefinitionRequired, 4094 bool AtEndOfTU) { 4095 if (Function->isInvalidDecl() || Function->isDefined() || 4096 isa<CXXDeductionGuideDecl>(Function)) 4097 return; 4098 4099 // Never instantiate an explicit specialization except if it is a class scope 4100 // explicit specialization. 4101 TemplateSpecializationKind TSK = 4102 Function->getTemplateSpecializationKindForInstantiation(); 4103 if (TSK == TSK_ExplicitSpecialization) 4104 return; 4105 4106 // Find the function body that we'll be substituting. 4107 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 4108 assert(PatternDecl && "instantiating a non-template"); 4109 4110 const FunctionDecl *PatternDef = PatternDecl->getDefinition(); 4111 Stmt *Pattern = nullptr; 4112 if (PatternDef) { 4113 Pattern = PatternDef->getBody(PatternDef); 4114 PatternDecl = PatternDef; 4115 if (PatternDef->willHaveBody()) 4116 PatternDef = nullptr; 4117 } 4118 4119 // FIXME: We need to track the instantiation stack in order to know which 4120 // definitions should be visible within this instantiation. 4121 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function, 4122 Function->getInstantiatedFromMemberFunction(), 4123 PatternDecl, PatternDef, TSK, 4124 /*Complain*/DefinitionRequired)) { 4125 if (DefinitionRequired) 4126 Function->setInvalidDecl(); 4127 else if (TSK == TSK_ExplicitInstantiationDefinition) { 4128 // Try again at the end of the translation unit (at which point a 4129 // definition will be required). 4130 assert(!Recursive); 4131 Function->setInstantiationIsPending(true); 4132 PendingInstantiations.push_back( 4133 std::make_pair(Function, PointOfInstantiation)); 4134 } else if (TSK == TSK_ImplicitInstantiation) { 4135 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 4136 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 4137 Diag(PointOfInstantiation, diag::warn_func_template_missing) 4138 << Function; 4139 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 4140 if (getLangOpts().CPlusPlus11) 4141 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) 4142 << Function; 4143 } 4144 } 4145 4146 return; 4147 } 4148 4149 // Postpone late parsed template instantiations. 4150 if (PatternDecl->isLateTemplateParsed() && 4151 !LateTemplateParser) { 4152 Function->setInstantiationIsPending(true); 4153 LateParsedInstantiations.push_back( 4154 std::make_pair(Function, PointOfInstantiation)); 4155 return; 4156 } 4157 4158 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() { 4159 std::string Name; 4160 llvm::raw_string_ostream OS(Name); 4161 Function->getNameForDiagnostic(OS, getPrintingPolicy(), 4162 /*Qualified=*/true); 4163 return Name; 4164 }); 4165 4166 // If we're performing recursive template instantiation, create our own 4167 // queue of pending implicit instantiations that we will instantiate later, 4168 // while we're still within our own instantiation context. 4169 // This has to happen before LateTemplateParser below is called, so that 4170 // it marks vtables used in late parsed templates as used. 4171 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4172 /*Enabled=*/Recursive); 4173 LocalEagerInstantiationScope LocalInstantiations(*this); 4174 4175 // Call the LateTemplateParser callback if there is a need to late parse 4176 // a templated function definition. 4177 if (!Pattern && PatternDecl->isLateTemplateParsed() && 4178 LateTemplateParser) { 4179 // FIXME: Optimize to allow individual templates to be deserialized. 4180 if (PatternDecl->isFromASTFile()) 4181 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 4182 4183 auto LPTIter = LateParsedTemplateMap.find(PatternDecl); 4184 assert(LPTIter != LateParsedTemplateMap.end() && 4185 "missing LateParsedTemplate"); 4186 LateTemplateParser(OpaqueParser, *LPTIter->second); 4187 Pattern = PatternDecl->getBody(PatternDecl); 4188 } 4189 4190 // Note, we should never try to instantiate a deleted function template. 4191 assert((Pattern || PatternDecl->isDefaulted() || 4192 PatternDecl->hasSkippedBody()) && 4193 "unexpected kind of function template definition"); 4194 4195 // C++1y [temp.explicit]p10: 4196 // Except for inline functions, declarations with types deduced from their 4197 // initializer or return value, and class template specializations, other 4198 // explicit instantiation declarations have the effect of suppressing the 4199 // implicit instantiation of the entity to which they refer. 4200 if (TSK == TSK_ExplicitInstantiationDeclaration && 4201 !PatternDecl->isInlined() && 4202 !PatternDecl->getReturnType()->getContainedAutoType()) 4203 return; 4204 4205 if (PatternDecl->isInlined()) { 4206 // Function, and all later redeclarations of it (from imported modules, 4207 // for instance), are now implicitly inline. 4208 for (auto *D = Function->getMostRecentDecl(); /**/; 4209 D = D->getPreviousDecl()) { 4210 D->setImplicitlyInline(); 4211 if (D == Function) 4212 break; 4213 } 4214 } 4215 4216 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 4217 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4218 return; 4219 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(), 4220 "instantiating function definition"); 4221 4222 // The instantiation is visible here, even if it was first declared in an 4223 // unimported module. 4224 Function->setVisibleDespiteOwningModule(); 4225 4226 // Copy the inner loc start from the pattern. 4227 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 4228 4229 EnterExpressionEvaluationContext EvalContext( 4230 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 4231 4232 // Introduce a new scope where local variable instantiations will be 4233 // recorded, unless we're actually a member function within a local 4234 // class, in which case we need to merge our results with the parent 4235 // scope (of the enclosing function). 4236 bool MergeWithParentScope = false; 4237 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 4238 MergeWithParentScope = Rec->isLocalClass(); 4239 4240 LocalInstantiationScope Scope(*this, MergeWithParentScope); 4241 4242 if (PatternDecl->isDefaulted()) 4243 SetDeclDefaulted(Function, PatternDecl->getLocation()); 4244 else { 4245 MultiLevelTemplateArgumentList TemplateArgs = 4246 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl); 4247 4248 // Substitute into the qualifier; we can get a substitution failure here 4249 // through evil use of alias templates. 4250 // FIXME: Is CurContext correct for this? Should we go to the (instantiation 4251 // of the) lexical context of the pattern? 4252 SubstQualifier(*this, PatternDecl, Function, TemplateArgs); 4253 4254 ActOnStartOfFunctionDef(nullptr, Function); 4255 4256 // Enter the scope of this instantiation. We don't use 4257 // PushDeclContext because we don't have a scope. 4258 Sema::ContextRAII savedContext(*this, Function); 4259 4260 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 4261 TemplateArgs)) 4262 return; 4263 4264 StmtResult Body; 4265 if (PatternDecl->hasSkippedBody()) { 4266 ActOnSkippedFunctionBody(Function); 4267 Body = nullptr; 4268 } else { 4269 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) { 4270 // If this is a constructor, instantiate the member initializers. 4271 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl), 4272 TemplateArgs); 4273 4274 // If this is an MS ABI dllexport default constructor, instantiate any 4275 // default arguments. 4276 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 4277 Ctor->isDefaultConstructor()) { 4278 InstantiateDefaultCtorDefaultArgs(*this, Ctor); 4279 } 4280 } 4281 4282 // Instantiate the function body. 4283 Body = SubstStmt(Pattern, TemplateArgs); 4284 4285 if (Body.isInvalid()) 4286 Function->setInvalidDecl(); 4287 } 4288 // FIXME: finishing the function body while in an expression evaluation 4289 // context seems wrong. Investigate more. 4290 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true); 4291 4292 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 4293 4294 if (auto *Listener = getASTMutationListener()) 4295 Listener->FunctionDefinitionInstantiated(Function); 4296 4297 savedContext.pop(); 4298 } 4299 4300 DeclGroupRef DG(Function); 4301 Consumer.HandleTopLevelDecl(DG); 4302 4303 // This class may have local implicit instantiations that need to be 4304 // instantiation within this scope. 4305 LocalInstantiations.perform(); 4306 Scope.Exit(); 4307 GlobalInstantiations.perform(); 4308 } 4309 4310 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 4311 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 4312 const TemplateArgumentList &TemplateArgList, 4313 const TemplateArgumentListInfo &TemplateArgsInfo, 4314 SmallVectorImpl<TemplateArgument> &Converted, 4315 SourceLocation PointOfInstantiation, void *InsertPos, 4316 LateInstantiatedAttrVec *LateAttrs, 4317 LocalInstantiationScope *StartingScope) { 4318 if (FromVar->isInvalidDecl()) 4319 return nullptr; 4320 4321 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 4322 if (Inst.isInvalid()) 4323 return nullptr; 4324 4325 MultiLevelTemplateArgumentList TemplateArgLists; 4326 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 4327 4328 // Instantiate the first declaration of the variable template: for a partial 4329 // specialization of a static data member template, the first declaration may 4330 // or may not be the declaration in the class; if it's in the class, we want 4331 // to instantiate a member in the class (a declaration), and if it's outside, 4332 // we want to instantiate a definition. 4333 // 4334 // If we're instantiating an explicitly-specialized member template or member 4335 // partial specialization, don't do this. The member specialization completely 4336 // replaces the original declaration in this case. 4337 bool IsMemberSpec = false; 4338 if (VarTemplatePartialSpecializationDecl *PartialSpec = 4339 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) 4340 IsMemberSpec = PartialSpec->isMemberSpecialization(); 4341 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate()) 4342 IsMemberSpec = FromTemplate->isMemberSpecialization(); 4343 if (!IsMemberSpec) 4344 FromVar = FromVar->getFirstDecl(); 4345 4346 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 4347 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 4348 MultiLevelList); 4349 4350 // TODO: Set LateAttrs and StartingScope ... 4351 4352 return cast_or_null<VarTemplateSpecializationDecl>( 4353 Instantiator.VisitVarTemplateSpecializationDecl( 4354 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted)); 4355 } 4356 4357 /// Instantiates a variable template specialization by completing it 4358 /// with appropriate type information and initializer. 4359 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 4360 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 4361 const MultiLevelTemplateArgumentList &TemplateArgs) { 4362 assert(PatternDecl->isThisDeclarationADefinition() && 4363 "don't have a definition to instantiate from"); 4364 4365 // Do substitution on the type of the declaration 4366 TypeSourceInfo *DI = 4367 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 4368 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 4369 if (!DI) 4370 return nullptr; 4371 4372 // Update the type of this variable template specialization. 4373 VarSpec->setType(DI->getType()); 4374 4375 // Convert the declaration into a definition now. 4376 VarSpec->setCompleteDefinition(); 4377 4378 // Instantiate the initializer. 4379 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 4380 4381 return VarSpec; 4382 } 4383 4384 /// BuildVariableInstantiation - Used after a new variable has been created. 4385 /// Sets basic variable data and decides whether to postpone the 4386 /// variable instantiation. 4387 void Sema::BuildVariableInstantiation( 4388 VarDecl *NewVar, VarDecl *OldVar, 4389 const MultiLevelTemplateArgumentList &TemplateArgs, 4390 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 4391 LocalInstantiationScope *StartingScope, 4392 bool InstantiatingVarTemplate, 4393 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) { 4394 // Instantiating a partial specialization to produce a partial 4395 // specialization. 4396 bool InstantiatingVarTemplatePartialSpec = 4397 isa<VarTemplatePartialSpecializationDecl>(OldVar) && 4398 isa<VarTemplatePartialSpecializationDecl>(NewVar); 4399 // Instantiating from a variable template (or partial specialization) to 4400 // produce a variable template specialization. 4401 bool InstantiatingSpecFromTemplate = 4402 isa<VarTemplateSpecializationDecl>(NewVar) && 4403 (OldVar->getDescribedVarTemplate() || 4404 isa<VarTemplatePartialSpecializationDecl>(OldVar)); 4405 4406 // If we are instantiating a local extern declaration, the 4407 // instantiation belongs lexically to the containing function. 4408 // If we are instantiating a static data member defined 4409 // out-of-line, the instantiation will have the same lexical 4410 // context (which will be a namespace scope) as the template. 4411 if (OldVar->isLocalExternDecl()) { 4412 NewVar->setLocalExternDecl(); 4413 NewVar->setLexicalDeclContext(Owner); 4414 } else if (OldVar->isOutOfLine()) 4415 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 4416 NewVar->setTSCSpec(OldVar->getTSCSpec()); 4417 NewVar->setInitStyle(OldVar->getInitStyle()); 4418 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 4419 NewVar->setObjCForDecl(OldVar->isObjCForDecl()); 4420 NewVar->setConstexpr(OldVar->isConstexpr()); 4421 NewVar->setInitCapture(OldVar->isInitCapture()); 4422 NewVar->setPreviousDeclInSameBlockScope( 4423 OldVar->isPreviousDeclInSameBlockScope()); 4424 NewVar->setAccess(OldVar->getAccess()); 4425 4426 if (!OldVar->isStaticDataMember()) { 4427 if (OldVar->isUsed(false)) 4428 NewVar->setIsUsed(); 4429 NewVar->setReferenced(OldVar->isReferenced()); 4430 } 4431 4432 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 4433 4434 LookupResult Previous( 4435 *this, NewVar->getDeclName(), NewVar->getLocation(), 4436 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 4437 : Sema::LookupOrdinaryName, 4438 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration 4439 : forRedeclarationInCurContext()); 4440 4441 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 4442 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 4443 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 4444 // We have a previous declaration. Use that one, so we merge with the 4445 // right type. 4446 if (NamedDecl *NewPrev = FindInstantiatedDecl( 4447 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 4448 Previous.addDecl(NewPrev); 4449 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 4450 OldVar->hasLinkage()) { 4451 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 4452 } else if (PrevDeclForVarTemplateSpecialization) { 4453 Previous.addDecl(PrevDeclForVarTemplateSpecialization); 4454 } 4455 CheckVariableDeclaration(NewVar, Previous); 4456 4457 if (!InstantiatingVarTemplate) { 4458 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 4459 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 4460 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 4461 } 4462 4463 if (!OldVar->isOutOfLine()) { 4464 if (NewVar->getDeclContext()->isFunctionOrMethod()) 4465 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 4466 } 4467 4468 // Link instantiations of static data members back to the template from 4469 // which they were instantiated. 4470 // 4471 // Don't do this when instantiating a template (we link the template itself 4472 // back in that case) nor when instantiating a static data member template 4473 // (that's not a member specialization). 4474 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate && 4475 !InstantiatingSpecFromTemplate) 4476 NewVar->setInstantiationOfStaticDataMember(OldVar, 4477 TSK_ImplicitInstantiation); 4478 4479 // If the pattern is an (in-class) explicit specialization, then the result 4480 // is also an explicit specialization. 4481 if (VarTemplateSpecializationDecl *OldVTSD = 4482 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) { 4483 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization && 4484 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD)) 4485 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind( 4486 TSK_ExplicitSpecialization); 4487 } 4488 4489 // Forward the mangling number from the template to the instantiated decl. 4490 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 4491 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar)); 4492 4493 // Figure out whether to eagerly instantiate the initializer. 4494 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) { 4495 // We're producing a template. Don't instantiate the initializer yet. 4496 } else if (NewVar->getType()->isUndeducedType()) { 4497 // We need the type to complete the declaration of the variable. 4498 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 4499 } else if (InstantiatingSpecFromTemplate || 4500 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() && 4501 !NewVar->isThisDeclarationADefinition())) { 4502 // Delay instantiation of the initializer for variable template 4503 // specializations or inline static data members until a definition of the 4504 // variable is needed. 4505 } else { 4506 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 4507 } 4508 4509 // Diagnose unused local variables with dependent types, where the diagnostic 4510 // will have been deferred. 4511 if (!NewVar->isInvalidDecl() && 4512 NewVar->getDeclContext()->isFunctionOrMethod() && 4513 OldVar->getType()->isDependentType()) 4514 DiagnoseUnusedDecl(NewVar); 4515 } 4516 4517 /// Instantiate the initializer of a variable. 4518 void Sema::InstantiateVariableInitializer( 4519 VarDecl *Var, VarDecl *OldVar, 4520 const MultiLevelTemplateArgumentList &TemplateArgs) { 4521 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4522 L->VariableDefinitionInstantiated(Var); 4523 4524 // We propagate the 'inline' flag with the initializer, because it 4525 // would otherwise imply that the variable is a definition for a 4526 // non-static data member. 4527 if (OldVar->isInlineSpecified()) 4528 Var->setInlineSpecified(); 4529 else if (OldVar->isInline()) 4530 Var->setImplicitlyInline(); 4531 4532 if (OldVar->getInit()) { 4533 EnterExpressionEvaluationContext Evaluated( 4534 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var); 4535 4536 // Instantiate the initializer. 4537 ExprResult Init; 4538 4539 { 4540 ContextRAII SwitchContext(*this, Var->getDeclContext()); 4541 Init = SubstInitializer(OldVar->getInit(), TemplateArgs, 4542 OldVar->getInitStyle() == VarDecl::CallInit); 4543 } 4544 4545 if (!Init.isInvalid()) { 4546 Expr *InitExpr = Init.get(); 4547 4548 if (Var->hasAttr<DLLImportAttr>() && 4549 (!InitExpr || 4550 !InitExpr->isConstantInitializer(getASTContext(), false))) { 4551 // Do not dynamically initialize dllimport variables. 4552 } else if (InitExpr) { 4553 bool DirectInit = OldVar->isDirectInit(); 4554 AddInitializerToDecl(Var, InitExpr, DirectInit); 4555 } else 4556 ActOnUninitializedDecl(Var); 4557 } else { 4558 // FIXME: Not too happy about invalidating the declaration 4559 // because of a bogus initializer. 4560 Var->setInvalidDecl(); 4561 } 4562 } else { 4563 // `inline` variables are a definition and declaration all in one; we won't 4564 // pick up an initializer from anywhere else. 4565 if (Var->isStaticDataMember() && !Var->isInline()) { 4566 if (!Var->isOutOfLine()) 4567 return; 4568 4569 // If the declaration inside the class had an initializer, don't add 4570 // another one to the out-of-line definition. 4571 if (OldVar->getFirstDecl()->hasInit()) 4572 return; 4573 } 4574 4575 // We'll add an initializer to a for-range declaration later. 4576 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl()) 4577 return; 4578 4579 ActOnUninitializedDecl(Var); 4580 } 4581 4582 if (getLangOpts().CUDA) 4583 checkAllowedCUDAInitializer(Var); 4584 } 4585 4586 /// Instantiate the definition of the given variable from its 4587 /// template. 4588 /// 4589 /// \param PointOfInstantiation the point at which the instantiation was 4590 /// required. Note that this is not precisely a "point of instantiation" 4591 /// for the variable, but it's close. 4592 /// 4593 /// \param Var the already-instantiated declaration of a templated variable. 4594 /// 4595 /// \param Recursive if true, recursively instantiates any functions that 4596 /// are required by this instantiation. 4597 /// 4598 /// \param DefinitionRequired if true, then we are performing an explicit 4599 /// instantiation where a definition of the variable is required. Complain 4600 /// if there is no such definition. 4601 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 4602 VarDecl *Var, bool Recursive, 4603 bool DefinitionRequired, bool AtEndOfTU) { 4604 if (Var->isInvalidDecl()) 4605 return; 4606 4607 // Never instantiate an explicitly-specialized entity. 4608 TemplateSpecializationKind TSK = 4609 Var->getTemplateSpecializationKindForInstantiation(); 4610 if (TSK == TSK_ExplicitSpecialization) 4611 return; 4612 4613 // Find the pattern and the arguments to substitute into it. 4614 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern(); 4615 assert(PatternDecl && "no pattern for templated variable"); 4616 MultiLevelTemplateArgumentList TemplateArgs = 4617 getTemplateInstantiationArgs(Var); 4618 4619 VarTemplateSpecializationDecl *VarSpec = 4620 dyn_cast<VarTemplateSpecializationDecl>(Var); 4621 if (VarSpec) { 4622 // If this is a variable template specialization, make sure that it is 4623 // non-dependent. 4624 bool InstantiationDependent = false; 4625 assert(!TemplateSpecializationType::anyDependentTemplateArguments( 4626 VarSpec->getTemplateArgsInfo(), InstantiationDependent) && 4627 "Only instantiate variable template specializations that are " 4628 "not type-dependent"); 4629 (void)InstantiationDependent; 4630 4631 // If this is a static data member template, there might be an 4632 // uninstantiated initializer on the declaration. If so, instantiate 4633 // it now. 4634 // 4635 // FIXME: This largely duplicates what we would do below. The difference 4636 // is that along this path we may instantiate an initializer from an 4637 // in-class declaration of the template and instantiate the definition 4638 // from a separate out-of-class definition. 4639 if (PatternDecl->isStaticDataMember() && 4640 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 4641 !Var->hasInit()) { 4642 // FIXME: Factor out the duplicated instantiation context setup/tear down 4643 // code here. 4644 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 4645 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4646 return; 4647 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 4648 "instantiating variable initializer"); 4649 4650 // The instantiation is visible here, even if it was first declared in an 4651 // unimported module. 4652 Var->setVisibleDespiteOwningModule(); 4653 4654 // If we're performing recursive template instantiation, create our own 4655 // queue of pending implicit instantiations that we will instantiate 4656 // later, while we're still within our own instantiation context. 4657 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4658 /*Enabled=*/Recursive); 4659 LocalInstantiationScope Local(*this); 4660 LocalEagerInstantiationScope LocalInstantiations(*this); 4661 4662 // Enter the scope of this instantiation. We don't use 4663 // PushDeclContext because we don't have a scope. 4664 ContextRAII PreviousContext(*this, Var->getDeclContext()); 4665 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 4666 PreviousContext.pop(); 4667 4668 // This variable may have local implicit instantiations that need to be 4669 // instantiated within this scope. 4670 LocalInstantiations.perform(); 4671 Local.Exit(); 4672 GlobalInstantiations.perform(); 4673 } 4674 } else { 4675 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && 4676 "not a static data member?"); 4677 } 4678 4679 VarDecl *Def = PatternDecl->getDefinition(getASTContext()); 4680 4681 // If we don't have a definition of the variable template, we won't perform 4682 // any instantiation. Rather, we rely on the user to instantiate this 4683 // definition (or provide a specialization for it) in another translation 4684 // unit. 4685 if (!Def && !DefinitionRequired) { 4686 if (TSK == TSK_ExplicitInstantiationDefinition) { 4687 PendingInstantiations.push_back( 4688 std::make_pair(Var, PointOfInstantiation)); 4689 } else if (TSK == TSK_ImplicitInstantiation) { 4690 // Warn about missing definition at the end of translation unit. 4691 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 4692 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 4693 Diag(PointOfInstantiation, diag::warn_var_template_missing) 4694 << Var; 4695 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 4696 if (getLangOpts().CPlusPlus11) 4697 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var; 4698 } 4699 return; 4700 } 4701 } 4702 4703 // FIXME: We need to track the instantiation stack in order to know which 4704 // definitions should be visible within this instantiation. 4705 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember(). 4706 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var, 4707 /*InstantiatedFromMember*/false, 4708 PatternDecl, Def, TSK, 4709 /*Complain*/DefinitionRequired)) 4710 return; 4711 4712 // C++11 [temp.explicit]p10: 4713 // Except for inline functions, const variables of literal types, variables 4714 // of reference types, [...] explicit instantiation declarations 4715 // have the effect of suppressing the implicit instantiation of the entity 4716 // to which they refer. 4717 if (TSK == TSK_ExplicitInstantiationDeclaration && 4718 !Var->isUsableInConstantExpressions(getASTContext())) 4719 return; 4720 4721 // Make sure to pass the instantiated variable to the consumer at the end. 4722 struct PassToConsumerRAII { 4723 ASTConsumer &Consumer; 4724 VarDecl *Var; 4725 4726 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 4727 : Consumer(Consumer), Var(Var) { } 4728 4729 ~PassToConsumerRAII() { 4730 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 4731 } 4732 } PassToConsumerRAII(Consumer, Var); 4733 4734 // If we already have a definition, we're done. 4735 if (VarDecl *Def = Var->getDefinition()) { 4736 // We may be explicitly instantiating something we've already implicitly 4737 // instantiated. 4738 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 4739 PointOfInstantiation); 4740 return; 4741 } 4742 4743 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 4744 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4745 return; 4746 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 4747 "instantiating variable definition"); 4748 4749 // If we're performing recursive template instantiation, create our own 4750 // queue of pending implicit instantiations that we will instantiate later, 4751 // while we're still within our own instantiation context. 4752 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4753 /*Enabled=*/Recursive); 4754 4755 // Enter the scope of this instantiation. We don't use 4756 // PushDeclContext because we don't have a scope. 4757 ContextRAII PreviousContext(*this, Var->getDeclContext()); 4758 LocalInstantiationScope Local(*this); 4759 4760 LocalEagerInstantiationScope LocalInstantiations(*this); 4761 4762 VarDecl *OldVar = Var; 4763 if (Def->isStaticDataMember() && !Def->isOutOfLine()) { 4764 // We're instantiating an inline static data member whose definition was 4765 // provided inside the class. 4766 InstantiateVariableInitializer(Var, Def, TemplateArgs); 4767 } else if (!VarSpec) { 4768 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 4769 TemplateArgs)); 4770 } else if (Var->isStaticDataMember() && 4771 Var->getLexicalDeclContext()->isRecord()) { 4772 // We need to instantiate the definition of a static data member template, 4773 // and all we have is the in-class declaration of it. Instantiate a separate 4774 // declaration of the definition. 4775 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 4776 TemplateArgs); 4777 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 4778 VarSpec->getSpecializedTemplate(), Def, nullptr, 4779 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray())); 4780 if (Var) { 4781 llvm::PointerUnion<VarTemplateDecl *, 4782 VarTemplatePartialSpecializationDecl *> PatternPtr = 4783 VarSpec->getSpecializedTemplateOrPartial(); 4784 if (VarTemplatePartialSpecializationDecl *Partial = 4785 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 4786 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 4787 Partial, &VarSpec->getTemplateInstantiationArgs()); 4788 4789 // Merge the definition with the declaration. 4790 LookupResult R(*this, Var->getDeclName(), Var->getLocation(), 4791 LookupOrdinaryName, forRedeclarationInCurContext()); 4792 R.addDecl(OldVar); 4793 MergeVarDecl(Var, R); 4794 4795 // Attach the initializer. 4796 InstantiateVariableInitializer(Var, Def, TemplateArgs); 4797 } 4798 } else 4799 // Complete the existing variable's definition with an appropriately 4800 // substituted type and initializer. 4801 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 4802 4803 PreviousContext.pop(); 4804 4805 if (Var) { 4806 PassToConsumerRAII.Var = Var; 4807 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 4808 OldVar->getPointOfInstantiation()); 4809 } 4810 4811 // This variable may have local implicit instantiations that need to be 4812 // instantiated within this scope. 4813 LocalInstantiations.perform(); 4814 Local.Exit(); 4815 GlobalInstantiations.perform(); 4816 } 4817 4818 void 4819 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 4820 const CXXConstructorDecl *Tmpl, 4821 const MultiLevelTemplateArgumentList &TemplateArgs) { 4822 4823 SmallVector<CXXCtorInitializer*, 4> NewInits; 4824 bool AnyErrors = Tmpl->isInvalidDecl(); 4825 4826 // Instantiate all the initializers. 4827 for (const auto *Init : Tmpl->inits()) { 4828 // Only instantiate written initializers, let Sema re-construct implicit 4829 // ones. 4830 if (!Init->isWritten()) 4831 continue; 4832 4833 SourceLocation EllipsisLoc; 4834 4835 if (Init->isPackExpansion()) { 4836 // This is a pack expansion. We should expand it now. 4837 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 4838 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 4839 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 4840 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 4841 bool ShouldExpand = false; 4842 bool RetainExpansion = false; 4843 Optional<unsigned> NumExpansions; 4844 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 4845 BaseTL.getSourceRange(), 4846 Unexpanded, 4847 TemplateArgs, ShouldExpand, 4848 RetainExpansion, 4849 NumExpansions)) { 4850 AnyErrors = true; 4851 New->setInvalidDecl(); 4852 continue; 4853 } 4854 assert(ShouldExpand && "Partial instantiation of base initializer?"); 4855 4856 // Loop over all of the arguments in the argument pack(s), 4857 for (unsigned I = 0; I != *NumExpansions; ++I) { 4858 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 4859 4860 // Instantiate the initializer. 4861 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4862 /*CXXDirectInit=*/true); 4863 if (TempInit.isInvalid()) { 4864 AnyErrors = true; 4865 break; 4866 } 4867 4868 // Instantiate the base type. 4869 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 4870 TemplateArgs, 4871 Init->getSourceLocation(), 4872 New->getDeclName()); 4873 if (!BaseTInfo) { 4874 AnyErrors = true; 4875 break; 4876 } 4877 4878 // Build the initializer. 4879 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 4880 BaseTInfo, TempInit.get(), 4881 New->getParent(), 4882 SourceLocation()); 4883 if (NewInit.isInvalid()) { 4884 AnyErrors = true; 4885 break; 4886 } 4887 4888 NewInits.push_back(NewInit.get()); 4889 } 4890 4891 continue; 4892 } 4893 4894 // Instantiate the initializer. 4895 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4896 /*CXXDirectInit=*/true); 4897 if (TempInit.isInvalid()) { 4898 AnyErrors = true; 4899 continue; 4900 } 4901 4902 MemInitResult NewInit; 4903 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 4904 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 4905 TemplateArgs, 4906 Init->getSourceLocation(), 4907 New->getDeclName()); 4908 if (!TInfo) { 4909 AnyErrors = true; 4910 New->setInvalidDecl(); 4911 continue; 4912 } 4913 4914 if (Init->isBaseInitializer()) 4915 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(), 4916 New->getParent(), EllipsisLoc); 4917 else 4918 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(), 4919 cast<CXXRecordDecl>(CurContext->getParent())); 4920 } else if (Init->isMemberInitializer()) { 4921 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 4922 Init->getMemberLocation(), 4923 Init->getMember(), 4924 TemplateArgs)); 4925 if (!Member) { 4926 AnyErrors = true; 4927 New->setInvalidDecl(); 4928 continue; 4929 } 4930 4931 NewInit = BuildMemberInitializer(Member, TempInit.get(), 4932 Init->getSourceLocation()); 4933 } else if (Init->isIndirectMemberInitializer()) { 4934 IndirectFieldDecl *IndirectMember = 4935 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 4936 Init->getMemberLocation(), 4937 Init->getIndirectMember(), TemplateArgs)); 4938 4939 if (!IndirectMember) { 4940 AnyErrors = true; 4941 New->setInvalidDecl(); 4942 continue; 4943 } 4944 4945 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(), 4946 Init->getSourceLocation()); 4947 } 4948 4949 if (NewInit.isInvalid()) { 4950 AnyErrors = true; 4951 New->setInvalidDecl(); 4952 } else { 4953 NewInits.push_back(NewInit.get()); 4954 } 4955 } 4956 4957 // Assign all the initializers to the new constructor. 4958 ActOnMemInitializers(New, 4959 /*FIXME: ColonLoc */ 4960 SourceLocation(), 4961 NewInits, 4962 AnyErrors); 4963 } 4964 4965 // TODO: this could be templated if the various decl types used the 4966 // same method name. 4967 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 4968 ClassTemplateDecl *Instance) { 4969 Pattern = Pattern->getCanonicalDecl(); 4970 4971 do { 4972 Instance = Instance->getCanonicalDecl(); 4973 if (Pattern == Instance) return true; 4974 Instance = Instance->getInstantiatedFromMemberTemplate(); 4975 } while (Instance); 4976 4977 return false; 4978 } 4979 4980 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 4981 FunctionTemplateDecl *Instance) { 4982 Pattern = Pattern->getCanonicalDecl(); 4983 4984 do { 4985 Instance = Instance->getCanonicalDecl(); 4986 if (Pattern == Instance) return true; 4987 Instance = Instance->getInstantiatedFromMemberTemplate(); 4988 } while (Instance); 4989 4990 return false; 4991 } 4992 4993 static bool 4994 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 4995 ClassTemplatePartialSpecializationDecl *Instance) { 4996 Pattern 4997 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 4998 do { 4999 Instance = cast<ClassTemplatePartialSpecializationDecl>( 5000 Instance->getCanonicalDecl()); 5001 if (Pattern == Instance) 5002 return true; 5003 Instance = Instance->getInstantiatedFromMember(); 5004 } while (Instance); 5005 5006 return false; 5007 } 5008 5009 static bool isInstantiationOf(CXXRecordDecl *Pattern, 5010 CXXRecordDecl *Instance) { 5011 Pattern = Pattern->getCanonicalDecl(); 5012 5013 do { 5014 Instance = Instance->getCanonicalDecl(); 5015 if (Pattern == Instance) return true; 5016 Instance = Instance->getInstantiatedFromMemberClass(); 5017 } while (Instance); 5018 5019 return false; 5020 } 5021 5022 static bool isInstantiationOf(FunctionDecl *Pattern, 5023 FunctionDecl *Instance) { 5024 Pattern = Pattern->getCanonicalDecl(); 5025 5026 do { 5027 Instance = Instance->getCanonicalDecl(); 5028 if (Pattern == Instance) return true; 5029 Instance = Instance->getInstantiatedFromMemberFunction(); 5030 } while (Instance); 5031 5032 return false; 5033 } 5034 5035 static bool isInstantiationOf(EnumDecl *Pattern, 5036 EnumDecl *Instance) { 5037 Pattern = Pattern->getCanonicalDecl(); 5038 5039 do { 5040 Instance = Instance->getCanonicalDecl(); 5041 if (Pattern == Instance) return true; 5042 Instance = Instance->getInstantiatedFromMemberEnum(); 5043 } while (Instance); 5044 5045 return false; 5046 } 5047 5048 static bool isInstantiationOf(UsingShadowDecl *Pattern, 5049 UsingShadowDecl *Instance, 5050 ASTContext &C) { 5051 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance), 5052 Pattern); 5053 } 5054 5055 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance, 5056 ASTContext &C) { 5057 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 5058 } 5059 5060 template<typename T> 5061 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, 5062 ASTContext &Ctx) { 5063 // An unresolved using declaration can instantiate to an unresolved using 5064 // declaration, or to a using declaration or a using declaration pack. 5065 // 5066 // Multiple declarations can claim to be instantiated from an unresolved 5067 // using declaration if it's a pack expansion. We want the UsingPackDecl 5068 // in that case, not the individual UsingDecls within the pack. 5069 bool OtherIsPackExpansion; 5070 NamedDecl *OtherFrom; 5071 if (auto *OtherUUD = dyn_cast<T>(Other)) { 5072 OtherIsPackExpansion = OtherUUD->isPackExpansion(); 5073 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD); 5074 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) { 5075 OtherIsPackExpansion = true; 5076 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl(); 5077 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) { 5078 OtherIsPackExpansion = false; 5079 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD); 5080 } else { 5081 return false; 5082 } 5083 return Pattern->isPackExpansion() == OtherIsPackExpansion && 5084 declaresSameEntity(OtherFrom, Pattern); 5085 } 5086 5087 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 5088 VarDecl *Instance) { 5089 assert(Instance->isStaticDataMember()); 5090 5091 Pattern = Pattern->getCanonicalDecl(); 5092 5093 do { 5094 Instance = Instance->getCanonicalDecl(); 5095 if (Pattern == Instance) return true; 5096 Instance = Instance->getInstantiatedFromStaticDataMember(); 5097 } while (Instance); 5098 5099 return false; 5100 } 5101 5102 // Other is the prospective instantiation 5103 // D is the prospective pattern 5104 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 5105 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) 5106 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5107 5108 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D)) 5109 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5110 5111 if (D->getKind() != Other->getKind()) 5112 return false; 5113 5114 if (auto *Record = dyn_cast<CXXRecordDecl>(Other)) 5115 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 5116 5117 if (auto *Function = dyn_cast<FunctionDecl>(Other)) 5118 return isInstantiationOf(cast<FunctionDecl>(D), Function); 5119 5120 if (auto *Enum = dyn_cast<EnumDecl>(Other)) 5121 return isInstantiationOf(cast<EnumDecl>(D), Enum); 5122 5123 if (auto *Var = dyn_cast<VarDecl>(Other)) 5124 if (Var->isStaticDataMember()) 5125 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 5126 5127 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other)) 5128 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 5129 5130 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 5131 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 5132 5133 if (auto *PartialSpec = 5134 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 5135 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 5136 PartialSpec); 5137 5138 if (auto *Field = dyn_cast<FieldDecl>(Other)) { 5139 if (!Field->getDeclName()) { 5140 // This is an unnamed field. 5141 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field), 5142 cast<FieldDecl>(D)); 5143 } 5144 } 5145 5146 if (auto *Using = dyn_cast<UsingDecl>(Other)) 5147 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 5148 5149 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other)) 5150 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 5151 5152 return D->getDeclName() && 5153 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 5154 } 5155 5156 template<typename ForwardIterator> 5157 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 5158 NamedDecl *D, 5159 ForwardIterator first, 5160 ForwardIterator last) { 5161 for (; first != last; ++first) 5162 if (isInstantiationOf(Ctx, D, *first)) 5163 return cast<NamedDecl>(*first); 5164 5165 return nullptr; 5166 } 5167 5168 /// Finds the instantiation of the given declaration context 5169 /// within the current instantiation. 5170 /// 5171 /// \returns NULL if there was an error 5172 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 5173 const MultiLevelTemplateArgumentList &TemplateArgs) { 5174 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 5175 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true); 5176 return cast_or_null<DeclContext>(ID); 5177 } else return DC; 5178 } 5179 5180 /// Find the instantiation of the given declaration within the 5181 /// current instantiation. 5182 /// 5183 /// This routine is intended to be used when \p D is a declaration 5184 /// referenced from within a template, that needs to mapped into the 5185 /// corresponding declaration within an instantiation. For example, 5186 /// given: 5187 /// 5188 /// \code 5189 /// template<typename T> 5190 /// struct X { 5191 /// enum Kind { 5192 /// KnownValue = sizeof(T) 5193 /// }; 5194 /// 5195 /// bool getKind() const { return KnownValue; } 5196 /// }; 5197 /// 5198 /// template struct X<int>; 5199 /// \endcode 5200 /// 5201 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the 5202 /// \p EnumConstantDecl for \p KnownValue (which refers to 5203 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation 5204 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs 5205 /// this mapping from within the instantiation of <tt>X<int></tt>. 5206 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 5207 const MultiLevelTemplateArgumentList &TemplateArgs, 5208 bool FindingInstantiatedContext) { 5209 DeclContext *ParentDC = D->getDeclContext(); 5210 // FIXME: Parmeters of pointer to functions (y below) that are themselves 5211 // parameters (p below) can have their ParentDC set to the translation-unit 5212 // - thus we can not consistently check if the ParentDC of such a parameter 5213 // is Dependent or/and a FunctionOrMethod. 5214 // For e.g. this code, during Template argument deduction tries to 5215 // find an instantiated decl for (T y) when the ParentDC for y is 5216 // the translation unit. 5217 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 5218 // float baz(float(*)()) { return 0.0; } 5219 // Foo(baz); 5220 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 5221 // it gets here, always has a FunctionOrMethod as its ParentDC?? 5222 // For now: 5223 // - as long as we have a ParmVarDecl whose parent is non-dependent and 5224 // whose type is not instantiation dependent, do nothing to the decl 5225 // - otherwise find its instantiated decl. 5226 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() && 5227 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 5228 return D; 5229 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 5230 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 5231 ((ParentDC->isFunctionOrMethod() || 5232 isa<OMPDeclareReductionDecl>(ParentDC) || 5233 isa<OMPDeclareMapperDecl>(ParentDC)) && 5234 ParentDC->isDependentContext()) || 5235 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 5236 // D is a local of some kind. Look into the map of local 5237 // declarations to their instantiations. 5238 if (CurrentInstantiationScope) { 5239 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) { 5240 if (Decl *FD = Found->dyn_cast<Decl *>()) 5241 return cast<NamedDecl>(FD); 5242 5243 int PackIdx = ArgumentPackSubstitutionIndex; 5244 assert(PackIdx != -1 && 5245 "found declaration pack but not pack expanding"); 5246 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 5247 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 5248 } 5249 } 5250 5251 // If we're performing a partial substitution during template argument 5252 // deduction, we may not have values for template parameters yet. They 5253 // just map to themselves. 5254 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 5255 isa<TemplateTemplateParmDecl>(D)) 5256 return D; 5257 5258 if (D->isInvalidDecl()) 5259 return nullptr; 5260 5261 // Normally this function only searches for already instantiated declaration 5262 // however we have to make an exclusion for local types used before 5263 // definition as in the code: 5264 // 5265 // template<typename T> void f1() { 5266 // void g1(struct x1); 5267 // struct x1 {}; 5268 // } 5269 // 5270 // In this case instantiation of the type of 'g1' requires definition of 5271 // 'x1', which is defined later. Error recovery may produce an enum used 5272 // before definition. In these cases we need to instantiate relevant 5273 // declarations here. 5274 bool NeedInstantiate = false; 5275 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 5276 NeedInstantiate = RD->isLocalClass(); 5277 else 5278 NeedInstantiate = isa<EnumDecl>(D); 5279 if (NeedInstantiate) { 5280 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 5281 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 5282 return cast<TypeDecl>(Inst); 5283 } 5284 5285 // If we didn't find the decl, then we must have a label decl that hasn't 5286 // been found yet. Lazily instantiate it and return it now. 5287 assert(isa<LabelDecl>(D)); 5288 5289 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 5290 assert(Inst && "Failed to instantiate label??"); 5291 5292 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 5293 return cast<LabelDecl>(Inst); 5294 } 5295 5296 // For variable template specializations, update those that are still 5297 // type-dependent. 5298 if (VarTemplateSpecializationDecl *VarSpec = 5299 dyn_cast<VarTemplateSpecializationDecl>(D)) { 5300 bool InstantiationDependent = false; 5301 const TemplateArgumentListInfo &VarTemplateArgs = 5302 VarSpec->getTemplateArgsInfo(); 5303 if (TemplateSpecializationType::anyDependentTemplateArguments( 5304 VarTemplateArgs, InstantiationDependent)) 5305 D = cast<NamedDecl>( 5306 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs)); 5307 return D; 5308 } 5309 5310 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 5311 if (!Record->isDependentContext()) 5312 return D; 5313 5314 // Determine whether this record is the "templated" declaration describing 5315 // a class template or class template partial specialization. 5316 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 5317 if (ClassTemplate) 5318 ClassTemplate = ClassTemplate->getCanonicalDecl(); 5319 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5320 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 5321 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 5322 5323 // Walk the current context to find either the record or an instantiation of 5324 // it. 5325 DeclContext *DC = CurContext; 5326 while (!DC->isFileContext()) { 5327 // If we're performing substitution while we're inside the template 5328 // definition, we'll find our own context. We're done. 5329 if (DC->Equals(Record)) 5330 return Record; 5331 5332 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 5333 // Check whether we're in the process of instantiating a class template 5334 // specialization of the template we're mapping. 5335 if (ClassTemplateSpecializationDecl *InstSpec 5336 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 5337 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 5338 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 5339 return InstRecord; 5340 } 5341 5342 // Check whether we're in the process of instantiating a member class. 5343 if (isInstantiationOf(Record, InstRecord)) 5344 return InstRecord; 5345 } 5346 5347 // Move to the outer template scope. 5348 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 5349 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 5350 DC = FD->getLexicalDeclContext(); 5351 continue; 5352 } 5353 // An implicit deduction guide acts as if it's within the class template 5354 // specialization described by its name and first N template params. 5355 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD); 5356 if (Guide && Guide->isImplicit()) { 5357 TemplateDecl *TD = Guide->getDeducedTemplate(); 5358 // Convert the arguments to an "as-written" list. 5359 TemplateArgumentListInfo Args(Loc, Loc); 5360 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front( 5361 TD->getTemplateParameters()->size())) { 5362 ArrayRef<TemplateArgument> Unpacked(Arg); 5363 if (Arg.getKind() == TemplateArgument::Pack) 5364 Unpacked = Arg.pack_elements(); 5365 for (TemplateArgument UnpackedArg : Unpacked) 5366 Args.addArgument( 5367 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc)); 5368 } 5369 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args); 5370 if (T.isNull()) 5371 return nullptr; 5372 auto *SubstRecord = T->getAsCXXRecordDecl(); 5373 assert(SubstRecord && "class template id not a class type?"); 5374 // Check that this template-id names the primary template and not a 5375 // partial or explicit specialization. (In the latter cases, it's 5376 // meaningless to attempt to find an instantiation of D within the 5377 // specialization.) 5378 // FIXME: The standard doesn't say what should happen here. 5379 if (FindingInstantiatedContext && 5380 usesPartialOrExplicitSpecialization( 5381 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) { 5382 Diag(Loc, diag::err_specialization_not_primary_template) 5383 << T << (SubstRecord->getTemplateSpecializationKind() == 5384 TSK_ExplicitSpecialization); 5385 return nullptr; 5386 } 5387 DC = SubstRecord; 5388 continue; 5389 } 5390 } 5391 5392 DC = DC->getParent(); 5393 } 5394 5395 // Fall through to deal with other dependent record types (e.g., 5396 // anonymous unions in class templates). 5397 } 5398 5399 if (!ParentDC->isDependentContext()) 5400 return D; 5401 5402 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 5403 if (!ParentDC) 5404 return nullptr; 5405 5406 if (ParentDC != D->getDeclContext()) { 5407 // We performed some kind of instantiation in the parent context, 5408 // so now we need to look into the instantiated parent context to 5409 // find the instantiation of the declaration D. 5410 5411 // If our context used to be dependent, we may need to instantiate 5412 // it before performing lookup into that context. 5413 bool IsBeingInstantiated = false; 5414 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 5415 if (!Spec->isDependentContext()) { 5416 QualType T = Context.getTypeDeclType(Spec); 5417 const RecordType *Tag = T->getAs<RecordType>(); 5418 assert(Tag && "type of non-dependent record is not a RecordType"); 5419 if (Tag->isBeingDefined()) 5420 IsBeingInstantiated = true; 5421 if (!Tag->isBeingDefined() && 5422 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 5423 return nullptr; 5424 5425 ParentDC = Tag->getDecl(); 5426 } 5427 } 5428 5429 NamedDecl *Result = nullptr; 5430 // FIXME: If the name is a dependent name, this lookup won't necessarily 5431 // find it. Does that ever matter? 5432 if (auto Name = D->getDeclName()) { 5433 DeclarationNameInfo NameInfo(Name, D->getLocation()); 5434 Name = SubstDeclarationNameInfo(NameInfo, TemplateArgs).getName(); 5435 if (!Name) 5436 return nullptr; 5437 DeclContext::lookup_result Found = ParentDC->lookup(Name); 5438 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 5439 } else { 5440 // Since we don't have a name for the entity we're looking for, 5441 // our only option is to walk through all of the declarations to 5442 // find that name. This will occur in a few cases: 5443 // 5444 // - anonymous struct/union within a template 5445 // - unnamed class/struct/union/enum within a template 5446 // 5447 // FIXME: Find a better way to find these instantiations! 5448 Result = findInstantiationOf(Context, D, 5449 ParentDC->decls_begin(), 5450 ParentDC->decls_end()); 5451 } 5452 5453 if (!Result) { 5454 if (isa<UsingShadowDecl>(D)) { 5455 // UsingShadowDecls can instantiate to nothing because of using hiding. 5456 } else if (Diags.hasErrorOccurred()) { 5457 // We've already complained about something, so most likely this 5458 // declaration failed to instantiate. There's no point in complaining 5459 // further, since this is normal in invalid code. 5460 } else if (IsBeingInstantiated) { 5461 // The class in which this member exists is currently being 5462 // instantiated, and we haven't gotten around to instantiating this 5463 // member yet. This can happen when the code uses forward declarations 5464 // of member classes, and introduces ordering dependencies via 5465 // template instantiation. 5466 Diag(Loc, diag::err_member_not_yet_instantiated) 5467 << D->getDeclName() 5468 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 5469 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 5470 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 5471 // This enumeration constant was found when the template was defined, 5472 // but can't be found in the instantiation. This can happen if an 5473 // unscoped enumeration member is explicitly specialized. 5474 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 5475 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 5476 TemplateArgs)); 5477 assert(Spec->getTemplateSpecializationKind() == 5478 TSK_ExplicitSpecialization); 5479 Diag(Loc, diag::err_enumerator_does_not_exist) 5480 << D->getDeclName() 5481 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 5482 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 5483 << Context.getTypeDeclType(Spec); 5484 } else { 5485 // We should have found something, but didn't. 5486 llvm_unreachable("Unable to find instantiation of declaration!"); 5487 } 5488 } 5489 5490 D = Result; 5491 } 5492 5493 return D; 5494 } 5495 5496 /// Performs template instantiation for all implicit template 5497 /// instantiations we have seen until this point. 5498 void Sema::PerformPendingInstantiations(bool LocalOnly) { 5499 while (!PendingLocalImplicitInstantiations.empty() || 5500 (!LocalOnly && !PendingInstantiations.empty())) { 5501 PendingImplicitInstantiation Inst; 5502 5503 if (PendingLocalImplicitInstantiations.empty()) { 5504 Inst = PendingInstantiations.front(); 5505 PendingInstantiations.pop_front(); 5506 } else { 5507 Inst = PendingLocalImplicitInstantiations.front(); 5508 PendingLocalImplicitInstantiations.pop_front(); 5509 } 5510 5511 // Instantiate function definitions 5512 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 5513 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 5514 TSK_ExplicitInstantiationDefinition; 5515 if (Function->isMultiVersion()) { 5516 getASTContext().forEachMultiversionedFunctionVersion( 5517 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) { 5518 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true, 5519 DefinitionRequired, true); 5520 if (CurFD->isDefined()) 5521 CurFD->setInstantiationIsPending(false); 5522 }); 5523 } else { 5524 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true, 5525 DefinitionRequired, true); 5526 if (Function->isDefined()) 5527 Function->setInstantiationIsPending(false); 5528 } 5529 continue; 5530 } 5531 5532 // Instantiate variable definitions 5533 VarDecl *Var = cast<VarDecl>(Inst.first); 5534 5535 assert((Var->isStaticDataMember() || 5536 isa<VarTemplateSpecializationDecl>(Var)) && 5537 "Not a static data member, nor a variable template" 5538 " specialization?"); 5539 5540 // Don't try to instantiate declarations if the most recent redeclaration 5541 // is invalid. 5542 if (Var->getMostRecentDecl()->isInvalidDecl()) 5543 continue; 5544 5545 // Check if the most recent declaration has changed the specialization kind 5546 // and removed the need for implicit instantiation. 5547 switch (Var->getMostRecentDecl() 5548 ->getTemplateSpecializationKindForInstantiation()) { 5549 case TSK_Undeclared: 5550 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 5551 case TSK_ExplicitInstantiationDeclaration: 5552 case TSK_ExplicitSpecialization: 5553 continue; // No longer need to instantiate this type. 5554 case TSK_ExplicitInstantiationDefinition: 5555 // We only need an instantiation if the pending instantiation *is* the 5556 // explicit instantiation. 5557 if (Var != Var->getMostRecentDecl()) 5558 continue; 5559 break; 5560 case TSK_ImplicitInstantiation: 5561 break; 5562 } 5563 5564 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 5565 "instantiating variable definition"); 5566 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 5567 TSK_ExplicitInstantiationDefinition; 5568 5569 // Instantiate static data member definitions or variable template 5570 // specializations. 5571 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 5572 DefinitionRequired, true); 5573 } 5574 } 5575 5576 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 5577 const MultiLevelTemplateArgumentList &TemplateArgs) { 5578 for (auto DD : Pattern->ddiags()) { 5579 switch (DD->getKind()) { 5580 case DependentDiagnostic::Access: 5581 HandleDependentAccessCheck(*DD, TemplateArgs); 5582 break; 5583 } 5584 } 5585 } 5586