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