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