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