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