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