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