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