xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
10b57cec5SDimitry Andric //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //===----------------------------------------------------------------------===/
70b57cec5SDimitry Andric //
80b57cec5SDimitry Andric //  This file implements C++ template instantiation for declarations.
90b57cec5SDimitry Andric //
100b57cec5SDimitry Andric //===----------------------------------------------------------------------===/
115ffd83dbSDimitry Andric 
120b57cec5SDimitry Andric #include "clang/AST/ASTConsumer.h"
130b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
140b57cec5SDimitry Andric #include "clang/AST/ASTMutationListener.h"
150b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
160b57cec5SDimitry Andric #include "clang/AST/DeclVisitor.h"
170b57cec5SDimitry Andric #include "clang/AST/DependentDiagnostic.h"
180b57cec5SDimitry Andric #include "clang/AST/Expr.h"
190b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
200b57cec5SDimitry Andric #include "clang/AST/PrettyDeclStackTrace.h"
210b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
225ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h"
235ffd83dbSDimitry Andric #include "clang/Basic/TargetInfo.h"
240b57cec5SDimitry Andric #include "clang/Sema/Initialization.h"
250b57cec5SDimitry Andric #include "clang/Sema/Lookup.h"
265ffd83dbSDimitry Andric #include "clang/Sema/SemaInternal.h"
270b57cec5SDimitry Andric #include "clang/Sema/Template.h"
280b57cec5SDimitry Andric #include "clang/Sema/TemplateInstCallback.h"
290b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric using namespace clang;
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric static bool isDeclWithinFunction(const Decl *D) {
340b57cec5SDimitry Andric   const DeclContext *DC = D->getDeclContext();
350b57cec5SDimitry Andric   if (DC->isFunctionOrMethod())
360b57cec5SDimitry Andric     return true;
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric   if (DC->isRecord())
390b57cec5SDimitry Andric     return cast<CXXRecordDecl>(DC)->isLocalClass();
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric   return false;
420b57cec5SDimitry Andric }
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric template<typename DeclT>
450b57cec5SDimitry Andric static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
460b57cec5SDimitry Andric                            const MultiLevelTemplateArgumentList &TemplateArgs) {
470b57cec5SDimitry Andric   if (!OldDecl->getQualifierLoc())
480b57cec5SDimitry Andric     return false;
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric   assert((NewDecl->getFriendObjectKind() ||
510b57cec5SDimitry Andric           !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
520b57cec5SDimitry Andric          "non-friend with qualified name defined in dependent context");
530b57cec5SDimitry Andric   Sema::ContextRAII SavedContext(
540b57cec5SDimitry Andric       SemaRef,
550b57cec5SDimitry Andric       const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
560b57cec5SDimitry Andric                                     ? NewDecl->getLexicalDeclContext()
570b57cec5SDimitry Andric                                     : OldDecl->getLexicalDeclContext()));
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric   NestedNameSpecifierLoc NewQualifierLoc
600b57cec5SDimitry Andric       = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
610b57cec5SDimitry Andric                                             TemplateArgs);
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric   if (!NewQualifierLoc)
640b57cec5SDimitry Andric     return true;
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric   NewDecl->setQualifierInfo(NewQualifierLoc);
670b57cec5SDimitry Andric   return false;
680b57cec5SDimitry Andric }
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
710b57cec5SDimitry Andric                                               DeclaratorDecl *NewDecl) {
720b57cec5SDimitry Andric   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
730b57cec5SDimitry Andric }
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
760b57cec5SDimitry Andric                                               TagDecl *NewDecl) {
770b57cec5SDimitry Andric   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric // Include attribute instantiation code.
810b57cec5SDimitry Andric #include "clang/Sema/AttrTemplateInstantiate.inc"
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric static void instantiateDependentAlignedAttr(
840b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
850b57cec5SDimitry Andric     const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
860b57cec5SDimitry Andric   if (Aligned->isAlignmentExpr()) {
870b57cec5SDimitry Andric     // The alignment expression is a constant expression.
880b57cec5SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
890b57cec5SDimitry Andric         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
900b57cec5SDimitry Andric     ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
910b57cec5SDimitry Andric     if (!Result.isInvalid())
92a7dea167SDimitry Andric       S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
930b57cec5SDimitry Andric   } else {
940b57cec5SDimitry Andric     TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
950b57cec5SDimitry Andric                                          TemplateArgs, Aligned->getLocation(),
960b57cec5SDimitry Andric                                          DeclarationName());
970b57cec5SDimitry Andric     if (Result)
98a7dea167SDimitry Andric       S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
990b57cec5SDimitry Andric   }
1000b57cec5SDimitry Andric }
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric static void instantiateDependentAlignedAttr(
1030b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1040b57cec5SDimitry Andric     const AlignedAttr *Aligned, Decl *New) {
1050b57cec5SDimitry Andric   if (!Aligned->isPackExpansion()) {
1060b57cec5SDimitry Andric     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
1070b57cec5SDimitry Andric     return;
1080b57cec5SDimitry Andric   }
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1110b57cec5SDimitry Andric   if (Aligned->isAlignmentExpr())
1120b57cec5SDimitry Andric     S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
1130b57cec5SDimitry Andric                                       Unexpanded);
1140b57cec5SDimitry Andric   else
1150b57cec5SDimitry Andric     S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
1160b57cec5SDimitry Andric                                       Unexpanded);
1170b57cec5SDimitry Andric   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric   // Determine whether we can expand this attribute pack yet.
1200b57cec5SDimitry Andric   bool Expand = true, RetainExpansion = false;
1210b57cec5SDimitry Andric   Optional<unsigned> NumExpansions;
1220b57cec5SDimitry Andric   // FIXME: Use the actual location of the ellipsis.
1230b57cec5SDimitry Andric   SourceLocation EllipsisLoc = Aligned->getLocation();
1240b57cec5SDimitry Andric   if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
1250b57cec5SDimitry Andric                                         Unexpanded, TemplateArgs, Expand,
1260b57cec5SDimitry Andric                                         RetainExpansion, NumExpansions))
1270b57cec5SDimitry Andric     return;
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   if (!Expand) {
1300b57cec5SDimitry Andric     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
1310b57cec5SDimitry Andric     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
1320b57cec5SDimitry Andric   } else {
1330b57cec5SDimitry Andric     for (unsigned I = 0; I != *NumExpansions; ++I) {
1340b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
1350b57cec5SDimitry Andric       instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
1360b57cec5SDimitry Andric     }
1370b57cec5SDimitry Andric   }
1380b57cec5SDimitry Andric }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric static void instantiateDependentAssumeAlignedAttr(
1410b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1420b57cec5SDimitry Andric     const AssumeAlignedAttr *Aligned, Decl *New) {
1430b57cec5SDimitry Andric   // The alignment expression is a constant expression.
1440b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
1450b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   Expr *E, *OE = nullptr;
1480b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
1490b57cec5SDimitry Andric   if (Result.isInvalid())
1500b57cec5SDimitry Andric     return;
1510b57cec5SDimitry Andric   E = Result.getAs<Expr>();
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   if (Aligned->getOffset()) {
1540b57cec5SDimitry Andric     Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
1550b57cec5SDimitry Andric     if (Result.isInvalid())
1560b57cec5SDimitry Andric       return;
1570b57cec5SDimitry Andric     OE = Result.getAs<Expr>();
1580b57cec5SDimitry Andric   }
1590b57cec5SDimitry Andric 
160a7dea167SDimitry Andric   S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
1610b57cec5SDimitry Andric }
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric static void instantiateDependentAlignValueAttr(
1640b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1650b57cec5SDimitry Andric     const AlignValueAttr *Aligned, Decl *New) {
1660b57cec5SDimitry Andric   // The alignment expression is a constant expression.
1670b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
1680b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1690b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
1700b57cec5SDimitry Andric   if (!Result.isInvalid())
171a7dea167SDimitry Andric     S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
1720b57cec5SDimitry Andric }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric static void instantiateDependentAllocAlignAttr(
1750b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
1760b57cec5SDimitry Andric     const AllocAlignAttr *Align, Decl *New) {
1770b57cec5SDimitry Andric   Expr *Param = IntegerLiteral::Create(
1780b57cec5SDimitry Andric       S.getASTContext(),
1790b57cec5SDimitry Andric       llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
1800b57cec5SDimitry Andric       S.getASTContext().UnsignedLongLongTy, Align->getLocation());
181a7dea167SDimitry Andric   S.AddAllocAlignAttr(New, *Align, Param);
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric 
184*e8d8bef9SDimitry Andric static void instantiateDependentAnnotationAttr(
185*e8d8bef9SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
186*e8d8bef9SDimitry Andric     const AnnotateAttr *Attr, Decl *New) {
187*e8d8bef9SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
188*e8d8bef9SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
189*e8d8bef9SDimitry Andric   SmallVector<Expr *, 4> Args;
190*e8d8bef9SDimitry Andric   Args.reserve(Attr->args_size());
191*e8d8bef9SDimitry Andric   for (auto *E : Attr->args()) {
192*e8d8bef9SDimitry Andric     ExprResult Result = S.SubstExpr(E, TemplateArgs);
193*e8d8bef9SDimitry Andric     if (!Result.isUsable())
194*e8d8bef9SDimitry Andric       return;
195*e8d8bef9SDimitry Andric     Args.push_back(Result.get());
196*e8d8bef9SDimitry Andric   }
197*e8d8bef9SDimitry Andric   S.AddAnnotationAttr(New, *Attr, Attr->getAnnotation(), Args);
198*e8d8bef9SDimitry Andric }
199*e8d8bef9SDimitry Andric 
2000b57cec5SDimitry Andric static Expr *instantiateDependentFunctionAttrCondition(
2010b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2020b57cec5SDimitry Andric     const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
2030b57cec5SDimitry Andric   Expr *Cond = nullptr;
2040b57cec5SDimitry Andric   {
2050b57cec5SDimitry Andric     Sema::ContextRAII SwitchContext(S, New);
2060b57cec5SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
2070b57cec5SDimitry Andric         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2080b57cec5SDimitry Andric     ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
2090b57cec5SDimitry Andric     if (Result.isInvalid())
2100b57cec5SDimitry Andric       return nullptr;
2110b57cec5SDimitry Andric     Cond = Result.getAs<Expr>();
2120b57cec5SDimitry Andric   }
2130b57cec5SDimitry Andric   if (!Cond->isTypeDependent()) {
2140b57cec5SDimitry Andric     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
2150b57cec5SDimitry Andric     if (Converted.isInvalid())
2160b57cec5SDimitry Andric       return nullptr;
2170b57cec5SDimitry Andric     Cond = Converted.get();
2180b57cec5SDimitry Andric   }
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric   SmallVector<PartialDiagnosticAt, 8> Diags;
2210b57cec5SDimitry Andric   if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
2220b57cec5SDimitry Andric       !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
2230b57cec5SDimitry Andric     S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
2240b57cec5SDimitry Andric     for (const auto &P : Diags)
2250b57cec5SDimitry Andric       S.Diag(P.first, P.second);
2260b57cec5SDimitry Andric     return nullptr;
2270b57cec5SDimitry Andric   }
2280b57cec5SDimitry Andric   return Cond;
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric static void instantiateDependentEnableIfAttr(
2320b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2330b57cec5SDimitry Andric     const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
2340b57cec5SDimitry Andric   Expr *Cond = instantiateDependentFunctionAttrCondition(
2350b57cec5SDimitry Andric       S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   if (Cond)
238a7dea167SDimitry Andric     New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
239a7dea167SDimitry Andric                                                       Cond, EIA->getMessage()));
2400b57cec5SDimitry Andric }
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric static void instantiateDependentDiagnoseIfAttr(
2430b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2440b57cec5SDimitry Andric     const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
2450b57cec5SDimitry Andric   Expr *Cond = instantiateDependentFunctionAttrCondition(
2460b57cec5SDimitry Andric       S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   if (Cond)
2490b57cec5SDimitry Andric     New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
250a7dea167SDimitry Andric         S.getASTContext(), *DIA, Cond, DIA->getMessage(),
251a7dea167SDimitry Andric         DIA->getDiagnosticType(), DIA->getArgDependent(), New));
2520b57cec5SDimitry Andric }
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
2550b57cec5SDimitry Andric // template A as the base and arguments from TemplateArgs.
2560b57cec5SDimitry Andric static void instantiateDependentCUDALaunchBoundsAttr(
2570b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2580b57cec5SDimitry Andric     const CUDALaunchBoundsAttr &Attr, Decl *New) {
2590b57cec5SDimitry Andric   // The alignment expression is a constant expression.
2600b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
2610b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
2640b57cec5SDimitry Andric   if (Result.isInvalid())
2650b57cec5SDimitry Andric     return;
2660b57cec5SDimitry Andric   Expr *MaxThreads = Result.getAs<Expr>();
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   Expr *MinBlocks = nullptr;
2690b57cec5SDimitry Andric   if (Attr.getMinBlocks()) {
2700b57cec5SDimitry Andric     Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
2710b57cec5SDimitry Andric     if (Result.isInvalid())
2720b57cec5SDimitry Andric       return;
2730b57cec5SDimitry Andric     MinBlocks = Result.getAs<Expr>();
2740b57cec5SDimitry Andric   }
2750b57cec5SDimitry Andric 
276a7dea167SDimitry Andric   S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
2770b57cec5SDimitry Andric }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric static void
2800b57cec5SDimitry Andric instantiateDependentModeAttr(Sema &S,
2810b57cec5SDimitry Andric                              const MultiLevelTemplateArgumentList &TemplateArgs,
2820b57cec5SDimitry Andric                              const ModeAttr &Attr, Decl *New) {
283a7dea167SDimitry Andric   S.AddModeAttr(New, Attr, Attr.getMode(),
284a7dea167SDimitry Andric                 /*InInstantiation=*/true);
2850b57cec5SDimitry Andric }
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric /// Instantiation of 'declare simd' attribute and its arguments.
2880b57cec5SDimitry Andric static void instantiateOMPDeclareSimdDeclAttr(
2890b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2900b57cec5SDimitry Andric     const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
2910b57cec5SDimitry Andric   // Allow 'this' in clauses with varlists.
2920b57cec5SDimitry Andric   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
2930b57cec5SDimitry Andric     New = FTD->getTemplatedDecl();
2940b57cec5SDimitry Andric   auto *FD = cast<FunctionDecl>(New);
2950b57cec5SDimitry Andric   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
2960b57cec5SDimitry Andric   SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
2970b57cec5SDimitry Andric   SmallVector<unsigned, 4> LinModifiers;
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   auto SubstExpr = [&](Expr *E) -> ExprResult {
3000b57cec5SDimitry Andric     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3010b57cec5SDimitry Andric       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3020b57cec5SDimitry Andric         Sema::ContextRAII SavedContext(S, FD);
3030b57cec5SDimitry Andric         LocalInstantiationScope Local(S);
3040b57cec5SDimitry Andric         if (FD->getNumParams() > PVD->getFunctionScopeIndex())
3050b57cec5SDimitry Andric           Local.InstantiatedLocal(
3060b57cec5SDimitry Andric               PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
3070b57cec5SDimitry Andric         return S.SubstExpr(E, TemplateArgs);
3080b57cec5SDimitry Andric       }
3090b57cec5SDimitry Andric     Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
3100b57cec5SDimitry Andric                                      FD->isCXXInstanceMember());
3110b57cec5SDimitry Andric     return S.SubstExpr(E, TemplateArgs);
3120b57cec5SDimitry Andric   };
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   // Substitute a single OpenMP clause, which is a potentially-evaluated
3150b57cec5SDimitry Andric   // full-expression.
3160b57cec5SDimitry Andric   auto Subst = [&](Expr *E) -> ExprResult {
3170b57cec5SDimitry Andric     EnterExpressionEvaluationContext Evaluated(
3180b57cec5SDimitry Andric         S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3190b57cec5SDimitry Andric     ExprResult Res = SubstExpr(E);
3200b57cec5SDimitry Andric     if (Res.isInvalid())
3210b57cec5SDimitry Andric       return Res;
3220b57cec5SDimitry Andric     return S.ActOnFinishFullExpr(Res.get(), false);
3230b57cec5SDimitry Andric   };
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric   ExprResult Simdlen;
3260b57cec5SDimitry Andric   if (auto *E = Attr.getSimdlen())
3270b57cec5SDimitry Andric     Simdlen = Subst(E);
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   if (Attr.uniforms_size() > 0) {
3300b57cec5SDimitry Andric     for(auto *E : Attr.uniforms()) {
3310b57cec5SDimitry Andric       ExprResult Inst = Subst(E);
3320b57cec5SDimitry Andric       if (Inst.isInvalid())
3330b57cec5SDimitry Andric         continue;
3340b57cec5SDimitry Andric       Uniforms.push_back(Inst.get());
3350b57cec5SDimitry Andric     }
3360b57cec5SDimitry Andric   }
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   auto AI = Attr.alignments_begin();
3390b57cec5SDimitry Andric   for (auto *E : Attr.aligneds()) {
3400b57cec5SDimitry Andric     ExprResult Inst = Subst(E);
3410b57cec5SDimitry Andric     if (Inst.isInvalid())
3420b57cec5SDimitry Andric       continue;
3430b57cec5SDimitry Andric     Aligneds.push_back(Inst.get());
3440b57cec5SDimitry Andric     Inst = ExprEmpty();
3450b57cec5SDimitry Andric     if (*AI)
3460b57cec5SDimitry Andric       Inst = S.SubstExpr(*AI, TemplateArgs);
3470b57cec5SDimitry Andric     Alignments.push_back(Inst.get());
3480b57cec5SDimitry Andric     ++AI;
3490b57cec5SDimitry Andric   }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   auto SI = Attr.steps_begin();
3520b57cec5SDimitry Andric   for (auto *E : Attr.linears()) {
3530b57cec5SDimitry Andric     ExprResult Inst = Subst(E);
3540b57cec5SDimitry Andric     if (Inst.isInvalid())
3550b57cec5SDimitry Andric       continue;
3560b57cec5SDimitry Andric     Linears.push_back(Inst.get());
3570b57cec5SDimitry Andric     Inst = ExprEmpty();
3580b57cec5SDimitry Andric     if (*SI)
3590b57cec5SDimitry Andric       Inst = S.SubstExpr(*SI, TemplateArgs);
3600b57cec5SDimitry Andric     Steps.push_back(Inst.get());
3610b57cec5SDimitry Andric     ++SI;
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric   LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
3640b57cec5SDimitry Andric   (void)S.ActOnOpenMPDeclareSimdDirective(
3650b57cec5SDimitry Andric       S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
3660b57cec5SDimitry Andric       Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
3670b57cec5SDimitry Andric       Attr.getRange());
3680b57cec5SDimitry Andric }
3690b57cec5SDimitry Andric 
370a7dea167SDimitry Andric /// Instantiation of 'declare variant' attribute and its arguments.
371a7dea167SDimitry Andric static void instantiateOMPDeclareVariantAttr(
372a7dea167SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
373a7dea167SDimitry Andric     const OMPDeclareVariantAttr &Attr, Decl *New) {
374a7dea167SDimitry Andric   // Allow 'this' in clauses with varlists.
375a7dea167SDimitry Andric   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
376a7dea167SDimitry Andric     New = FTD->getTemplatedDecl();
377a7dea167SDimitry Andric   auto *FD = cast<FunctionDecl>(New);
378a7dea167SDimitry Andric   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
379a7dea167SDimitry Andric 
380a7dea167SDimitry Andric   auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
381a7dea167SDimitry Andric     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
382a7dea167SDimitry Andric       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
383a7dea167SDimitry Andric         Sema::ContextRAII SavedContext(S, FD);
384a7dea167SDimitry Andric         LocalInstantiationScope Local(S);
385a7dea167SDimitry Andric         if (FD->getNumParams() > PVD->getFunctionScopeIndex())
386a7dea167SDimitry Andric           Local.InstantiatedLocal(
387a7dea167SDimitry Andric               PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
388a7dea167SDimitry Andric         return S.SubstExpr(E, TemplateArgs);
389a7dea167SDimitry Andric       }
390a7dea167SDimitry Andric     Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
391a7dea167SDimitry Andric                                      FD->isCXXInstanceMember());
392a7dea167SDimitry Andric     return S.SubstExpr(E, TemplateArgs);
393a7dea167SDimitry Andric   };
394a7dea167SDimitry Andric 
395a7dea167SDimitry Andric   // Substitute a single OpenMP clause, which is a potentially-evaluated
396a7dea167SDimitry Andric   // full-expression.
397a7dea167SDimitry Andric   auto &&Subst = [&SubstExpr, &S](Expr *E) {
398a7dea167SDimitry Andric     EnterExpressionEvaluationContext Evaluated(
399a7dea167SDimitry Andric         S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
400a7dea167SDimitry Andric     ExprResult Res = SubstExpr(E);
401a7dea167SDimitry Andric     if (Res.isInvalid())
402a7dea167SDimitry Andric       return Res;
403a7dea167SDimitry Andric     return S.ActOnFinishFullExpr(Res.get(), false);
404a7dea167SDimitry Andric   };
405a7dea167SDimitry Andric 
406a7dea167SDimitry Andric   ExprResult VariantFuncRef;
407480093f4SDimitry Andric   if (Expr *E = Attr.getVariantFuncRef()) {
408480093f4SDimitry Andric     // Do not mark function as is used to prevent its emission if this is the
409480093f4SDimitry Andric     // only place where it is used.
410480093f4SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
411480093f4SDimitry Andric         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
412a7dea167SDimitry Andric     VariantFuncRef = Subst(E);
413480093f4SDimitry Andric   }
414a7dea167SDimitry Andric 
4155ffd83dbSDimitry Andric   // Copy the template version of the OMPTraitInfo and run substitute on all
4165ffd83dbSDimitry Andric   // score and condition expressiosn.
4175ffd83dbSDimitry Andric   OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
4185ffd83dbSDimitry Andric   TI = *Attr.getTraitInfos();
4195ffd83dbSDimitry Andric 
4205ffd83dbSDimitry Andric   // Try to substitute template parameters in score and condition expressions.
4215ffd83dbSDimitry Andric   auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
4225ffd83dbSDimitry Andric     if (E) {
4235ffd83dbSDimitry Andric       EnterExpressionEvaluationContext Unevaluated(
4245ffd83dbSDimitry Andric           S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4255ffd83dbSDimitry Andric       ExprResult ER = Subst(E);
4265ffd83dbSDimitry Andric       if (ER.isUsable())
4275ffd83dbSDimitry Andric         E = ER.get();
4285ffd83dbSDimitry Andric       else
4295ffd83dbSDimitry Andric         return true;
4305ffd83dbSDimitry Andric     }
4315ffd83dbSDimitry Andric     return false;
4325ffd83dbSDimitry Andric   };
4335ffd83dbSDimitry Andric   if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
4345ffd83dbSDimitry Andric     return;
4355ffd83dbSDimitry Andric 
436*e8d8bef9SDimitry Andric   Expr *E = VariantFuncRef.get();
437*e8d8bef9SDimitry Andric   // Check function/variant ref for `omp declare variant` but not for `omp
438*e8d8bef9SDimitry Andric   // begin declare variant` (which use implicit attributes).
439a7dea167SDimitry Andric   Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
4405ffd83dbSDimitry Andric       S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New),
4415ffd83dbSDimitry Andric                                           VariantFuncRef.get(), TI,
4425ffd83dbSDimitry Andric                                           Attr.getRange());
4435ffd83dbSDimitry Andric 
444a7dea167SDimitry Andric   if (!DeclVarData)
445a7dea167SDimitry Andric     return;
4465ffd83dbSDimitry Andric 
447*e8d8bef9SDimitry Andric   E = DeclVarData.getValue().second;
448*e8d8bef9SDimitry Andric   FD = DeclVarData.getValue().first;
449*e8d8bef9SDimitry Andric 
450*e8d8bef9SDimitry Andric   if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
451*e8d8bef9SDimitry Andric     if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
452*e8d8bef9SDimitry Andric       if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
453*e8d8bef9SDimitry Andric         if (!VariantFTD->isThisDeclarationADefinition())
454*e8d8bef9SDimitry Andric           return;
455*e8d8bef9SDimitry Andric         Sema::TentativeAnalysisScope Trap(S);
456*e8d8bef9SDimitry Andric         const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
457*e8d8bef9SDimitry Andric             S.Context, TemplateArgs.getInnermost());
458*e8d8bef9SDimitry Andric 
459*e8d8bef9SDimitry Andric         auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
460*e8d8bef9SDimitry Andric                                                          New->getLocation());
461*e8d8bef9SDimitry Andric         if (!SubstFD)
462*e8d8bef9SDimitry Andric           return;
463*e8d8bef9SDimitry Andric         QualType NewType = S.Context.mergeFunctionTypes(
464*e8d8bef9SDimitry Andric             SubstFD->getType(), FD->getType(),
465*e8d8bef9SDimitry Andric             /* OfBlockPointer */ false,
466*e8d8bef9SDimitry Andric             /* Unqualified */ false, /* AllowCXX */ true);
467*e8d8bef9SDimitry Andric         if (NewType.isNull())
468*e8d8bef9SDimitry Andric           return;
469*e8d8bef9SDimitry Andric         S.InstantiateFunctionDefinition(
470*e8d8bef9SDimitry Andric             New->getLocation(), SubstFD, /* Recursive */ true,
471*e8d8bef9SDimitry Andric             /* DefinitionRequired */ false, /* AtEndOfTU */ false);
472*e8d8bef9SDimitry Andric         SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
473*e8d8bef9SDimitry Andric         E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
474*e8d8bef9SDimitry Andric                                 SourceLocation(), SubstFD,
475*e8d8bef9SDimitry Andric                                 /* RefersToEnclosingVariableOrCapture */ false,
476*e8d8bef9SDimitry Andric                                 /* NameLoc */ SubstFD->getLocation(),
477*e8d8bef9SDimitry Andric                                 SubstFD->getType(), ExprValueKind::VK_RValue);
478*e8d8bef9SDimitry Andric       }
479*e8d8bef9SDimitry Andric     }
480*e8d8bef9SDimitry Andric   }
481*e8d8bef9SDimitry Andric 
482*e8d8bef9SDimitry Andric   S.ActOnOpenMPDeclareVariantDirective(FD, E, TI, Attr.getRange());
483a7dea167SDimitry Andric }
484a7dea167SDimitry Andric 
4850b57cec5SDimitry Andric static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
4860b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
4870b57cec5SDimitry Andric     const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
4880b57cec5SDimitry Andric   // Both min and max expression are constant expressions.
4890b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
4900b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
4930b57cec5SDimitry Andric   if (Result.isInvalid())
4940b57cec5SDimitry Andric     return;
4950b57cec5SDimitry Andric   Expr *MinExpr = Result.getAs<Expr>();
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric   Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
4980b57cec5SDimitry Andric   if (Result.isInvalid())
4990b57cec5SDimitry Andric     return;
5000b57cec5SDimitry Andric   Expr *MaxExpr = Result.getAs<Expr>();
5010b57cec5SDimitry Andric 
502a7dea167SDimitry Andric   S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
5030b57cec5SDimitry Andric }
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric static ExplicitSpecifier
5060b57cec5SDimitry Andric instantiateExplicitSpecifier(Sema &S,
5070b57cec5SDimitry Andric                              const MultiLevelTemplateArgumentList &TemplateArgs,
5080b57cec5SDimitry Andric                              ExplicitSpecifier ES, FunctionDecl *New) {
5090b57cec5SDimitry Andric   if (!ES.getExpr())
5100b57cec5SDimitry Andric     return ES;
5110b57cec5SDimitry Andric   Expr *OldCond = ES.getExpr();
5120b57cec5SDimitry Andric   Expr *Cond = nullptr;
5130b57cec5SDimitry Andric   {
5140b57cec5SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
5150b57cec5SDimitry Andric         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5160b57cec5SDimitry Andric     ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
5170b57cec5SDimitry Andric     if (SubstResult.isInvalid()) {
5180b57cec5SDimitry Andric       return ExplicitSpecifier::Invalid();
5190b57cec5SDimitry Andric     }
5200b57cec5SDimitry Andric     Cond = SubstResult.get();
5210b57cec5SDimitry Andric   }
5220b57cec5SDimitry Andric   ExplicitSpecifier Result(Cond, ES.getKind());
5230b57cec5SDimitry Andric   if (!Cond->isTypeDependent())
5240b57cec5SDimitry Andric     S.tryResolveExplicitSpecifier(Result);
5250b57cec5SDimitry Andric   return Result;
5260b57cec5SDimitry Andric }
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric static void instantiateDependentAMDGPUWavesPerEUAttr(
5290b57cec5SDimitry Andric     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
5300b57cec5SDimitry Andric     const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
5310b57cec5SDimitry Andric   // Both min and max expression are constant expressions.
5320b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
5330b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric   ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
5360b57cec5SDimitry Andric   if (Result.isInvalid())
5370b57cec5SDimitry Andric     return;
5380b57cec5SDimitry Andric   Expr *MinExpr = Result.getAs<Expr>();
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric   Expr *MaxExpr = nullptr;
5410b57cec5SDimitry Andric   if (auto Max = Attr.getMax()) {
5420b57cec5SDimitry Andric     Result = S.SubstExpr(Max, TemplateArgs);
5430b57cec5SDimitry Andric     if (Result.isInvalid())
5440b57cec5SDimitry Andric       return;
5450b57cec5SDimitry Andric     MaxExpr = Result.getAs<Expr>();
5460b57cec5SDimitry Andric   }
5470b57cec5SDimitry Andric 
548a7dea167SDimitry Andric   S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
5490b57cec5SDimitry Andric }
5500b57cec5SDimitry Andric 
551*e8d8bef9SDimitry Andric /// Determine whether the attribute A might be relevent to the declaration D.
552*e8d8bef9SDimitry Andric /// If not, we can skip instantiating it. The attribute may or may not have
553*e8d8bef9SDimitry Andric /// been instantiated yet.
554*e8d8bef9SDimitry Andric static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
555*e8d8bef9SDimitry Andric   // 'preferred_name' is only relevant to the matching specialization of the
556*e8d8bef9SDimitry Andric   // template.
557*e8d8bef9SDimitry Andric   if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
558*e8d8bef9SDimitry Andric     QualType T = PNA->getTypedefType();
559*e8d8bef9SDimitry Andric     const auto *RD = cast<CXXRecordDecl>(D);
560*e8d8bef9SDimitry Andric     if (!T->isDependentType() && !RD->isDependentContext() &&
561*e8d8bef9SDimitry Andric         !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
562*e8d8bef9SDimitry Andric       return false;
563*e8d8bef9SDimitry Andric     for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
564*e8d8bef9SDimitry Andric       if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
565*e8d8bef9SDimitry Andric                                 PNA->getTypedefType()))
566*e8d8bef9SDimitry Andric         return false;
567*e8d8bef9SDimitry Andric     return true;
568*e8d8bef9SDimitry Andric   }
569*e8d8bef9SDimitry Andric 
570*e8d8bef9SDimitry Andric   return true;
571*e8d8bef9SDimitry Andric }
572*e8d8bef9SDimitry Andric 
5730b57cec5SDimitry Andric void Sema::InstantiateAttrsForDecl(
5740b57cec5SDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
5750b57cec5SDimitry Andric     Decl *New, LateInstantiatedAttrVec *LateAttrs,
5760b57cec5SDimitry Andric     LocalInstantiationScope *OuterMostScope) {
5770b57cec5SDimitry Andric   if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
578*e8d8bef9SDimitry Andric     // FIXME: This function is called multiple times for the same template
579*e8d8bef9SDimitry Andric     // specialization. We should only instantiate attributes that were added
580*e8d8bef9SDimitry Andric     // since the previous instantiation.
5810b57cec5SDimitry Andric     for (const auto *TmplAttr : Tmpl->attrs()) {
582*e8d8bef9SDimitry Andric       if (!isRelevantAttr(*this, New, TmplAttr))
583*e8d8bef9SDimitry Andric         continue;
584*e8d8bef9SDimitry Andric 
5850b57cec5SDimitry Andric       // FIXME: If any of the special case versions from InstantiateAttrs become
5860b57cec5SDimitry Andric       // applicable to template declaration, we'll need to add them here.
5870b57cec5SDimitry Andric       CXXThisScopeRAII ThisScope(
5880b57cec5SDimitry Andric           *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
5890b57cec5SDimitry Andric           Qualifiers(), ND->isCXXInstanceMember());
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric       Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
5920b57cec5SDimitry Andric           TmplAttr, Context, *this, TemplateArgs);
593*e8d8bef9SDimitry Andric       if (NewAttr && isRelevantAttr(*this, New, NewAttr))
5940b57cec5SDimitry Andric         New->addAttr(NewAttr);
5950b57cec5SDimitry Andric     }
5960b57cec5SDimitry Andric   }
5970b57cec5SDimitry Andric }
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric static Sema::RetainOwnershipKind
6000b57cec5SDimitry Andric attrToRetainOwnershipKind(const Attr *A) {
6010b57cec5SDimitry Andric   switch (A->getKind()) {
6020b57cec5SDimitry Andric   case clang::attr::CFConsumed:
6030b57cec5SDimitry Andric     return Sema::RetainOwnershipKind::CF;
6040b57cec5SDimitry Andric   case clang::attr::OSConsumed:
6050b57cec5SDimitry Andric     return Sema::RetainOwnershipKind::OS;
6060b57cec5SDimitry Andric   case clang::attr::NSConsumed:
6070b57cec5SDimitry Andric     return Sema::RetainOwnershipKind::NS;
6080b57cec5SDimitry Andric   default:
6090b57cec5SDimitry Andric     llvm_unreachable("Wrong argument supplied");
6100b57cec5SDimitry Andric   }
6110b57cec5SDimitry Andric }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
6140b57cec5SDimitry Andric                             const Decl *Tmpl, Decl *New,
6150b57cec5SDimitry Andric                             LateInstantiatedAttrVec *LateAttrs,
6160b57cec5SDimitry Andric                             LocalInstantiationScope *OuterMostScope) {
6170b57cec5SDimitry Andric   for (const auto *TmplAttr : Tmpl->attrs()) {
618*e8d8bef9SDimitry Andric     if (!isRelevantAttr(*this, New, TmplAttr))
619*e8d8bef9SDimitry Andric       continue;
620*e8d8bef9SDimitry Andric 
6210b57cec5SDimitry Andric     // FIXME: This should be generalized to more than just the AlignedAttr.
6220b57cec5SDimitry Andric     const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
6230b57cec5SDimitry Andric     if (Aligned && Aligned->isAlignmentDependent()) {
6240b57cec5SDimitry Andric       instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
6250b57cec5SDimitry Andric       continue;
6260b57cec5SDimitry Andric     }
6270b57cec5SDimitry Andric 
628a7dea167SDimitry Andric     if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
6290b57cec5SDimitry Andric       instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
6300b57cec5SDimitry Andric       continue;
6310b57cec5SDimitry Andric     }
6320b57cec5SDimitry Andric 
633a7dea167SDimitry Andric     if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
6340b57cec5SDimitry Andric       instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
6350b57cec5SDimitry Andric       continue;
6360b57cec5SDimitry Andric     }
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric     if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
6390b57cec5SDimitry Andric       instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
6400b57cec5SDimitry Andric       continue;
6410b57cec5SDimitry Andric     }
6420b57cec5SDimitry Andric 
643*e8d8bef9SDimitry Andric     if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
644*e8d8bef9SDimitry Andric       instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
645*e8d8bef9SDimitry Andric       continue;
646*e8d8bef9SDimitry Andric     }
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric     if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
6490b57cec5SDimitry Andric       instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
6500b57cec5SDimitry Andric                                        cast<FunctionDecl>(New));
6510b57cec5SDimitry Andric       continue;
6520b57cec5SDimitry Andric     }
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric     if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
6550b57cec5SDimitry Andric       instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
6560b57cec5SDimitry Andric                                          cast<FunctionDecl>(New));
6570b57cec5SDimitry Andric       continue;
6580b57cec5SDimitry Andric     }
6590b57cec5SDimitry Andric 
660a7dea167SDimitry Andric     if (const auto *CUDALaunchBounds =
6610b57cec5SDimitry Andric             dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
6620b57cec5SDimitry Andric       instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
6630b57cec5SDimitry Andric                                                *CUDALaunchBounds, New);
6640b57cec5SDimitry Andric       continue;
6650b57cec5SDimitry Andric     }
6660b57cec5SDimitry Andric 
667a7dea167SDimitry Andric     if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
6680b57cec5SDimitry Andric       instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
6690b57cec5SDimitry Andric       continue;
6700b57cec5SDimitry Andric     }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric     if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
6730b57cec5SDimitry Andric       instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
6740b57cec5SDimitry Andric       continue;
6750b57cec5SDimitry Andric     }
6760b57cec5SDimitry Andric 
677a7dea167SDimitry Andric     if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
678a7dea167SDimitry Andric       instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
679a7dea167SDimitry Andric       continue;
680a7dea167SDimitry Andric     }
681a7dea167SDimitry Andric 
682a7dea167SDimitry Andric     if (const auto *AMDGPUFlatWorkGroupSize =
6830b57cec5SDimitry Andric             dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
6840b57cec5SDimitry Andric       instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
6850b57cec5SDimitry Andric           *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
6860b57cec5SDimitry Andric     }
6870b57cec5SDimitry Andric 
688a7dea167SDimitry Andric     if (const auto *AMDGPUFlatWorkGroupSize =
6890b57cec5SDimitry Andric             dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
6900b57cec5SDimitry Andric       instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
6910b57cec5SDimitry Andric                                                *AMDGPUFlatWorkGroupSize, New);
6920b57cec5SDimitry Andric     }
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric     // Existing DLL attribute on the instantiation takes precedence.
6950b57cec5SDimitry Andric     if (TmplAttr->getKind() == attr::DLLExport ||
6960b57cec5SDimitry Andric         TmplAttr->getKind() == attr::DLLImport) {
6970b57cec5SDimitry Andric       if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
6980b57cec5SDimitry Andric         continue;
6990b57cec5SDimitry Andric       }
7000b57cec5SDimitry Andric     }
7010b57cec5SDimitry Andric 
702a7dea167SDimitry Andric     if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
703a7dea167SDimitry Andric       AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
7040b57cec5SDimitry Andric       continue;
7050b57cec5SDimitry Andric     }
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric     if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
7080b57cec5SDimitry Andric         isa<CFConsumedAttr>(TmplAttr)) {
709a7dea167SDimitry Andric       AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
7100b57cec5SDimitry Andric                        /*template instantiation=*/true);
7110b57cec5SDimitry Andric       continue;
7120b57cec5SDimitry Andric     }
7130b57cec5SDimitry Andric 
714a7dea167SDimitry Andric     if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
715a7dea167SDimitry Andric       if (!New->hasAttr<PointerAttr>())
716a7dea167SDimitry Andric         New->addAttr(A->clone(Context));
717a7dea167SDimitry Andric       continue;
718a7dea167SDimitry Andric     }
719a7dea167SDimitry Andric 
720a7dea167SDimitry Andric     if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
721a7dea167SDimitry Andric       if (!New->hasAttr<OwnerAttr>())
722a7dea167SDimitry Andric         New->addAttr(A->clone(Context));
723a7dea167SDimitry Andric       continue;
724a7dea167SDimitry Andric     }
725a7dea167SDimitry Andric 
7260b57cec5SDimitry Andric     assert(!TmplAttr->isPackExpansion());
7270b57cec5SDimitry Andric     if (TmplAttr->isLateParsed() && LateAttrs) {
7280b57cec5SDimitry Andric       // Late parsed attributes must be instantiated and attached after the
7290b57cec5SDimitry Andric       // enclosing class has been instantiated.  See Sema::InstantiateClass.
7300b57cec5SDimitry Andric       LocalInstantiationScope *Saved = nullptr;
7310b57cec5SDimitry Andric       if (CurrentInstantiationScope)
7320b57cec5SDimitry Andric         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
7330b57cec5SDimitry Andric       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
7340b57cec5SDimitry Andric     } else {
7350b57cec5SDimitry Andric       // Allow 'this' within late-parsed attributes.
736480093f4SDimitry Andric       auto *ND = cast<NamedDecl>(New);
737480093f4SDimitry Andric       auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
7380b57cec5SDimitry Andric       CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
739480093f4SDimitry Andric                                  ND->isCXXInstanceMember());
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
7420b57cec5SDimitry Andric                                                          *this, TemplateArgs);
743*e8d8bef9SDimitry Andric       if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
7440b57cec5SDimitry Andric         New->addAttr(NewAttr);
7450b57cec5SDimitry Andric     }
7460b57cec5SDimitry Andric   }
7470b57cec5SDimitry Andric }
7480b57cec5SDimitry Andric 
749*e8d8bef9SDimitry Andric /// In the MS ABI, we need to instantiate default arguments of dllexported
750*e8d8bef9SDimitry Andric /// default constructors along with the constructor definition. This allows IR
751*e8d8bef9SDimitry Andric /// gen to emit a constructor closure which calls the default constructor with
752*e8d8bef9SDimitry Andric /// its default arguments.
753*e8d8bef9SDimitry Andric void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
754*e8d8bef9SDimitry Andric   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
755*e8d8bef9SDimitry Andric          Ctor->isDefaultConstructor());
756*e8d8bef9SDimitry Andric   unsigned NumParams = Ctor->getNumParams();
757*e8d8bef9SDimitry Andric   if (NumParams == 0)
758*e8d8bef9SDimitry Andric     return;
759*e8d8bef9SDimitry Andric   DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
760*e8d8bef9SDimitry Andric   if (!Attr)
761*e8d8bef9SDimitry Andric     return;
762*e8d8bef9SDimitry Andric   for (unsigned I = 0; I != NumParams; ++I) {
763*e8d8bef9SDimitry Andric     (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
764*e8d8bef9SDimitry Andric                                    Ctor->getParamDecl(I));
765*e8d8bef9SDimitry Andric     DiscardCleanupsInEvaluationContext();
766*e8d8bef9SDimitry Andric   }
767*e8d8bef9SDimitry Andric }
768*e8d8bef9SDimitry Andric 
7690b57cec5SDimitry Andric /// Get the previous declaration of a declaration for the purposes of template
7700b57cec5SDimitry Andric /// instantiation. If this finds a previous declaration, then the previous
7710b57cec5SDimitry Andric /// declaration of the instantiation of D should be an instantiation of the
7720b57cec5SDimitry Andric /// result of this function.
7730b57cec5SDimitry Andric template<typename DeclT>
7740b57cec5SDimitry Andric static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
7750b57cec5SDimitry Andric   DeclT *Result = D->getPreviousDecl();
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   // If the declaration is within a class, and the previous declaration was
7780b57cec5SDimitry Andric   // merged from a different definition of that class, then we don't have a
7790b57cec5SDimitry Andric   // previous declaration for the purpose of template instantiation.
7800b57cec5SDimitry Andric   if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
7810b57cec5SDimitry Andric       D->getLexicalDeclContext() != Result->getLexicalDeclContext())
7820b57cec5SDimitry Andric     return nullptr;
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   return Result;
7850b57cec5SDimitry Andric }
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric Decl *
7880b57cec5SDimitry Andric TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
7890b57cec5SDimitry Andric   llvm_unreachable("Translation units cannot be instantiated");
7900b57cec5SDimitry Andric }
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric Decl *
7930b57cec5SDimitry Andric TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
7940b57cec5SDimitry Andric   llvm_unreachable("pragma comment cannot be instantiated");
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
7980b57cec5SDimitry Andric     PragmaDetectMismatchDecl *D) {
7990b57cec5SDimitry Andric   llvm_unreachable("pragma comment cannot be instantiated");
8000b57cec5SDimitry Andric }
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric Decl *
8030b57cec5SDimitry Andric TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
8040b57cec5SDimitry Andric   llvm_unreachable("extern \"C\" context cannot be instantiated");
8050b57cec5SDimitry Andric }
8060b57cec5SDimitry Andric 
8075ffd83dbSDimitry Andric Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
8085ffd83dbSDimitry Andric   llvm_unreachable("GUID declaration cannot be instantiated");
8095ffd83dbSDimitry Andric }
8105ffd83dbSDimitry Andric 
811*e8d8bef9SDimitry Andric Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
812*e8d8bef9SDimitry Andric     TemplateParamObjectDecl *D) {
813*e8d8bef9SDimitry Andric   llvm_unreachable("template parameter objects cannot be instantiated");
814*e8d8bef9SDimitry Andric }
815*e8d8bef9SDimitry Andric 
8160b57cec5SDimitry Andric Decl *
8170b57cec5SDimitry Andric TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
8180b57cec5SDimitry Andric   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
8190b57cec5SDimitry Andric                                       D->getIdentifier());
8200b57cec5SDimitry Andric   Owner->addDecl(Inst);
8210b57cec5SDimitry Andric   return Inst;
8220b57cec5SDimitry Andric }
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric Decl *
8250b57cec5SDimitry Andric TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
8260b57cec5SDimitry Andric   llvm_unreachable("Namespaces cannot be instantiated");
8270b57cec5SDimitry Andric }
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric Decl *
8300b57cec5SDimitry Andric TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
8310b57cec5SDimitry Andric   NamespaceAliasDecl *Inst
8320b57cec5SDimitry Andric     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
8330b57cec5SDimitry Andric                                  D->getNamespaceLoc(),
8340b57cec5SDimitry Andric                                  D->getAliasLoc(),
8350b57cec5SDimitry Andric                                  D->getIdentifier(),
8360b57cec5SDimitry Andric                                  D->getQualifierLoc(),
8370b57cec5SDimitry Andric                                  D->getTargetNameLoc(),
8380b57cec5SDimitry Andric                                  D->getNamespace());
8390b57cec5SDimitry Andric   Owner->addDecl(Inst);
8400b57cec5SDimitry Andric   return Inst;
8410b57cec5SDimitry Andric }
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
8440b57cec5SDimitry Andric                                                            bool IsTypeAlias) {
8450b57cec5SDimitry Andric   bool Invalid = false;
8460b57cec5SDimitry Andric   TypeSourceInfo *DI = D->getTypeSourceInfo();
8470b57cec5SDimitry Andric   if (DI->getType()->isInstantiationDependentType() ||
8480b57cec5SDimitry Andric       DI->getType()->isVariablyModifiedType()) {
8490b57cec5SDimitry Andric     DI = SemaRef.SubstType(DI, TemplateArgs,
8500b57cec5SDimitry Andric                            D->getLocation(), D->getDeclName());
8510b57cec5SDimitry Andric     if (!DI) {
8520b57cec5SDimitry Andric       Invalid = true;
8530b57cec5SDimitry Andric       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
8540b57cec5SDimitry Andric     }
8550b57cec5SDimitry Andric   } else {
8560b57cec5SDimitry Andric     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
8570b57cec5SDimitry Andric   }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   // HACK: g++ has a bug where it gets the value kind of ?: wrong.
8600b57cec5SDimitry Andric   // libstdc++ relies upon this bug in its implementation of common_type.
8610b57cec5SDimitry Andric   // If we happen to be processing that implementation, fake up the g++ ?:
8620b57cec5SDimitry Andric   // semantics. See LWG issue 2141 for more information on the bug.
8630b57cec5SDimitry Andric   const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
8640b57cec5SDimitry Andric   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
8650b57cec5SDimitry Andric   if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
8660b57cec5SDimitry Andric       DT->isReferenceType() &&
8670b57cec5SDimitry Andric       RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
8680b57cec5SDimitry Andric       RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
8690b57cec5SDimitry Andric       D->getIdentifier() && D->getIdentifier()->isStr("type") &&
8700b57cec5SDimitry Andric       SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
8710b57cec5SDimitry Andric     // Fold it to the (non-reference) type which g++ would have produced.
8720b57cec5SDimitry Andric     DI = SemaRef.Context.getTrivialTypeSourceInfo(
8730b57cec5SDimitry Andric       DI->getType().getNonReferenceType());
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric   // Create the new typedef
8760b57cec5SDimitry Andric   TypedefNameDecl *Typedef;
8770b57cec5SDimitry Andric   if (IsTypeAlias)
8780b57cec5SDimitry Andric     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
8790b57cec5SDimitry Andric                                     D->getLocation(), D->getIdentifier(), DI);
8800b57cec5SDimitry Andric   else
8810b57cec5SDimitry Andric     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
8820b57cec5SDimitry Andric                                   D->getLocation(), D->getIdentifier(), DI);
8830b57cec5SDimitry Andric   if (Invalid)
8840b57cec5SDimitry Andric     Typedef->setInvalidDecl();
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric   // If the old typedef was the name for linkage purposes of an anonymous
8870b57cec5SDimitry Andric   // tag decl, re-establish that relationship for the new typedef.
8880b57cec5SDimitry Andric   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
8890b57cec5SDimitry Andric     TagDecl *oldTag = oldTagType->getDecl();
8900b57cec5SDimitry Andric     if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
8910b57cec5SDimitry Andric       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
8920b57cec5SDimitry Andric       assert(!newTag->hasNameForLinkage());
8930b57cec5SDimitry Andric       newTag->setTypedefNameForAnonDecl(Typedef);
8940b57cec5SDimitry Andric     }
8950b57cec5SDimitry Andric   }
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric   if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
8980b57cec5SDimitry Andric     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
8990b57cec5SDimitry Andric                                                        TemplateArgs);
9000b57cec5SDimitry Andric     if (!InstPrev)
9010b57cec5SDimitry Andric       return nullptr;
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric     // If the typedef types are not identical, reject them.
9060b57cec5SDimitry Andric     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric     Typedef->setPreviousDecl(InstPrevTypedef);
9090b57cec5SDimitry Andric   }
9100b57cec5SDimitry Andric 
9110b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
9120b57cec5SDimitry Andric 
913a7dea167SDimitry Andric   if (D->getUnderlyingType()->getAs<DependentNameType>())
914a7dea167SDimitry Andric     SemaRef.inferGslPointerAttribute(Typedef);
915a7dea167SDimitry Andric 
9160b57cec5SDimitry Andric   Typedef->setAccess(D->getAccess());
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   return Typedef;
9190b57cec5SDimitry Andric }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
9220b57cec5SDimitry Andric   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
9230b57cec5SDimitry Andric   if (Typedef)
9240b57cec5SDimitry Andric     Owner->addDecl(Typedef);
9250b57cec5SDimitry Andric   return Typedef;
9260b57cec5SDimitry Andric }
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
9290b57cec5SDimitry Andric   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
9300b57cec5SDimitry Andric   if (Typedef)
9310b57cec5SDimitry Andric     Owner->addDecl(Typedef);
9320b57cec5SDimitry Andric   return Typedef;
9330b57cec5SDimitry Andric }
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric Decl *
9360b57cec5SDimitry Andric TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
9370b57cec5SDimitry Andric   // Create a local instantiation scope for this type alias template, which
9380b57cec5SDimitry Andric   // will contain the instantiations of the template parameters.
9390b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
9420b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
9430b57cec5SDimitry Andric   if (!InstParams)
9440b57cec5SDimitry Andric     return nullptr;
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric   TypeAliasDecl *Pattern = D->getTemplatedDecl();
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
9490b57cec5SDimitry Andric   if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
9500b57cec5SDimitry Andric     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
9510b57cec5SDimitry Andric     if (!Found.empty()) {
9520b57cec5SDimitry Andric       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
9530b57cec5SDimitry Andric     }
9540b57cec5SDimitry Andric   }
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
9570b57cec5SDimitry Andric     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
9580b57cec5SDimitry Andric   if (!AliasInst)
9590b57cec5SDimitry Andric     return nullptr;
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   TypeAliasTemplateDecl *Inst
9620b57cec5SDimitry Andric     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
9630b57cec5SDimitry Andric                                     D->getDeclName(), InstParams, AliasInst);
9640b57cec5SDimitry Andric   AliasInst->setDescribedAliasTemplate(Inst);
9650b57cec5SDimitry Andric   if (PrevAliasTemplate)
9660b57cec5SDimitry Andric     Inst->setPreviousDecl(PrevAliasTemplate);
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   Inst->setAccess(D->getAccess());
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric   if (!PrevAliasTemplate)
9710b57cec5SDimitry Andric     Inst->setInstantiatedFromMemberTemplate(D);
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric   Owner->addDecl(Inst);
9740b57cec5SDimitry Andric 
9750b57cec5SDimitry Andric   return Inst;
9760b57cec5SDimitry Andric }
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
9790b57cec5SDimitry Andric   auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
9800b57cec5SDimitry Andric                                     D->getIdentifier());
9810b57cec5SDimitry Andric   NewBD->setReferenced(D->isReferenced());
9820b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
9830b57cec5SDimitry Andric   return NewBD;
9840b57cec5SDimitry Andric }
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
9870b57cec5SDimitry Andric   // Transform the bindings first.
9880b57cec5SDimitry Andric   SmallVector<BindingDecl*, 16> NewBindings;
9890b57cec5SDimitry Andric   for (auto *OldBD : D->bindings())
9900b57cec5SDimitry Andric     NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
9910b57cec5SDimitry Andric   ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   auto *NewDD = cast_or_null<DecompositionDecl>(
9940b57cec5SDimitry Andric       VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
9950b57cec5SDimitry Andric 
9960b57cec5SDimitry Andric   if (!NewDD || NewDD->isInvalidDecl())
9970b57cec5SDimitry Andric     for (auto *NewBD : NewBindings)
9980b57cec5SDimitry Andric       NewBD->setInvalidDecl();
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   return NewDD;
10010b57cec5SDimitry Andric }
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
10040b57cec5SDimitry Andric   return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
10050b57cec5SDimitry Andric }
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
10080b57cec5SDimitry Andric                                              bool InstantiatingVarTemplate,
10090b57cec5SDimitry Andric                                              ArrayRef<BindingDecl*> *Bindings) {
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric   // Do substitution on the type of the declaration
10120b57cec5SDimitry Andric   TypeSourceInfo *DI = SemaRef.SubstType(
10130b57cec5SDimitry Andric       D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
10140b57cec5SDimitry Andric       D->getDeclName(), /*AllowDeducedTST*/true);
10150b57cec5SDimitry Andric   if (!DI)
10160b57cec5SDimitry Andric     return nullptr;
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric   if (DI->getType()->isFunctionType()) {
10190b57cec5SDimitry Andric     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
10200b57cec5SDimitry Andric       << D->isStaticDataMember() << DI->getType();
10210b57cec5SDimitry Andric     return nullptr;
10220b57cec5SDimitry Andric   }
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   DeclContext *DC = Owner;
10250b57cec5SDimitry Andric   if (D->isLocalExternDecl())
10260b57cec5SDimitry Andric     SemaRef.adjustContextForLocalExternDecl(DC);
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   // Build the instantiated declaration.
10290b57cec5SDimitry Andric   VarDecl *Var;
10300b57cec5SDimitry Andric   if (Bindings)
10310b57cec5SDimitry Andric     Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
10320b57cec5SDimitry Andric                                     D->getLocation(), DI->getType(), DI,
10330b57cec5SDimitry Andric                                     D->getStorageClass(), *Bindings);
10340b57cec5SDimitry Andric   else
10350b57cec5SDimitry Andric     Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
10360b57cec5SDimitry Andric                           D->getLocation(), D->getIdentifier(), DI->getType(),
10370b57cec5SDimitry Andric                           DI, D->getStorageClass());
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric   // In ARC, infer 'retaining' for variables of retainable type.
10400b57cec5SDimitry Andric   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
10410b57cec5SDimitry Andric       SemaRef.inferObjCARCLifetime(Var))
10420b57cec5SDimitry Andric     Var->setInvalidDecl();
10430b57cec5SDimitry Andric 
1044480093f4SDimitry Andric   if (SemaRef.getLangOpts().OpenCL)
1045480093f4SDimitry Andric     SemaRef.deduceOpenCLAddressSpace(Var);
1046480093f4SDimitry Andric 
10470b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
10480b57cec5SDimitry Andric   if (SubstQualifier(D, Var))
10490b57cec5SDimitry Andric     return nullptr;
10500b57cec5SDimitry Andric 
10510b57cec5SDimitry Andric   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
10520b57cec5SDimitry Andric                                      StartingScope, InstantiatingVarTemplate);
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   if (D->isNRVOVariable()) {
10550b57cec5SDimitry Andric     QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
10560b57cec5SDimitry Andric     if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
10570b57cec5SDimitry Andric       Var->setNRVOVariable(true);
10580b57cec5SDimitry Andric   }
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric   Var->setImplicit(D->isImplicit());
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric   if (Var->isStaticLocal())
10630b57cec5SDimitry Andric     SemaRef.CheckStaticLocalForDllExport(Var);
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric   return Var;
10660b57cec5SDimitry Andric }
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
10690b57cec5SDimitry Andric   AccessSpecDecl* AD
10700b57cec5SDimitry Andric     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
10710b57cec5SDimitry Andric                              D->getAccessSpecifierLoc(), D->getColonLoc());
10720b57cec5SDimitry Andric   Owner->addHiddenDecl(AD);
10730b57cec5SDimitry Andric   return AD;
10740b57cec5SDimitry Andric }
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
10770b57cec5SDimitry Andric   bool Invalid = false;
10780b57cec5SDimitry Andric   TypeSourceInfo *DI = D->getTypeSourceInfo();
10790b57cec5SDimitry Andric   if (DI->getType()->isInstantiationDependentType() ||
10800b57cec5SDimitry Andric       DI->getType()->isVariablyModifiedType())  {
10810b57cec5SDimitry Andric     DI = SemaRef.SubstType(DI, TemplateArgs,
10820b57cec5SDimitry Andric                            D->getLocation(), D->getDeclName());
10830b57cec5SDimitry Andric     if (!DI) {
10840b57cec5SDimitry Andric       DI = D->getTypeSourceInfo();
10850b57cec5SDimitry Andric       Invalid = true;
10860b57cec5SDimitry Andric     } else if (DI->getType()->isFunctionType()) {
10870b57cec5SDimitry Andric       // C++ [temp.arg.type]p3:
10880b57cec5SDimitry Andric       //   If a declaration acquires a function type through a type
10890b57cec5SDimitry Andric       //   dependent on a template-parameter and this causes a
10900b57cec5SDimitry Andric       //   declaration that does not use the syntactic form of a
10910b57cec5SDimitry Andric       //   function declarator to have function type, the program is
10920b57cec5SDimitry Andric       //   ill-formed.
10930b57cec5SDimitry Andric       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
10940b57cec5SDimitry Andric         << DI->getType();
10950b57cec5SDimitry Andric       Invalid = true;
10960b57cec5SDimitry Andric     }
10970b57cec5SDimitry Andric   } else {
10980b57cec5SDimitry Andric     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
10990b57cec5SDimitry Andric   }
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   Expr *BitWidth = D->getBitWidth();
11020b57cec5SDimitry Andric   if (Invalid)
11030b57cec5SDimitry Andric     BitWidth = nullptr;
11040b57cec5SDimitry Andric   else if (BitWidth) {
11050b57cec5SDimitry Andric     // The bit-width expression is a constant expression.
11060b57cec5SDimitry Andric     EnterExpressionEvaluationContext Unevaluated(
11070b57cec5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric     ExprResult InstantiatedBitWidth
11100b57cec5SDimitry Andric       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
11110b57cec5SDimitry Andric     if (InstantiatedBitWidth.isInvalid()) {
11120b57cec5SDimitry Andric       Invalid = true;
11130b57cec5SDimitry Andric       BitWidth = nullptr;
11140b57cec5SDimitry Andric     } else
11150b57cec5SDimitry Andric       BitWidth = InstantiatedBitWidth.getAs<Expr>();
11160b57cec5SDimitry Andric   }
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
11190b57cec5SDimitry Andric                                             DI->getType(), DI,
11200b57cec5SDimitry Andric                                             cast<RecordDecl>(Owner),
11210b57cec5SDimitry Andric                                             D->getLocation(),
11220b57cec5SDimitry Andric                                             D->isMutable(),
11230b57cec5SDimitry Andric                                             BitWidth,
11240b57cec5SDimitry Andric                                             D->getInClassInitStyle(),
11250b57cec5SDimitry Andric                                             D->getInnerLocStart(),
11260b57cec5SDimitry Andric                                             D->getAccess(),
11270b57cec5SDimitry Andric                                             nullptr);
11280b57cec5SDimitry Andric   if (!Field) {
11290b57cec5SDimitry Andric     cast<Decl>(Owner)->setInvalidDecl();
11300b57cec5SDimitry Andric     return nullptr;
11310b57cec5SDimitry Andric   }
11320b57cec5SDimitry Andric 
11330b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric   if (Field->hasAttrs())
11360b57cec5SDimitry Andric     SemaRef.CheckAlignasUnderalignment(Field);
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric   if (Invalid)
11390b57cec5SDimitry Andric     Field->setInvalidDecl();
11400b57cec5SDimitry Andric 
11410b57cec5SDimitry Andric   if (!Field->getDeclName()) {
11420b57cec5SDimitry Andric     // Keep track of where this decl came from.
11430b57cec5SDimitry Andric     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
11440b57cec5SDimitry Andric   }
11450b57cec5SDimitry Andric   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
11460b57cec5SDimitry Andric     if (Parent->isAnonymousStructOrUnion() &&
11470b57cec5SDimitry Andric         Parent->getRedeclContext()->isFunctionOrMethod())
11480b57cec5SDimitry Andric       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
11490b57cec5SDimitry Andric   }
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric   Field->setImplicit(D->isImplicit());
11520b57cec5SDimitry Andric   Field->setAccess(D->getAccess());
11530b57cec5SDimitry Andric   Owner->addDecl(Field);
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric   return Field;
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
11590b57cec5SDimitry Andric   bool Invalid = false;
11600b57cec5SDimitry Andric   TypeSourceInfo *DI = D->getTypeSourceInfo();
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric   if (DI->getType()->isVariablyModifiedType()) {
11630b57cec5SDimitry Andric     SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
11640b57cec5SDimitry Andric       << D;
11650b57cec5SDimitry Andric     Invalid = true;
11660b57cec5SDimitry Andric   } else if (DI->getType()->isInstantiationDependentType())  {
11670b57cec5SDimitry Andric     DI = SemaRef.SubstType(DI, TemplateArgs,
11680b57cec5SDimitry Andric                            D->getLocation(), D->getDeclName());
11690b57cec5SDimitry Andric     if (!DI) {
11700b57cec5SDimitry Andric       DI = D->getTypeSourceInfo();
11710b57cec5SDimitry Andric       Invalid = true;
11720b57cec5SDimitry Andric     } else if (DI->getType()->isFunctionType()) {
11730b57cec5SDimitry Andric       // C++ [temp.arg.type]p3:
11740b57cec5SDimitry Andric       //   If a declaration acquires a function type through a type
11750b57cec5SDimitry Andric       //   dependent on a template-parameter and this causes a
11760b57cec5SDimitry Andric       //   declaration that does not use the syntactic form of a
11770b57cec5SDimitry Andric       //   function declarator to have function type, the program is
11780b57cec5SDimitry Andric       //   ill-formed.
11790b57cec5SDimitry Andric       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
11800b57cec5SDimitry Andric       << DI->getType();
11810b57cec5SDimitry Andric       Invalid = true;
11820b57cec5SDimitry Andric     }
11830b57cec5SDimitry Andric   } else {
11840b57cec5SDimitry Andric     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
11850b57cec5SDimitry Andric   }
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric   MSPropertyDecl *Property = MSPropertyDecl::Create(
11880b57cec5SDimitry Andric       SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
11890b57cec5SDimitry Andric       DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
11920b57cec5SDimitry Andric                            StartingScope);
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric   if (Invalid)
11950b57cec5SDimitry Andric     Property->setInvalidDecl();
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   Property->setAccess(D->getAccess());
11980b57cec5SDimitry Andric   Owner->addDecl(Property);
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric   return Property;
12010b57cec5SDimitry Andric }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
12040b57cec5SDimitry Andric   NamedDecl **NamedChain =
12050b57cec5SDimitry Andric     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   int i = 0;
12080b57cec5SDimitry Andric   for (auto *PI : D->chain()) {
12090b57cec5SDimitry Andric     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
12100b57cec5SDimitry Andric                                               TemplateArgs);
12110b57cec5SDimitry Andric     if (!Next)
12120b57cec5SDimitry Andric       return nullptr;
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric     NamedChain[i++] = Next;
12150b57cec5SDimitry Andric   }
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
12180b57cec5SDimitry Andric   IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
12190b57cec5SDimitry Andric       SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
12200b57cec5SDimitry Andric       {NamedChain, D->getChainingSize()});
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric   for (const auto *Attr : D->attrs())
12230b57cec5SDimitry Andric     IndirectField->addAttr(Attr->clone(SemaRef.Context));
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric   IndirectField->setImplicit(D->isImplicit());
12260b57cec5SDimitry Andric   IndirectField->setAccess(D->getAccess());
12270b57cec5SDimitry Andric   Owner->addDecl(IndirectField);
12280b57cec5SDimitry Andric   return IndirectField;
12290b57cec5SDimitry Andric }
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
12320b57cec5SDimitry Andric   // Handle friend type expressions by simply substituting template
12330b57cec5SDimitry Andric   // parameters into the pattern type and checking the result.
12340b57cec5SDimitry Andric   if (TypeSourceInfo *Ty = D->getFriendType()) {
12350b57cec5SDimitry Andric     TypeSourceInfo *InstTy;
12360b57cec5SDimitry Andric     // If this is an unsupported friend, don't bother substituting template
12370b57cec5SDimitry Andric     // arguments into it. The actual type referred to won't be used by any
12380b57cec5SDimitry Andric     // parts of Clang, and may not be valid for instantiating. Just use the
12390b57cec5SDimitry Andric     // same info for the instantiated friend.
12400b57cec5SDimitry Andric     if (D->isUnsupportedFriend()) {
12410b57cec5SDimitry Andric       InstTy = Ty;
12420b57cec5SDimitry Andric     } else {
12430b57cec5SDimitry Andric       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
12440b57cec5SDimitry Andric                                  D->getLocation(), DeclarationName());
12450b57cec5SDimitry Andric     }
12460b57cec5SDimitry Andric     if (!InstTy)
12470b57cec5SDimitry Andric       return nullptr;
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
12500b57cec5SDimitry Andric                                                  D->getFriendLoc(), InstTy);
12510b57cec5SDimitry Andric     if (!FD)
12520b57cec5SDimitry Andric       return nullptr;
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric     FD->setAccess(AS_public);
12550b57cec5SDimitry Andric     FD->setUnsupportedFriend(D->isUnsupportedFriend());
12560b57cec5SDimitry Andric     Owner->addDecl(FD);
12570b57cec5SDimitry Andric     return FD;
12580b57cec5SDimitry Andric   }
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric   NamedDecl *ND = D->getFriendDecl();
12610b57cec5SDimitry Andric   assert(ND && "friend decl must be a decl or a type!");
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   // All of the Visit implementations for the various potential friend
12640b57cec5SDimitry Andric   // declarations have to be carefully written to work for friend
12650b57cec5SDimitry Andric   // objects, with the most important detail being that the target
12660b57cec5SDimitry Andric   // decl should almost certainly not be placed in Owner.
12670b57cec5SDimitry Andric   Decl *NewND = Visit(ND);
12680b57cec5SDimitry Andric   if (!NewND) return nullptr;
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   FriendDecl *FD =
12710b57cec5SDimitry Andric     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
12720b57cec5SDimitry Andric                        cast<NamedDecl>(NewND), D->getFriendLoc());
12730b57cec5SDimitry Andric   FD->setAccess(AS_public);
12740b57cec5SDimitry Andric   FD->setUnsupportedFriend(D->isUnsupportedFriend());
12750b57cec5SDimitry Andric   Owner->addDecl(FD);
12760b57cec5SDimitry Andric   return FD;
12770b57cec5SDimitry Andric }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
12800b57cec5SDimitry Andric   Expr *AssertExpr = D->getAssertExpr();
12810b57cec5SDimitry Andric 
12820b57cec5SDimitry Andric   // The expression in a static assertion is a constant expression.
12830b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
12840b57cec5SDimitry Andric       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric   ExprResult InstantiatedAssertExpr
12870b57cec5SDimitry Andric     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
12880b57cec5SDimitry Andric   if (InstantiatedAssertExpr.isInvalid())
12890b57cec5SDimitry Andric     return nullptr;
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric   return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
12920b57cec5SDimitry Andric                                               InstantiatedAssertExpr.get(),
12930b57cec5SDimitry Andric                                               D->getMessage(),
12940b57cec5SDimitry Andric                                               D->getRParenLoc(),
12950b57cec5SDimitry Andric                                               D->isFailed());
12960b57cec5SDimitry Andric }
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
12990b57cec5SDimitry Andric   EnumDecl *PrevDecl = nullptr;
13000b57cec5SDimitry Andric   if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
13010b57cec5SDimitry Andric     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
13020b57cec5SDimitry Andric                                                    PatternPrev,
13030b57cec5SDimitry Andric                                                    TemplateArgs);
13040b57cec5SDimitry Andric     if (!Prev) return nullptr;
13050b57cec5SDimitry Andric     PrevDecl = cast<EnumDecl>(Prev);
13060b57cec5SDimitry Andric   }
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric   EnumDecl *Enum =
13090b57cec5SDimitry Andric       EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
13100b57cec5SDimitry Andric                        D->getLocation(), D->getIdentifier(), PrevDecl,
13110b57cec5SDimitry Andric                        D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
13120b57cec5SDimitry Andric   if (D->isFixed()) {
13130b57cec5SDimitry Andric     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
13140b57cec5SDimitry Andric       // If we have type source information for the underlying type, it means it
13150b57cec5SDimitry Andric       // has been explicitly set by the user. Perform substitution on it before
13160b57cec5SDimitry Andric       // moving on.
13170b57cec5SDimitry Andric       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13180b57cec5SDimitry Andric       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
13190b57cec5SDimitry Andric                                                 DeclarationName());
13200b57cec5SDimitry Andric       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
13210b57cec5SDimitry Andric         Enum->setIntegerType(SemaRef.Context.IntTy);
13220b57cec5SDimitry Andric       else
13230b57cec5SDimitry Andric         Enum->setIntegerTypeSourceInfo(NewTI);
13240b57cec5SDimitry Andric     } else {
13250b57cec5SDimitry Andric       assert(!D->getIntegerType()->isDependentType()
13260b57cec5SDimitry Andric              && "Dependent type without type source info");
13270b57cec5SDimitry Andric       Enum->setIntegerType(D->getIntegerType());
13280b57cec5SDimitry Andric     }
13290b57cec5SDimitry Andric   }
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
13340b57cec5SDimitry Andric   Enum->setAccess(D->getAccess());
13350b57cec5SDimitry Andric   // Forward the mangling number from the template to the instantiated decl.
13360b57cec5SDimitry Andric   SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
13370b57cec5SDimitry Andric   // See if the old tag was defined along with a declarator.
13380b57cec5SDimitry Andric   // If it did, mark the new tag as being associated with that declarator.
13390b57cec5SDimitry Andric   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
13400b57cec5SDimitry Andric     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
13410b57cec5SDimitry Andric   // See if the old tag was defined along with a typedef.
13420b57cec5SDimitry Andric   // If it did, mark the new tag as being associated with that typedef.
13430b57cec5SDimitry Andric   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
13440b57cec5SDimitry Andric     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
13450b57cec5SDimitry Andric   if (SubstQualifier(D, Enum)) return nullptr;
13460b57cec5SDimitry Andric   Owner->addDecl(Enum);
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric   EnumDecl *Def = D->getDefinition();
13490b57cec5SDimitry Andric   if (Def && Def != D) {
13500b57cec5SDimitry Andric     // If this is an out-of-line definition of an enum member template, check
13510b57cec5SDimitry Andric     // that the underlying types match in the instantiation of both
13520b57cec5SDimitry Andric     // declarations.
13530b57cec5SDimitry Andric     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
13540b57cec5SDimitry Andric       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13550b57cec5SDimitry Andric       QualType DefnUnderlying =
13560b57cec5SDimitry Andric         SemaRef.SubstType(TI->getType(), TemplateArgs,
13570b57cec5SDimitry Andric                           UnderlyingLoc, DeclarationName());
13580b57cec5SDimitry Andric       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
13590b57cec5SDimitry Andric                                      DefnUnderlying, /*IsFixed=*/true, Enum);
13600b57cec5SDimitry Andric     }
13610b57cec5SDimitry Andric   }
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric   // C++11 [temp.inst]p1: The implicit instantiation of a class template
13640b57cec5SDimitry Andric   // specialization causes the implicit instantiation of the declarations, but
13650b57cec5SDimitry Andric   // not the definitions of scoped member enumerations.
13660b57cec5SDimitry Andric   //
13670b57cec5SDimitry Andric   // DR1484 clarifies that enumeration definitions inside of a template
13680b57cec5SDimitry Andric   // declaration aren't considered entities that can be separately instantiated
13690b57cec5SDimitry Andric   // from the rest of the entity they are declared inside of.
13700b57cec5SDimitry Andric   if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
13710b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
13720b57cec5SDimitry Andric     InstantiateEnumDefinition(Enum, Def);
13730b57cec5SDimitry Andric   }
13740b57cec5SDimitry Andric 
13750b57cec5SDimitry Andric   return Enum;
13760b57cec5SDimitry Andric }
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric void TemplateDeclInstantiator::InstantiateEnumDefinition(
13790b57cec5SDimitry Andric     EnumDecl *Enum, EnumDecl *Pattern) {
13800b57cec5SDimitry Andric   Enum->startDefinition();
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric   // Update the location to refer to the definition.
13830b57cec5SDimitry Andric   Enum->setLocation(Pattern->getLocation());
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric   SmallVector<Decl*, 4> Enumerators;
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric   EnumConstantDecl *LastEnumConst = nullptr;
13880b57cec5SDimitry Andric   for (auto *EC : Pattern->enumerators()) {
13890b57cec5SDimitry Andric     // The specified value for the enumerator.
13900b57cec5SDimitry Andric     ExprResult Value((Expr *)nullptr);
13910b57cec5SDimitry Andric     if (Expr *UninstValue = EC->getInitExpr()) {
13920b57cec5SDimitry Andric       // The enumerator's value expression is a constant expression.
13930b57cec5SDimitry Andric       EnterExpressionEvaluationContext Unevaluated(
13940b57cec5SDimitry Andric           SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
13970b57cec5SDimitry Andric     }
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric     // Drop the initial value and continue.
14000b57cec5SDimitry Andric     bool isInvalid = false;
14010b57cec5SDimitry Andric     if (Value.isInvalid()) {
14020b57cec5SDimitry Andric       Value = nullptr;
14030b57cec5SDimitry Andric       isInvalid = true;
14040b57cec5SDimitry Andric     }
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric     EnumConstantDecl *EnumConst
14070b57cec5SDimitry Andric       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
14080b57cec5SDimitry Andric                                   EC->getLocation(), EC->getIdentifier(),
14090b57cec5SDimitry Andric                                   Value.get());
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric     if (isInvalid) {
14120b57cec5SDimitry Andric       if (EnumConst)
14130b57cec5SDimitry Andric         EnumConst->setInvalidDecl();
14140b57cec5SDimitry Andric       Enum->setInvalidDecl();
14150b57cec5SDimitry Andric     }
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric     if (EnumConst) {
14180b57cec5SDimitry Andric       SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric       EnumConst->setAccess(Enum->getAccess());
14210b57cec5SDimitry Andric       Enum->addDecl(EnumConst);
14220b57cec5SDimitry Andric       Enumerators.push_back(EnumConst);
14230b57cec5SDimitry Andric       LastEnumConst = EnumConst;
14240b57cec5SDimitry Andric 
14250b57cec5SDimitry Andric       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
14260b57cec5SDimitry Andric           !Enum->isScoped()) {
14270b57cec5SDimitry Andric         // If the enumeration is within a function or method, record the enum
14280b57cec5SDimitry Andric         // constant as a local.
14290b57cec5SDimitry Andric         SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
14300b57cec5SDimitry Andric       }
14310b57cec5SDimitry Andric     }
14320b57cec5SDimitry Andric   }
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric   SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
14350b57cec5SDimitry Andric                         Enumerators, nullptr, ParsedAttributesView());
14360b57cec5SDimitry Andric }
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
14390b57cec5SDimitry Andric   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
14400b57cec5SDimitry Andric }
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric Decl *
14430b57cec5SDimitry Andric TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
14440b57cec5SDimitry Andric   llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
14450b57cec5SDimitry Andric }
14460b57cec5SDimitry Andric 
14470b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
14480b57cec5SDimitry Andric   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric   // Create a local instantiation scope for this class template, which
14510b57cec5SDimitry Andric   // will contain the instantiations of the template parameters.
14520b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
14530b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
14540b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
14550b57cec5SDimitry Andric   if (!InstParams)
14560b57cec5SDimitry Andric     return nullptr;
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric   CXXRecordDecl *Pattern = D->getTemplatedDecl();
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   // Instantiate the qualifier.  We have to do this first in case
14610b57cec5SDimitry Andric   // we're a friend declaration, because if we are then we need to put
14620b57cec5SDimitry Andric   // the new declaration in the appropriate context.
14630b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
14640b57cec5SDimitry Andric   if (QualifierLoc) {
14650b57cec5SDimitry Andric     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
14660b57cec5SDimitry Andric                                                        TemplateArgs);
14670b57cec5SDimitry Andric     if (!QualifierLoc)
14680b57cec5SDimitry Andric       return nullptr;
14690b57cec5SDimitry Andric   }
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric   CXXRecordDecl *PrevDecl = nullptr;
14720b57cec5SDimitry Andric   ClassTemplateDecl *PrevClassTemplate = nullptr;
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
14750b57cec5SDimitry Andric     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
14760b57cec5SDimitry Andric     if (!Found.empty()) {
14770b57cec5SDimitry Andric       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
14780b57cec5SDimitry Andric       if (PrevClassTemplate)
14790b57cec5SDimitry Andric         PrevDecl = PrevClassTemplate->getTemplatedDecl();
14800b57cec5SDimitry Andric     }
14810b57cec5SDimitry Andric   }
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric   // If this isn't a friend, then it's a member template, in which
14840b57cec5SDimitry Andric   // case we just want to build the instantiation in the
14850b57cec5SDimitry Andric   // specialization.  If it is a friend, we want to build it in
14860b57cec5SDimitry Andric   // the appropriate context.
14870b57cec5SDimitry Andric   DeclContext *DC = Owner;
14880b57cec5SDimitry Andric   if (isFriend) {
14890b57cec5SDimitry Andric     if (QualifierLoc) {
14900b57cec5SDimitry Andric       CXXScopeSpec SS;
14910b57cec5SDimitry Andric       SS.Adopt(QualifierLoc);
14920b57cec5SDimitry Andric       DC = SemaRef.computeDeclContext(SS);
14930b57cec5SDimitry Andric       if (!DC) return nullptr;
14940b57cec5SDimitry Andric     } else {
14950b57cec5SDimitry Andric       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
14960b57cec5SDimitry Andric                                            Pattern->getDeclContext(),
14970b57cec5SDimitry Andric                                            TemplateArgs);
14980b57cec5SDimitry Andric     }
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric     // Look for a previous declaration of the template in the owning
15010b57cec5SDimitry Andric     // context.
15020b57cec5SDimitry Andric     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
15030b57cec5SDimitry Andric                    Sema::LookupOrdinaryName,
15040b57cec5SDimitry Andric                    SemaRef.forRedeclarationInCurContext());
15050b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(R, DC);
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric     if (R.isSingleResult()) {
15080b57cec5SDimitry Andric       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
15090b57cec5SDimitry Andric       if (PrevClassTemplate)
15100b57cec5SDimitry Andric         PrevDecl = PrevClassTemplate->getTemplatedDecl();
15110b57cec5SDimitry Andric     }
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric     if (!PrevClassTemplate && QualifierLoc) {
15140b57cec5SDimitry Andric       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
15150b57cec5SDimitry Andric         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
15160b57cec5SDimitry Andric         << QualifierLoc.getSourceRange();
15170b57cec5SDimitry Andric       return nullptr;
15180b57cec5SDimitry Andric     }
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric     bool AdoptedPreviousTemplateParams = false;
15210b57cec5SDimitry Andric     if (PrevClassTemplate) {
15220b57cec5SDimitry Andric       bool Complain = true;
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric       // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
15250b57cec5SDimitry Andric       // template for struct std::tr1::__detail::_Map_base, where the
15260b57cec5SDimitry Andric       // template parameters of the friend declaration don't match the
15270b57cec5SDimitry Andric       // template parameters of the original declaration. In this one
15280b57cec5SDimitry Andric       // case, we don't complain about the ill-formed friend
15290b57cec5SDimitry Andric       // declaration.
15300b57cec5SDimitry Andric       if (isFriend && Pattern->getIdentifier() &&
15310b57cec5SDimitry Andric           Pattern->getIdentifier()->isStr("_Map_base") &&
15320b57cec5SDimitry Andric           DC->isNamespace() &&
15330b57cec5SDimitry Andric           cast<NamespaceDecl>(DC)->getIdentifier() &&
15340b57cec5SDimitry Andric           cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
15350b57cec5SDimitry Andric         DeclContext *DCParent = DC->getParent();
15360b57cec5SDimitry Andric         if (DCParent->isNamespace() &&
15370b57cec5SDimitry Andric             cast<NamespaceDecl>(DCParent)->getIdentifier() &&
15380b57cec5SDimitry Andric             cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
15390b57cec5SDimitry Andric           if (cast<Decl>(DCParent)->isInStdNamespace())
15400b57cec5SDimitry Andric             Complain = false;
15410b57cec5SDimitry Andric         }
15420b57cec5SDimitry Andric       }
15430b57cec5SDimitry Andric 
15440b57cec5SDimitry Andric       TemplateParameterList *PrevParams
15450b57cec5SDimitry Andric         = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric       // Make sure the parameter lists match.
15480b57cec5SDimitry Andric       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
15490b57cec5SDimitry Andric                                                   Complain,
15500b57cec5SDimitry Andric                                                   Sema::TPL_TemplateMatch)) {
15510b57cec5SDimitry Andric         if (Complain)
15520b57cec5SDimitry Andric           return nullptr;
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric         AdoptedPreviousTemplateParams = true;
15550b57cec5SDimitry Andric         InstParams = PrevParams;
15560b57cec5SDimitry Andric       }
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric       // Do some additional validation, then merge default arguments
15590b57cec5SDimitry Andric       // from the existing declarations.
15600b57cec5SDimitry Andric       if (!AdoptedPreviousTemplateParams &&
15610b57cec5SDimitry Andric           SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
15620b57cec5SDimitry Andric                                              Sema::TPC_ClassTemplate))
15630b57cec5SDimitry Andric         return nullptr;
15640b57cec5SDimitry Andric     }
15650b57cec5SDimitry Andric   }
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric   CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
15680b57cec5SDimitry Andric       SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
15690b57cec5SDimitry Andric       Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
15700b57cec5SDimitry Andric       /*DelayTypeCreation=*/true);
15710b57cec5SDimitry Andric 
15720b57cec5SDimitry Andric   if (QualifierLoc)
15730b57cec5SDimitry Andric     RecordInst->setQualifierInfo(QualifierLoc);
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
15760b57cec5SDimitry Andric                                                               StartingScope);
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric   ClassTemplateDecl *Inst
15790b57cec5SDimitry Andric     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
15800b57cec5SDimitry Andric                                 D->getIdentifier(), InstParams, RecordInst);
15810b57cec5SDimitry Andric   assert(!(isFriend && Owner->isDependentContext()));
15820b57cec5SDimitry Andric   Inst->setPreviousDecl(PrevClassTemplate);
15830b57cec5SDimitry Andric 
15840b57cec5SDimitry Andric   RecordInst->setDescribedClassTemplate(Inst);
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric   if (isFriend) {
15870b57cec5SDimitry Andric     if (PrevClassTemplate)
15880b57cec5SDimitry Andric       Inst->setAccess(PrevClassTemplate->getAccess());
15890b57cec5SDimitry Andric     else
15900b57cec5SDimitry Andric       Inst->setAccess(D->getAccess());
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric     Inst->setObjectOfFriendDecl();
15930b57cec5SDimitry Andric     // TODO: do we want to track the instantiation progeny of this
15940b57cec5SDimitry Andric     // friend target decl?
15950b57cec5SDimitry Andric   } else {
15960b57cec5SDimitry Andric     Inst->setAccess(D->getAccess());
15970b57cec5SDimitry Andric     if (!PrevClassTemplate)
15980b57cec5SDimitry Andric       Inst->setInstantiatedFromMemberTemplate(D);
15990b57cec5SDimitry Andric   }
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric   // Trigger creation of the type for the instantiation.
16020b57cec5SDimitry Andric   SemaRef.Context.getInjectedClassNameType(RecordInst,
16030b57cec5SDimitry Andric                                     Inst->getInjectedClassNameSpecialization());
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric   // Finish handling of friends.
16060b57cec5SDimitry Andric   if (isFriend) {
16070b57cec5SDimitry Andric     DC->makeDeclVisibleInContext(Inst);
16080b57cec5SDimitry Andric     Inst->setLexicalDeclContext(Owner);
16090b57cec5SDimitry Andric     RecordInst->setLexicalDeclContext(Owner);
16100b57cec5SDimitry Andric     return Inst;
16110b57cec5SDimitry Andric   }
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric   if (D->isOutOfLine()) {
16140b57cec5SDimitry Andric     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
16150b57cec5SDimitry Andric     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
16160b57cec5SDimitry Andric   }
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric   Owner->addDecl(Inst);
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric   if (!PrevClassTemplate) {
16210b57cec5SDimitry Andric     // Queue up any out-of-line partial specializations of this member
16220b57cec5SDimitry Andric     // class template; the client will force their instantiation once
16230b57cec5SDimitry Andric     // the enclosing class has been instantiated.
16240b57cec5SDimitry Andric     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
16250b57cec5SDimitry Andric     D->getPartialSpecializations(PartialSpecs);
16260b57cec5SDimitry Andric     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
16270b57cec5SDimitry Andric       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
16280b57cec5SDimitry Andric         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
16290b57cec5SDimitry Andric   }
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   return Inst;
16320b57cec5SDimitry Andric }
16330b57cec5SDimitry Andric 
16340b57cec5SDimitry Andric Decl *
16350b57cec5SDimitry Andric TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
16360b57cec5SDimitry Andric                                    ClassTemplatePartialSpecializationDecl *D) {
16370b57cec5SDimitry Andric   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   // Lookup the already-instantiated declaration in the instantiation
16400b57cec5SDimitry Andric   // of the class template and return that.
16410b57cec5SDimitry Andric   DeclContext::lookup_result Found
16420b57cec5SDimitry Andric     = Owner->lookup(ClassTemplate->getDeclName());
16430b57cec5SDimitry Andric   if (Found.empty())
16440b57cec5SDimitry Andric     return nullptr;
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric   ClassTemplateDecl *InstClassTemplate
16470b57cec5SDimitry Andric     = dyn_cast<ClassTemplateDecl>(Found.front());
16480b57cec5SDimitry Andric   if (!InstClassTemplate)
16490b57cec5SDimitry Andric     return nullptr;
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric   if (ClassTemplatePartialSpecializationDecl *Result
16520b57cec5SDimitry Andric         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
16530b57cec5SDimitry Andric     return Result;
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
16560b57cec5SDimitry Andric }
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
16590b57cec5SDimitry Andric   assert(D->getTemplatedDecl()->isStaticDataMember() &&
16600b57cec5SDimitry Andric          "Only static data member templates are allowed.");
16610b57cec5SDimitry Andric 
16620b57cec5SDimitry Andric   // Create a local instantiation scope for this variable template, which
16630b57cec5SDimitry Andric   // will contain the instantiations of the template parameters.
16640b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
16650b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
16660b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
16670b57cec5SDimitry Andric   if (!InstParams)
16680b57cec5SDimitry Andric     return nullptr;
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric   VarDecl *Pattern = D->getTemplatedDecl();
16710b57cec5SDimitry Andric   VarTemplateDecl *PrevVarTemplate = nullptr;
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric   if (getPreviousDeclForInstantiation(Pattern)) {
16740b57cec5SDimitry Andric     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
16750b57cec5SDimitry Andric     if (!Found.empty())
16760b57cec5SDimitry Andric       PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
16770b57cec5SDimitry Andric   }
16780b57cec5SDimitry Andric 
16790b57cec5SDimitry Andric   VarDecl *VarInst =
16800b57cec5SDimitry Andric       cast_or_null<VarDecl>(VisitVarDecl(Pattern,
16810b57cec5SDimitry Andric                                          /*InstantiatingVarTemplate=*/true));
16820b57cec5SDimitry Andric   if (!VarInst) return nullptr;
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric   DeclContext *DC = Owner;
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric   VarTemplateDecl *Inst = VarTemplateDecl::Create(
16870b57cec5SDimitry Andric       SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
16880b57cec5SDimitry Andric       VarInst);
16890b57cec5SDimitry Andric   VarInst->setDescribedVarTemplate(Inst);
16900b57cec5SDimitry Andric   Inst->setPreviousDecl(PrevVarTemplate);
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric   Inst->setAccess(D->getAccess());
16930b57cec5SDimitry Andric   if (!PrevVarTemplate)
16940b57cec5SDimitry Andric     Inst->setInstantiatedFromMemberTemplate(D);
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric   if (D->isOutOfLine()) {
16970b57cec5SDimitry Andric     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
16980b57cec5SDimitry Andric     VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
16990b57cec5SDimitry Andric   }
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric   Owner->addDecl(Inst);
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric   if (!PrevVarTemplate) {
17040b57cec5SDimitry Andric     // Queue up any out-of-line partial specializations of this member
17050b57cec5SDimitry Andric     // variable template; the client will force their instantiation once
17060b57cec5SDimitry Andric     // the enclosing class has been instantiated.
17070b57cec5SDimitry Andric     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
17080b57cec5SDimitry Andric     D->getPartialSpecializations(PartialSpecs);
17090b57cec5SDimitry Andric     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
17100b57cec5SDimitry Andric       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
17110b57cec5SDimitry Andric         OutOfLineVarPartialSpecs.push_back(
17120b57cec5SDimitry Andric             std::make_pair(Inst, PartialSpecs[I]));
17130b57cec5SDimitry Andric   }
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   return Inst;
17160b57cec5SDimitry Andric }
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
17190b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *D) {
17200b57cec5SDimitry Andric   assert(D->isStaticDataMember() &&
17210b57cec5SDimitry Andric          "Only static data member templates are allowed.");
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
17240b57cec5SDimitry Andric 
17250b57cec5SDimitry Andric   // Lookup the already-instantiated declaration and return that.
17260b57cec5SDimitry Andric   DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
17270b57cec5SDimitry Andric   assert(!Found.empty() && "Instantiation found nothing?");
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric   VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
17300b57cec5SDimitry Andric   assert(InstVarTemplate && "Instantiation did not find a variable template?");
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   if (VarTemplatePartialSpecializationDecl *Result =
17330b57cec5SDimitry Andric           InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
17340b57cec5SDimitry Andric     return Result;
17350b57cec5SDimitry Andric 
17360b57cec5SDimitry Andric   return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
17370b57cec5SDimitry Andric }
17380b57cec5SDimitry Andric 
17390b57cec5SDimitry Andric Decl *
17400b57cec5SDimitry Andric TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
17410b57cec5SDimitry Andric   // Create a local instantiation scope for this function template, which
17420b57cec5SDimitry Andric   // will contain the instantiations of the template parameters and then get
17430b57cec5SDimitry Andric   // merged with the local instantiation scope for the function template
17440b57cec5SDimitry Andric   // itself.
17450b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
17480b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
17490b57cec5SDimitry Andric   if (!InstParams)
17500b57cec5SDimitry Andric     return nullptr;
17510b57cec5SDimitry Andric 
17520b57cec5SDimitry Andric   FunctionDecl *Instantiated = nullptr;
17530b57cec5SDimitry Andric   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
17540b57cec5SDimitry Andric     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
17550b57cec5SDimitry Andric                                                                  InstParams));
17560b57cec5SDimitry Andric   else
17570b57cec5SDimitry Andric     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
17580b57cec5SDimitry Andric                                                           D->getTemplatedDecl(),
17590b57cec5SDimitry Andric                                                                 InstParams));
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   if (!Instantiated)
17620b57cec5SDimitry Andric     return nullptr;
17630b57cec5SDimitry Andric 
17640b57cec5SDimitry Andric   // Link the instantiated function template declaration to the function
17650b57cec5SDimitry Andric   // template from which it was instantiated.
17660b57cec5SDimitry Andric   FunctionTemplateDecl *InstTemplate
17670b57cec5SDimitry Andric     = Instantiated->getDescribedFunctionTemplate();
17680b57cec5SDimitry Andric   InstTemplate->setAccess(D->getAccess());
17690b57cec5SDimitry Andric   assert(InstTemplate &&
17700b57cec5SDimitry Andric          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   // Link the instantiation back to the pattern *unless* this is a
17750b57cec5SDimitry Andric   // non-definition friend declaration.
17760b57cec5SDimitry Andric   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
17770b57cec5SDimitry Andric       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
17780b57cec5SDimitry Andric     InstTemplate->setInstantiatedFromMemberTemplate(D);
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric   // Make declarations visible in the appropriate context.
17810b57cec5SDimitry Andric   if (!isFriend) {
17820b57cec5SDimitry Andric     Owner->addDecl(InstTemplate);
17830b57cec5SDimitry Andric   } else if (InstTemplate->getDeclContext()->isRecord() &&
17840b57cec5SDimitry Andric              !getPreviousDeclForInstantiation(D)) {
17850b57cec5SDimitry Andric     SemaRef.CheckFriendAccess(InstTemplate);
17860b57cec5SDimitry Andric   }
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric   return InstTemplate;
17890b57cec5SDimitry Andric }
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
17920b57cec5SDimitry Andric   CXXRecordDecl *PrevDecl = nullptr;
17930b57cec5SDimitry Andric   if (D->isInjectedClassName())
17940b57cec5SDimitry Andric     PrevDecl = cast<CXXRecordDecl>(Owner);
17950b57cec5SDimitry Andric   else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
17960b57cec5SDimitry Andric     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
17970b57cec5SDimitry Andric                                                    PatternPrev,
17980b57cec5SDimitry Andric                                                    TemplateArgs);
17990b57cec5SDimitry Andric     if (!Prev) return nullptr;
18000b57cec5SDimitry Andric     PrevDecl = cast<CXXRecordDecl>(Prev);
18010b57cec5SDimitry Andric   }
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric   CXXRecordDecl *Record = CXXRecordDecl::Create(
18040b57cec5SDimitry Andric       SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
18050b57cec5SDimitry Andric       D->getLocation(), D->getIdentifier(), PrevDecl);
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
18080b57cec5SDimitry Andric   if (SubstQualifier(D, Record))
18090b57cec5SDimitry Andric     return nullptr;
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric   SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
18120b57cec5SDimitry Andric                                                               StartingScope);
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   Record->setImplicit(D->isImplicit());
18150b57cec5SDimitry Andric   // FIXME: Check against AS_none is an ugly hack to work around the issue that
18160b57cec5SDimitry Andric   // the tag decls introduced by friend class declarations don't have an access
18170b57cec5SDimitry Andric   // specifier. Remove once this area of the code gets sorted out.
18180b57cec5SDimitry Andric   if (D->getAccess() != AS_none)
18190b57cec5SDimitry Andric     Record->setAccess(D->getAccess());
18200b57cec5SDimitry Andric   if (!D->isInjectedClassName())
18210b57cec5SDimitry Andric     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric   // If the original function was part of a friend declaration,
18240b57cec5SDimitry Andric   // inherit its namespace state.
18250b57cec5SDimitry Andric   if (D->getFriendObjectKind())
18260b57cec5SDimitry Andric     Record->setObjectOfFriendDecl();
18270b57cec5SDimitry Andric 
18280b57cec5SDimitry Andric   // Make sure that anonymous structs and unions are recorded.
18290b57cec5SDimitry Andric   if (D->isAnonymousStructOrUnion())
18300b57cec5SDimitry Andric     Record->setAnonymousStructOrUnion(true);
18310b57cec5SDimitry Andric 
18320b57cec5SDimitry Andric   if (D->isLocalClass())
18330b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric   // Forward the mangling number from the template to the instantiated decl.
18360b57cec5SDimitry Andric   SemaRef.Context.setManglingNumber(Record,
18370b57cec5SDimitry Andric                                     SemaRef.Context.getManglingNumber(D));
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric   // See if the old tag was defined along with a declarator.
18400b57cec5SDimitry Andric   // If it did, mark the new tag as being associated with that declarator.
18410b57cec5SDimitry Andric   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
18420b57cec5SDimitry Andric     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
18430b57cec5SDimitry Andric 
18440b57cec5SDimitry Andric   // See if the old tag was defined along with a typedef.
18450b57cec5SDimitry Andric   // If it did, mark the new tag as being associated with that typedef.
18460b57cec5SDimitry Andric   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
18470b57cec5SDimitry Andric     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric   Owner->addDecl(Record);
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   // DR1484 clarifies that the members of a local class are instantiated as part
18520b57cec5SDimitry Andric   // of the instantiation of their enclosing entity.
18530b57cec5SDimitry Andric   if (D->isCompleteDefinition() && D->isLocalClass()) {
18540b57cec5SDimitry Andric     Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric     SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
18570b57cec5SDimitry Andric                              TSK_ImplicitInstantiation,
18580b57cec5SDimitry Andric                              /*Complain=*/true);
18590b57cec5SDimitry Andric 
18600b57cec5SDimitry Andric     // For nested local classes, we will instantiate the members when we
18610b57cec5SDimitry Andric     // reach the end of the outermost (non-nested) local class.
18620b57cec5SDimitry Andric     if (!D->isCXXClassMember())
18630b57cec5SDimitry Andric       SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
18640b57cec5SDimitry Andric                                       TSK_ImplicitInstantiation);
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric     // This class may have local implicit instantiations that need to be
18670b57cec5SDimitry Andric     // performed within this scope.
18680b57cec5SDimitry Andric     LocalInstantiations.perform();
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   SemaRef.DiagnoseUnusedNestedTypedefs(Record);
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric   return Record;
18740b57cec5SDimitry Andric }
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric /// Adjust the given function type for an instantiation of the
18770b57cec5SDimitry Andric /// given declaration, to cope with modifications to the function's type that
18780b57cec5SDimitry Andric /// aren't reflected in the type-source information.
18790b57cec5SDimitry Andric ///
18800b57cec5SDimitry Andric /// \param D The declaration we're instantiating.
18810b57cec5SDimitry Andric /// \param TInfo The already-instantiated type.
18820b57cec5SDimitry Andric static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
18830b57cec5SDimitry Andric                                                    FunctionDecl *D,
18840b57cec5SDimitry Andric                                                    TypeSourceInfo *TInfo) {
18850b57cec5SDimitry Andric   const FunctionProtoType *OrigFunc
18860b57cec5SDimitry Andric     = D->getType()->castAs<FunctionProtoType>();
18870b57cec5SDimitry Andric   const FunctionProtoType *NewFunc
18880b57cec5SDimitry Andric     = TInfo->getType()->castAs<FunctionProtoType>();
18890b57cec5SDimitry Andric   if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
18900b57cec5SDimitry Andric     return TInfo->getType();
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric   FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
18930b57cec5SDimitry Andric   NewEPI.ExtInfo = OrigFunc->getExtInfo();
18940b57cec5SDimitry Andric   return Context.getFunctionType(NewFunc->getReturnType(),
18950b57cec5SDimitry Andric                                  NewFunc->getParamTypes(), NewEPI);
18960b57cec5SDimitry Andric }
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric /// Normal class members are of more specific types and therefore
18990b57cec5SDimitry Andric /// don't make it here.  This function serves three purposes:
19000b57cec5SDimitry Andric ///   1) instantiating function templates
19010b57cec5SDimitry Andric ///   2) substituting friend declarations
19020b57cec5SDimitry Andric ///   3) substituting deduction guide declarations for nested class templates
1903480093f4SDimitry Andric Decl *TemplateDeclInstantiator::VisitFunctionDecl(
1904480093f4SDimitry Andric     FunctionDecl *D, TemplateParameterList *TemplateParams,
1905480093f4SDimitry Andric     RewriteKind FunctionRewriteKind) {
19060b57cec5SDimitry Andric   // Check whether there is already a function template specialization for
19070b57cec5SDimitry Andric   // this declaration.
19080b57cec5SDimitry Andric   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
19090b57cec5SDimitry Andric   if (FunctionTemplate && !TemplateParams) {
19100b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric     void *InsertPos = nullptr;
19130b57cec5SDimitry Andric     FunctionDecl *SpecFunc
19140b57cec5SDimitry Andric       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
19150b57cec5SDimitry Andric 
19160b57cec5SDimitry Andric     // If we already have a function template specialization, return it.
19170b57cec5SDimitry Andric     if (SpecFunc)
19180b57cec5SDimitry Andric       return SpecFunc;
19190b57cec5SDimitry Andric   }
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric   bool isFriend;
19220b57cec5SDimitry Andric   if (FunctionTemplate)
19230b57cec5SDimitry Andric     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
19240b57cec5SDimitry Andric   else
19250b57cec5SDimitry Andric     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric   bool MergeWithParentScope = (TemplateParams != nullptr) ||
19280b57cec5SDimitry Andric     Owner->isFunctionOrMethod() ||
19290b57cec5SDimitry Andric     !(isa<Decl>(Owner) &&
19300b57cec5SDimitry Andric       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
19310b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric   ExplicitSpecifier InstantiatedExplicitSpecifier;
19340b57cec5SDimitry Andric   if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
19350b57cec5SDimitry Andric     InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
19360b57cec5SDimitry Andric         SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
19370b57cec5SDimitry Andric     if (InstantiatedExplicitSpecifier.isInvalid())
19380b57cec5SDimitry Andric       return nullptr;
19390b57cec5SDimitry Andric   }
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric   SmallVector<ParmVarDecl *, 4> Params;
19420b57cec5SDimitry Andric   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
19430b57cec5SDimitry Andric   if (!TInfo)
19440b57cec5SDimitry Andric     return nullptr;
19450b57cec5SDimitry Andric   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
19460b57cec5SDimitry Andric 
194713138422SDimitry Andric   if (TemplateParams && TemplateParams->size()) {
194813138422SDimitry Andric     auto *LastParam =
194913138422SDimitry Andric         dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
195013138422SDimitry Andric     if (LastParam && LastParam->isImplicit() &&
195113138422SDimitry Andric         LastParam->hasTypeConstraint()) {
195213138422SDimitry Andric       // In abbreviated templates, the type-constraints of invented template
195313138422SDimitry Andric       // type parameters are instantiated with the function type, invalidating
195413138422SDimitry Andric       // the TemplateParameterList which relied on the template type parameter
195513138422SDimitry Andric       // not having a type constraint. Recreate the TemplateParameterList with
195613138422SDimitry Andric       // the updated parameter list.
195713138422SDimitry Andric       TemplateParams = TemplateParameterList::Create(
195813138422SDimitry Andric           SemaRef.Context, TemplateParams->getTemplateLoc(),
195913138422SDimitry Andric           TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
196013138422SDimitry Andric           TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
196113138422SDimitry Andric     }
196213138422SDimitry Andric   }
196313138422SDimitry Andric 
19640b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
19650b57cec5SDimitry Andric   if (QualifierLoc) {
19660b57cec5SDimitry Andric     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
19670b57cec5SDimitry Andric                                                        TemplateArgs);
19680b57cec5SDimitry Andric     if (!QualifierLoc)
19690b57cec5SDimitry Andric       return nullptr;
19700b57cec5SDimitry Andric   }
19710b57cec5SDimitry Andric 
1972480093f4SDimitry Andric   // FIXME: Concepts: Do not substitute into constraint expressions
1973480093f4SDimitry Andric   Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
1974480093f4SDimitry Andric   if (TrailingRequiresClause) {
197555e4f9d5SDimitry Andric     EnterExpressionEvaluationContext ConstantEvaluated(
197655e4f9d5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
1977480093f4SDimitry Andric     ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
1978480093f4SDimitry Andric                                            TemplateArgs);
1979480093f4SDimitry Andric     if (SubstRC.isInvalid())
1980480093f4SDimitry Andric       return nullptr;
1981480093f4SDimitry Andric     TrailingRequiresClause = SubstRC.get();
1982480093f4SDimitry Andric     if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
1983480093f4SDimitry Andric       return nullptr;
1984480093f4SDimitry Andric   }
1985480093f4SDimitry Andric 
19860b57cec5SDimitry Andric   // If we're instantiating a local function declaration, put the result
19870b57cec5SDimitry Andric   // in the enclosing namespace; otherwise we need to find the instantiated
19880b57cec5SDimitry Andric   // context.
19890b57cec5SDimitry Andric   DeclContext *DC;
19900b57cec5SDimitry Andric   if (D->isLocalExternDecl()) {
19910b57cec5SDimitry Andric     DC = Owner;
19920b57cec5SDimitry Andric     SemaRef.adjustContextForLocalExternDecl(DC);
19930b57cec5SDimitry Andric   } else if (isFriend && QualifierLoc) {
19940b57cec5SDimitry Andric     CXXScopeSpec SS;
19950b57cec5SDimitry Andric     SS.Adopt(QualifierLoc);
19960b57cec5SDimitry Andric     DC = SemaRef.computeDeclContext(SS);
19970b57cec5SDimitry Andric     if (!DC) return nullptr;
19980b57cec5SDimitry Andric   } else {
19990b57cec5SDimitry Andric     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
20000b57cec5SDimitry Andric                                          TemplateArgs);
20010b57cec5SDimitry Andric   }
20020b57cec5SDimitry Andric 
20030b57cec5SDimitry Andric   DeclarationNameInfo NameInfo
20040b57cec5SDimitry Andric     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
20050b57cec5SDimitry Andric 
2006480093f4SDimitry Andric   if (FunctionRewriteKind != RewriteKind::None)
2007480093f4SDimitry Andric     adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2008480093f4SDimitry Andric 
20090b57cec5SDimitry Andric   FunctionDecl *Function;
20100b57cec5SDimitry Andric   if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
20110b57cec5SDimitry Andric     Function = CXXDeductionGuideDecl::Create(
20120b57cec5SDimitry Andric         SemaRef.Context, DC, D->getInnerLocStart(),
20130b57cec5SDimitry Andric         InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
20140b57cec5SDimitry Andric         D->getSourceRange().getEnd());
20150b57cec5SDimitry Andric     if (DGuide->isCopyDeductionCandidate())
20160b57cec5SDimitry Andric       cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
20170b57cec5SDimitry Andric     Function->setAccess(D->getAccess());
20180b57cec5SDimitry Andric   } else {
20190b57cec5SDimitry Andric     Function = FunctionDecl::Create(
20200b57cec5SDimitry Andric         SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
20210b57cec5SDimitry Andric         D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
2022480093f4SDimitry Andric         D->hasWrittenPrototype(), D->getConstexprKind(),
2023480093f4SDimitry Andric         TrailingRequiresClause);
20240b57cec5SDimitry Andric     Function->setRangeEnd(D->getSourceRange().getEnd());
20250b57cec5SDimitry Andric   }
20260b57cec5SDimitry Andric 
20270b57cec5SDimitry Andric   if (D->isInlined())
20280b57cec5SDimitry Andric     Function->setImplicitlyInline();
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric   if (QualifierLoc)
20310b57cec5SDimitry Andric     Function->setQualifierInfo(QualifierLoc);
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric   if (D->isLocalExternDecl())
20340b57cec5SDimitry Andric     Function->setLocalExternDecl();
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric   DeclContext *LexicalDC = Owner;
20370b57cec5SDimitry Andric   if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
20380b57cec5SDimitry Andric     assert(D->getDeclContext()->isFileContext());
20390b57cec5SDimitry Andric     LexicalDC = D->getDeclContext();
20400b57cec5SDimitry Andric   }
20410b57cec5SDimitry Andric 
20420b57cec5SDimitry Andric   Function->setLexicalDeclContext(LexicalDC);
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric   // Attach the parameters
20450b57cec5SDimitry Andric   for (unsigned P = 0; P < Params.size(); ++P)
20460b57cec5SDimitry Andric     if (Params[P])
20470b57cec5SDimitry Andric       Params[P]->setOwningFunction(Function);
20480b57cec5SDimitry Andric   Function->setParams(Params);
20490b57cec5SDimitry Andric 
2050480093f4SDimitry Andric   if (TrailingRequiresClause)
2051480093f4SDimitry Andric     Function->setTrailingRequiresClause(TrailingRequiresClause);
2052480093f4SDimitry Andric 
20530b57cec5SDimitry Andric   if (TemplateParams) {
20540b57cec5SDimitry Andric     // Our resulting instantiation is actually a function template, since we
20550b57cec5SDimitry Andric     // are substituting only the outer template parameters. For example, given
20560b57cec5SDimitry Andric     //
20570b57cec5SDimitry Andric     //   template<typename T>
20580b57cec5SDimitry Andric     //   struct X {
20590b57cec5SDimitry Andric     //     template<typename U> friend void f(T, U);
20600b57cec5SDimitry Andric     //   };
20610b57cec5SDimitry Andric     //
20620b57cec5SDimitry Andric     //   X<int> x;
20630b57cec5SDimitry Andric     //
20640b57cec5SDimitry Andric     // We are instantiating the friend function template "f" within X<int>,
20650b57cec5SDimitry Andric     // which means substituting int for T, but leaving "f" as a friend function
20660b57cec5SDimitry Andric     // template.
20670b57cec5SDimitry Andric     // Build the function template itself.
20680b57cec5SDimitry Andric     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
20690b57cec5SDimitry Andric                                                     Function->getLocation(),
20700b57cec5SDimitry Andric                                                     Function->getDeclName(),
20710b57cec5SDimitry Andric                                                     TemplateParams, Function);
20720b57cec5SDimitry Andric     Function->setDescribedFunctionTemplate(FunctionTemplate);
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric     FunctionTemplate->setLexicalDeclContext(LexicalDC);
20750b57cec5SDimitry Andric 
20760b57cec5SDimitry Andric     if (isFriend && D->isThisDeclarationADefinition()) {
20770b57cec5SDimitry Andric       FunctionTemplate->setInstantiatedFromMemberTemplate(
20780b57cec5SDimitry Andric                                            D->getDescribedFunctionTemplate());
20790b57cec5SDimitry Andric     }
20800b57cec5SDimitry Andric   } else if (FunctionTemplate) {
20810b57cec5SDimitry Andric     // Record this function template specialization.
20820b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
20830b57cec5SDimitry Andric     Function->setFunctionTemplateSpecialization(FunctionTemplate,
20840b57cec5SDimitry Andric                             TemplateArgumentList::CreateCopy(SemaRef.Context,
20850b57cec5SDimitry Andric                                                              Innermost),
20860b57cec5SDimitry Andric                                                 /*InsertPos=*/nullptr);
20870b57cec5SDimitry Andric   } else if (isFriend && D->isThisDeclarationADefinition()) {
20880b57cec5SDimitry Andric     // Do not connect the friend to the template unless it's actually a
20890b57cec5SDimitry Andric     // definition. We don't want non-template functions to be marked as being
20900b57cec5SDimitry Andric     // template instantiations.
20910b57cec5SDimitry Andric     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
20920b57cec5SDimitry Andric   }
20930b57cec5SDimitry Andric 
2094*e8d8bef9SDimitry Andric   if (isFriend) {
20950b57cec5SDimitry Andric     Function->setObjectOfFriendDecl();
2096*e8d8bef9SDimitry Andric     if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2097*e8d8bef9SDimitry Andric       FT->setObjectOfFriendDecl();
2098*e8d8bef9SDimitry Andric   }
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric   if (InitFunctionInstantiation(Function, D))
21010b57cec5SDimitry Andric     Function->setInvalidDecl();
21020b57cec5SDimitry Andric 
21030b57cec5SDimitry Andric   bool IsExplicitSpecialization = false;
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric   LookupResult Previous(
21060b57cec5SDimitry Andric       SemaRef, Function->getDeclName(), SourceLocation(),
21070b57cec5SDimitry Andric       D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
21080b57cec5SDimitry Andric                              : Sema::LookupOrdinaryName,
21090b57cec5SDimitry Andric       D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
21100b57cec5SDimitry Andric                              : SemaRef.forRedeclarationInCurContext());
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric   if (DependentFunctionTemplateSpecializationInfo *Info
21130b57cec5SDimitry Andric         = D->getDependentSpecializationInfo()) {
21140b57cec5SDimitry Andric     assert(isFriend && "non-friend has dependent specialization info?");
21150b57cec5SDimitry Andric 
21160b57cec5SDimitry Andric     // Instantiate the explicit template arguments.
21170b57cec5SDimitry Andric     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
21180b57cec5SDimitry Andric                                           Info->getRAngleLoc());
21190b57cec5SDimitry Andric     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
21200b57cec5SDimitry Andric                       ExplicitArgs, TemplateArgs))
21210b57cec5SDimitry Andric       return nullptr;
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric     // Map the candidate templates to their instantiations.
21240b57cec5SDimitry Andric     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
21250b57cec5SDimitry Andric       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
21260b57cec5SDimitry Andric                                                 Info->getTemplate(I),
21270b57cec5SDimitry Andric                                                 TemplateArgs);
21280b57cec5SDimitry Andric       if (!Temp) return nullptr;
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
21310b57cec5SDimitry Andric     }
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
21340b57cec5SDimitry Andric                                                     &ExplicitArgs,
21350b57cec5SDimitry Andric                                                     Previous))
21360b57cec5SDimitry Andric       Function->setInvalidDecl();
21370b57cec5SDimitry Andric 
21380b57cec5SDimitry Andric     IsExplicitSpecialization = true;
21390b57cec5SDimitry Andric   } else if (const ASTTemplateArgumentListInfo *Info =
21400b57cec5SDimitry Andric                  D->getTemplateSpecializationArgsAsWritten()) {
21410b57cec5SDimitry Andric     // The name of this function was written as a template-id.
21420b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Previous, DC);
21430b57cec5SDimitry Andric 
21440b57cec5SDimitry Andric     // Instantiate the explicit template arguments.
21450b57cec5SDimitry Andric     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
21460b57cec5SDimitry Andric                                           Info->getRAngleLoc());
21470b57cec5SDimitry Andric     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
21480b57cec5SDimitry Andric                       ExplicitArgs, TemplateArgs))
21490b57cec5SDimitry Andric       return nullptr;
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
21520b57cec5SDimitry Andric                                                     &ExplicitArgs,
21530b57cec5SDimitry Andric                                                     Previous))
21540b57cec5SDimitry Andric       Function->setInvalidDecl();
21550b57cec5SDimitry Andric 
21560b57cec5SDimitry Andric     IsExplicitSpecialization = true;
21570b57cec5SDimitry Andric   } else if (TemplateParams || !FunctionTemplate) {
21580b57cec5SDimitry Andric     // Look only into the namespace where the friend would be declared to
21590b57cec5SDimitry Andric     // find a previous declaration. This is the innermost enclosing namespace,
21600b57cec5SDimitry Andric     // as described in ActOnFriendFunctionDecl.
21615ffd83dbSDimitry Andric     SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric     // In C++, the previous declaration we find might be a tag type
21640b57cec5SDimitry Andric     // (class or enum). In this case, the new declaration will hide the
21650b57cec5SDimitry Andric     // tag type. Note that this does does not apply if we're declaring a
21660b57cec5SDimitry Andric     // typedef (C++ [dcl.typedef]p4).
21670b57cec5SDimitry Andric     if (Previous.isSingleTagDecl())
21680b57cec5SDimitry Andric       Previous.clear();
216916d6b3b3SDimitry Andric 
217016d6b3b3SDimitry Andric     // Filter out previous declarations that don't match the scope. The only
217116d6b3b3SDimitry Andric     // effect this has is to remove declarations found in inline namespaces
217216d6b3b3SDimitry Andric     // for friend declarations with unqualified names.
217316d6b3b3SDimitry Andric     SemaRef.FilterLookupForScope(Previous, DC, /*Scope*/ nullptr,
217416d6b3b3SDimitry Andric                                  /*ConsiderLinkage*/ true,
217516d6b3b3SDimitry Andric                                  QualifierLoc.hasQualifier());
21760b57cec5SDimitry Andric   }
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric   SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
21790b57cec5SDimitry Andric                                    IsExplicitSpecialization);
21800b57cec5SDimitry Andric 
21810b57cec5SDimitry Andric   // Check the template parameter list against the previous declaration. The
21820b57cec5SDimitry Andric   // goal here is to pick up default arguments added since the friend was
21830b57cec5SDimitry Andric   // declared; we know the template parameter lists match, since otherwise
21840b57cec5SDimitry Andric   // we would not have picked this template as the previous declaration.
2185*e8d8bef9SDimitry Andric   if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
21860b57cec5SDimitry Andric     SemaRef.CheckTemplateParameterList(
21870b57cec5SDimitry Andric         TemplateParams,
21880b57cec5SDimitry Andric         FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
21890b57cec5SDimitry Andric         Function->isThisDeclarationADefinition()
21900b57cec5SDimitry Andric             ? Sema::TPC_FriendFunctionTemplateDefinition
21910b57cec5SDimitry Andric             : Sema::TPC_FriendFunctionTemplate);
21920b57cec5SDimitry Andric   }
2193*e8d8bef9SDimitry Andric 
2194*e8d8bef9SDimitry Andric   // If we're introducing a friend definition after the first use, trigger
2195*e8d8bef9SDimitry Andric   // instantiation.
2196*e8d8bef9SDimitry Andric   // FIXME: If this is a friend function template definition, we should check
2197*e8d8bef9SDimitry Andric   // to see if any specializations have been used.
2198*e8d8bef9SDimitry Andric   if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2199*e8d8bef9SDimitry Andric     if (MemberSpecializationInfo *MSInfo =
2200*e8d8bef9SDimitry Andric             Function->getMemberSpecializationInfo()) {
2201*e8d8bef9SDimitry Andric       if (MSInfo->getPointOfInstantiation().isInvalid()) {
2202*e8d8bef9SDimitry Andric         SourceLocation Loc = D->getLocation(); // FIXME
2203*e8d8bef9SDimitry Andric         MSInfo->setPointOfInstantiation(Loc);
2204*e8d8bef9SDimitry Andric         SemaRef.PendingLocalImplicitInstantiations.push_back(
2205*e8d8bef9SDimitry Andric             std::make_pair(Function, Loc));
2206*e8d8bef9SDimitry Andric       }
2207*e8d8bef9SDimitry Andric     }
22080b57cec5SDimitry Andric   }
22090b57cec5SDimitry Andric 
2210480093f4SDimitry Andric   if (D->isExplicitlyDefaulted()) {
2211480093f4SDimitry Andric     if (SubstDefaultedFunction(Function, D))
2212480093f4SDimitry Andric       return nullptr;
2213480093f4SDimitry Andric   }
2214480093f4SDimitry Andric   if (D->isDeleted())
2215480093f4SDimitry Andric     SemaRef.SetDeclDeleted(Function, D->getLocation());
2216480093f4SDimitry Andric 
2217*e8d8bef9SDimitry Andric   NamedDecl *PrincipalDecl =
2218*e8d8bef9SDimitry Andric       (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2219*e8d8bef9SDimitry Andric 
2220*e8d8bef9SDimitry Andric   // If this declaration lives in a different context from its lexical context,
2221*e8d8bef9SDimitry Andric   // add it to the corresponding lookup table.
2222*e8d8bef9SDimitry Andric   if (isFriend ||
2223*e8d8bef9SDimitry Andric       (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
22240b57cec5SDimitry Andric     DC->makeDeclVisibleInContext(PrincipalDecl);
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric   if (Function->isOverloadedOperator() && !DC->isRecord() &&
22270b57cec5SDimitry Andric       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
22280b57cec5SDimitry Andric     PrincipalDecl->setNonMemberOperator();
22290b57cec5SDimitry Andric 
22300b57cec5SDimitry Andric   return Function;
22310b57cec5SDimitry Andric }
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
22340b57cec5SDimitry Andric     CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2235480093f4SDimitry Andric     Optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs,
2236480093f4SDimitry Andric     RewriteKind FunctionRewriteKind) {
22370b57cec5SDimitry Andric   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
22380b57cec5SDimitry Andric   if (FunctionTemplate && !TemplateParams) {
22390b57cec5SDimitry Andric     // We are creating a function template specialization from a function
22400b57cec5SDimitry Andric     // template. Check whether there is already a function template
22410b57cec5SDimitry Andric     // specialization for this particular set of template arguments.
22420b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
22430b57cec5SDimitry Andric 
22440b57cec5SDimitry Andric     void *InsertPos = nullptr;
22450b57cec5SDimitry Andric     FunctionDecl *SpecFunc
22460b57cec5SDimitry Andric       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
22470b57cec5SDimitry Andric 
22480b57cec5SDimitry Andric     // If we already have a function template specialization, return it.
22490b57cec5SDimitry Andric     if (SpecFunc)
22500b57cec5SDimitry Andric       return SpecFunc;
22510b57cec5SDimitry Andric   }
22520b57cec5SDimitry Andric 
22530b57cec5SDimitry Andric   bool isFriend;
22540b57cec5SDimitry Andric   if (FunctionTemplate)
22550b57cec5SDimitry Andric     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
22560b57cec5SDimitry Andric   else
22570b57cec5SDimitry Andric     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric   bool MergeWithParentScope = (TemplateParams != nullptr) ||
22600b57cec5SDimitry Andric     !(isa<Decl>(Owner) &&
22610b57cec5SDimitry Andric       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
22620b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric   // Instantiate enclosing template arguments for friends.
22650b57cec5SDimitry Andric   SmallVector<TemplateParameterList *, 4> TempParamLists;
22660b57cec5SDimitry Andric   unsigned NumTempParamLists = 0;
22670b57cec5SDimitry Andric   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
22680b57cec5SDimitry Andric     TempParamLists.resize(NumTempParamLists);
22690b57cec5SDimitry Andric     for (unsigned I = 0; I != NumTempParamLists; ++I) {
22700b57cec5SDimitry Andric       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
22710b57cec5SDimitry Andric       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
22720b57cec5SDimitry Andric       if (!InstParams)
22730b57cec5SDimitry Andric         return nullptr;
22740b57cec5SDimitry Andric       TempParamLists[I] = InstParams;
22750b57cec5SDimitry Andric     }
22760b57cec5SDimitry Andric   }
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric   ExplicitSpecifier InstantiatedExplicitSpecifier =
22790b57cec5SDimitry Andric       instantiateExplicitSpecifier(SemaRef, TemplateArgs,
22800b57cec5SDimitry Andric                                    ExplicitSpecifier::getFromDecl(D), D);
22810b57cec5SDimitry Andric   if (InstantiatedExplicitSpecifier.isInvalid())
22820b57cec5SDimitry Andric     return nullptr;
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric   SmallVector<ParmVarDecl *, 4> Params;
22850b57cec5SDimitry Andric   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
22860b57cec5SDimitry Andric   if (!TInfo)
22870b57cec5SDimitry Andric     return nullptr;
22880b57cec5SDimitry Andric   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
22890b57cec5SDimitry Andric 
229013138422SDimitry Andric   if (TemplateParams && TemplateParams->size()) {
229113138422SDimitry Andric     auto *LastParam =
229213138422SDimitry Andric         dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
229313138422SDimitry Andric     if (LastParam && LastParam->isImplicit() &&
229413138422SDimitry Andric         LastParam->hasTypeConstraint()) {
229513138422SDimitry Andric       // In abbreviated templates, the type-constraints of invented template
229613138422SDimitry Andric       // type parameters are instantiated with the function type, invalidating
229713138422SDimitry Andric       // the TemplateParameterList which relied on the template type parameter
229813138422SDimitry Andric       // not having a type constraint. Recreate the TemplateParameterList with
229913138422SDimitry Andric       // the updated parameter list.
230013138422SDimitry Andric       TemplateParams = TemplateParameterList::Create(
230113138422SDimitry Andric           SemaRef.Context, TemplateParams->getTemplateLoc(),
230213138422SDimitry Andric           TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
230313138422SDimitry Andric           TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
230413138422SDimitry Andric     }
230513138422SDimitry Andric   }
230613138422SDimitry Andric 
23070b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
23080b57cec5SDimitry Andric   if (QualifierLoc) {
23090b57cec5SDimitry Andric     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
23100b57cec5SDimitry Andric                                                  TemplateArgs);
23110b57cec5SDimitry Andric     if (!QualifierLoc)
23120b57cec5SDimitry Andric       return nullptr;
23130b57cec5SDimitry Andric   }
23140b57cec5SDimitry Andric 
2315480093f4SDimitry Andric   // FIXME: Concepts: Do not substitute into constraint expressions
2316480093f4SDimitry Andric   Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2317480093f4SDimitry Andric   if (TrailingRequiresClause) {
231855e4f9d5SDimitry Andric     EnterExpressionEvaluationContext ConstantEvaluated(
231955e4f9d5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
232013138422SDimitry Andric     auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
232113138422SDimitry Andric     Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext,
232213138422SDimitry Andric                                      D->getMethodQualifiers(), ThisContext);
2323480093f4SDimitry Andric     ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
2324480093f4SDimitry Andric                                            TemplateArgs);
2325480093f4SDimitry Andric     if (SubstRC.isInvalid())
2326480093f4SDimitry Andric       return nullptr;
2327480093f4SDimitry Andric     TrailingRequiresClause = SubstRC.get();
2328480093f4SDimitry Andric     if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
2329480093f4SDimitry Andric       return nullptr;
2330480093f4SDimitry Andric   }
2331480093f4SDimitry Andric 
23320b57cec5SDimitry Andric   DeclContext *DC = Owner;
23330b57cec5SDimitry Andric   if (isFriend) {
23340b57cec5SDimitry Andric     if (QualifierLoc) {
23350b57cec5SDimitry Andric       CXXScopeSpec SS;
23360b57cec5SDimitry Andric       SS.Adopt(QualifierLoc);
23370b57cec5SDimitry Andric       DC = SemaRef.computeDeclContext(SS);
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
23400b57cec5SDimitry Andric         return nullptr;
23410b57cec5SDimitry Andric     } else {
23420b57cec5SDimitry Andric       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
23430b57cec5SDimitry Andric                                            D->getDeclContext(),
23440b57cec5SDimitry Andric                                            TemplateArgs);
23450b57cec5SDimitry Andric     }
23460b57cec5SDimitry Andric     if (!DC) return nullptr;
23470b57cec5SDimitry Andric   }
23480b57cec5SDimitry Andric 
2349480093f4SDimitry Andric   DeclarationNameInfo NameInfo
2350480093f4SDimitry Andric     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2351480093f4SDimitry Andric 
2352480093f4SDimitry Andric   if (FunctionRewriteKind != RewriteKind::None)
2353480093f4SDimitry Andric     adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2354480093f4SDimitry Andric 
23550b57cec5SDimitry Andric   // Build the instantiated method declaration.
23560b57cec5SDimitry Andric   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
23570b57cec5SDimitry Andric   CXXMethodDecl *Method = nullptr;
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric   SourceLocation StartLoc = D->getInnerLocStart();
23600b57cec5SDimitry Andric   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
23610b57cec5SDimitry Andric     Method = CXXConstructorDecl::Create(
23620b57cec5SDimitry Andric         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
23630b57cec5SDimitry Andric         InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
2364480093f4SDimitry Andric         Constructor->getConstexprKind(), InheritedConstructor(),
2365480093f4SDimitry Andric         TrailingRequiresClause);
23660b57cec5SDimitry Andric     Method->setRangeEnd(Constructor->getEndLoc());
23670b57cec5SDimitry Andric   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2368a7dea167SDimitry Andric     Method = CXXDestructorDecl::Create(
2369a7dea167SDimitry Andric         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2370480093f4SDimitry Andric         Destructor->isInlineSpecified(), false, Destructor->getConstexprKind(),
2371480093f4SDimitry Andric         TrailingRequiresClause);
23720b57cec5SDimitry Andric     Method->setRangeEnd(Destructor->getEndLoc());
23730b57cec5SDimitry Andric   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
23740b57cec5SDimitry Andric     Method = CXXConversionDecl::Create(
23750b57cec5SDimitry Andric         SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
23760b57cec5SDimitry Andric         Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
2377480093f4SDimitry Andric         Conversion->getConstexprKind(), Conversion->getEndLoc(),
2378480093f4SDimitry Andric         TrailingRequiresClause);
23790b57cec5SDimitry Andric   } else {
23800b57cec5SDimitry Andric     StorageClass SC = D->isStatic() ? SC_Static : SC_None;
23810b57cec5SDimitry Andric     Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
23820b57cec5SDimitry Andric                                    T, TInfo, SC, D->isInlineSpecified(),
2383480093f4SDimitry Andric                                    D->getConstexprKind(), D->getEndLoc(),
2384480093f4SDimitry Andric                                    TrailingRequiresClause);
23850b57cec5SDimitry Andric   }
23860b57cec5SDimitry Andric 
23870b57cec5SDimitry Andric   if (D->isInlined())
23880b57cec5SDimitry Andric     Method->setImplicitlyInline();
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   if (QualifierLoc)
23910b57cec5SDimitry Andric     Method->setQualifierInfo(QualifierLoc);
23920b57cec5SDimitry Andric 
23930b57cec5SDimitry Andric   if (TemplateParams) {
23940b57cec5SDimitry Andric     // Our resulting instantiation is actually a function template, since we
23950b57cec5SDimitry Andric     // are substituting only the outer template parameters. For example, given
23960b57cec5SDimitry Andric     //
23970b57cec5SDimitry Andric     //   template<typename T>
23980b57cec5SDimitry Andric     //   struct X {
23990b57cec5SDimitry Andric     //     template<typename U> void f(T, U);
24000b57cec5SDimitry Andric     //   };
24010b57cec5SDimitry Andric     //
24020b57cec5SDimitry Andric     //   X<int> x;
24030b57cec5SDimitry Andric     //
24040b57cec5SDimitry Andric     // We are instantiating the member template "f" within X<int>, which means
24050b57cec5SDimitry Andric     // substituting int for T, but leaving "f" as a member function template.
24060b57cec5SDimitry Andric     // Build the function template itself.
24070b57cec5SDimitry Andric     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
24080b57cec5SDimitry Andric                                                     Method->getLocation(),
24090b57cec5SDimitry Andric                                                     Method->getDeclName(),
24100b57cec5SDimitry Andric                                                     TemplateParams, Method);
24110b57cec5SDimitry Andric     if (isFriend) {
24120b57cec5SDimitry Andric       FunctionTemplate->setLexicalDeclContext(Owner);
24130b57cec5SDimitry Andric       FunctionTemplate->setObjectOfFriendDecl();
24140b57cec5SDimitry Andric     } else if (D->isOutOfLine())
24150b57cec5SDimitry Andric       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
24160b57cec5SDimitry Andric     Method->setDescribedFunctionTemplate(FunctionTemplate);
24170b57cec5SDimitry Andric   } else if (FunctionTemplate) {
24180b57cec5SDimitry Andric     // Record this function template specialization.
24190b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
24200b57cec5SDimitry Andric     Method->setFunctionTemplateSpecialization(FunctionTemplate,
24210b57cec5SDimitry Andric                          TemplateArgumentList::CreateCopy(SemaRef.Context,
24220b57cec5SDimitry Andric                                                           Innermost),
24230b57cec5SDimitry Andric                                               /*InsertPos=*/nullptr);
24240b57cec5SDimitry Andric   } else if (!isFriend) {
24250b57cec5SDimitry Andric     // Record that this is an instantiation of a member function.
24260b57cec5SDimitry Andric     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
24270b57cec5SDimitry Andric   }
24280b57cec5SDimitry Andric 
24290b57cec5SDimitry Andric   // If we are instantiating a member function defined
24300b57cec5SDimitry Andric   // out-of-line, the instantiation will have the same lexical
24310b57cec5SDimitry Andric   // context (which will be a namespace scope) as the template.
24320b57cec5SDimitry Andric   if (isFriend) {
24330b57cec5SDimitry Andric     if (NumTempParamLists)
24340b57cec5SDimitry Andric       Method->setTemplateParameterListsInfo(
24350b57cec5SDimitry Andric           SemaRef.Context,
24360b57cec5SDimitry Andric           llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
24370b57cec5SDimitry Andric 
24380b57cec5SDimitry Andric     Method->setLexicalDeclContext(Owner);
24390b57cec5SDimitry Andric     Method->setObjectOfFriendDecl();
24400b57cec5SDimitry Andric   } else if (D->isOutOfLine())
24410b57cec5SDimitry Andric     Method->setLexicalDeclContext(D->getLexicalDeclContext());
24420b57cec5SDimitry Andric 
24430b57cec5SDimitry Andric   // Attach the parameters
24440b57cec5SDimitry Andric   for (unsigned P = 0; P < Params.size(); ++P)
24450b57cec5SDimitry Andric     Params[P]->setOwningFunction(Method);
24460b57cec5SDimitry Andric   Method->setParams(Params);
24470b57cec5SDimitry Andric 
24480b57cec5SDimitry Andric   if (InitMethodInstantiation(Method, D))
24490b57cec5SDimitry Andric     Method->setInvalidDecl();
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
24520b57cec5SDimitry Andric                         Sema::ForExternalRedeclaration);
24530b57cec5SDimitry Andric 
24540b57cec5SDimitry Andric   bool IsExplicitSpecialization = false;
24550b57cec5SDimitry Andric 
24560b57cec5SDimitry Andric   // If the name of this function was written as a template-id, instantiate
24570b57cec5SDimitry Andric   // the explicit template arguments.
24580b57cec5SDimitry Andric   if (DependentFunctionTemplateSpecializationInfo *Info
24590b57cec5SDimitry Andric         = D->getDependentSpecializationInfo()) {
24600b57cec5SDimitry Andric     assert(isFriend && "non-friend has dependent specialization info?");
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric     // Instantiate the explicit template arguments.
24630b57cec5SDimitry Andric     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
24640b57cec5SDimitry Andric                                           Info->getRAngleLoc());
24650b57cec5SDimitry Andric     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
24660b57cec5SDimitry Andric                       ExplicitArgs, TemplateArgs))
24670b57cec5SDimitry Andric       return nullptr;
24680b57cec5SDimitry Andric 
24690b57cec5SDimitry Andric     // Map the candidate templates to their instantiations.
24700b57cec5SDimitry Andric     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
24710b57cec5SDimitry Andric       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
24720b57cec5SDimitry Andric                                                 Info->getTemplate(I),
24730b57cec5SDimitry Andric                                                 TemplateArgs);
24740b57cec5SDimitry Andric       if (!Temp) return nullptr;
24750b57cec5SDimitry Andric 
24760b57cec5SDimitry Andric       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
24770b57cec5SDimitry Andric     }
24780b57cec5SDimitry Andric 
24790b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Method,
24800b57cec5SDimitry Andric                                                     &ExplicitArgs,
24810b57cec5SDimitry Andric                                                     Previous))
24820b57cec5SDimitry Andric       Method->setInvalidDecl();
24830b57cec5SDimitry Andric 
24840b57cec5SDimitry Andric     IsExplicitSpecialization = true;
24850b57cec5SDimitry Andric   } else if (const ASTTemplateArgumentListInfo *Info =
24860b57cec5SDimitry Andric                  ClassScopeSpecializationArgs.getValueOr(
24870b57cec5SDimitry Andric                      D->getTemplateSpecializationArgsAsWritten())) {
24880b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Previous, DC);
24890b57cec5SDimitry Andric 
24900b57cec5SDimitry Andric     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
24910b57cec5SDimitry Andric                                           Info->getRAngleLoc());
24920b57cec5SDimitry Andric     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
24930b57cec5SDimitry Andric                       ExplicitArgs, TemplateArgs))
24940b57cec5SDimitry Andric       return nullptr;
24950b57cec5SDimitry Andric 
24960b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Method,
24970b57cec5SDimitry Andric                                                     &ExplicitArgs,
24980b57cec5SDimitry Andric                                                     Previous))
24990b57cec5SDimitry Andric       Method->setInvalidDecl();
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric     IsExplicitSpecialization = true;
25020b57cec5SDimitry Andric   } else if (ClassScopeSpecializationArgs) {
25030b57cec5SDimitry Andric     // Class-scope explicit specialization written without explicit template
25040b57cec5SDimitry Andric     // arguments.
25050b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Previous, DC);
25060b57cec5SDimitry Andric     if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
25070b57cec5SDimitry Andric       Method->setInvalidDecl();
25080b57cec5SDimitry Andric 
25090b57cec5SDimitry Andric     IsExplicitSpecialization = true;
25100b57cec5SDimitry Andric   } else if (!FunctionTemplate || TemplateParams || isFriend) {
25110b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Previous, Record);
25120b57cec5SDimitry Andric 
25130b57cec5SDimitry Andric     // In C++, the previous declaration we find might be a tag type
25140b57cec5SDimitry Andric     // (class or enum). In this case, the new declaration will hide the
25150b57cec5SDimitry Andric     // tag type. Note that this does does not apply if we're declaring a
25160b57cec5SDimitry Andric     // typedef (C++ [dcl.typedef]p4).
25170b57cec5SDimitry Andric     if (Previous.isSingleTagDecl())
25180b57cec5SDimitry Andric       Previous.clear();
25190b57cec5SDimitry Andric   }
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric   SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
25220b57cec5SDimitry Andric                                    IsExplicitSpecialization);
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric   if (D->isPure())
25250b57cec5SDimitry Andric     SemaRef.CheckPureMethod(Method, SourceRange());
25260b57cec5SDimitry Andric 
25270b57cec5SDimitry Andric   // Propagate access.  For a non-friend declaration, the access is
25280b57cec5SDimitry Andric   // whatever we're propagating from.  For a friend, it should be the
25290b57cec5SDimitry Andric   // previous declaration we just found.
25300b57cec5SDimitry Andric   if (isFriend && Method->getPreviousDecl())
25310b57cec5SDimitry Andric     Method->setAccess(Method->getPreviousDecl()->getAccess());
25320b57cec5SDimitry Andric   else
25330b57cec5SDimitry Andric     Method->setAccess(D->getAccess());
25340b57cec5SDimitry Andric   if (FunctionTemplate)
25350b57cec5SDimitry Andric     FunctionTemplate->setAccess(Method->getAccess());
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric   SemaRef.CheckOverrideControl(Method);
25380b57cec5SDimitry Andric 
25390b57cec5SDimitry Andric   // If a function is defined as defaulted or deleted, mark it as such now.
2540480093f4SDimitry Andric   if (D->isExplicitlyDefaulted()) {
2541480093f4SDimitry Andric     if (SubstDefaultedFunction(Method, D))
2542480093f4SDimitry Andric       return nullptr;
2543480093f4SDimitry Andric   }
25440b57cec5SDimitry Andric   if (D->isDeletedAsWritten())
25450b57cec5SDimitry Andric     SemaRef.SetDeclDeleted(Method, Method->getLocation());
25460b57cec5SDimitry Andric 
25470b57cec5SDimitry Andric   // If this is an explicit specialization, mark the implicitly-instantiated
25480b57cec5SDimitry Andric   // template specialization as being an explicit specialization too.
25490b57cec5SDimitry Andric   // FIXME: Is this necessary?
25500b57cec5SDimitry Andric   if (IsExplicitSpecialization && !isFriend)
25510b57cec5SDimitry Andric     SemaRef.CompleteMemberSpecialization(Method, Previous);
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric   // If there's a function template, let our caller handle it.
25540b57cec5SDimitry Andric   if (FunctionTemplate) {
25550b57cec5SDimitry Andric     // do nothing
25560b57cec5SDimitry Andric 
25570b57cec5SDimitry Andric   // Don't hide a (potentially) valid declaration with an invalid one.
25580b57cec5SDimitry Andric   } else if (Method->isInvalidDecl() && !Previous.empty()) {
25590b57cec5SDimitry Andric     // do nothing
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric   // Otherwise, check access to friends and make them visible.
25620b57cec5SDimitry Andric   } else if (isFriend) {
25630b57cec5SDimitry Andric     // We only need to re-check access for methods which we didn't
25640b57cec5SDimitry Andric     // manage to match during parsing.
25650b57cec5SDimitry Andric     if (!D->getPreviousDecl())
25660b57cec5SDimitry Andric       SemaRef.CheckFriendAccess(Method);
25670b57cec5SDimitry Andric 
25680b57cec5SDimitry Andric     Record->makeDeclVisibleInContext(Method);
25690b57cec5SDimitry Andric 
25700b57cec5SDimitry Andric   // Otherwise, add the declaration.  We don't need to do this for
25710b57cec5SDimitry Andric   // class-scope specializations because we'll have matched them with
25720b57cec5SDimitry Andric   // the appropriate template.
25730b57cec5SDimitry Andric   } else {
25740b57cec5SDimitry Andric     Owner->addDecl(Method);
25750b57cec5SDimitry Andric   }
25760b57cec5SDimitry Andric 
25770b57cec5SDimitry Andric   // PR17480: Honor the used attribute to instantiate member function
25780b57cec5SDimitry Andric   // definitions
25790b57cec5SDimitry Andric   if (Method->hasAttr<UsedAttr>()) {
25800b57cec5SDimitry Andric     if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
25810b57cec5SDimitry Andric       SourceLocation Loc;
25820b57cec5SDimitry Andric       if (const MemberSpecializationInfo *MSInfo =
25830b57cec5SDimitry Andric               A->getMemberSpecializationInfo())
25840b57cec5SDimitry Andric         Loc = MSInfo->getPointOfInstantiation();
25850b57cec5SDimitry Andric       else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
25860b57cec5SDimitry Andric         Loc = Spec->getPointOfInstantiation();
25870b57cec5SDimitry Andric       SemaRef.MarkFunctionReferenced(Loc, Method);
25880b57cec5SDimitry Andric     }
25890b57cec5SDimitry Andric   }
25900b57cec5SDimitry Andric 
25910b57cec5SDimitry Andric   return Method;
25920b57cec5SDimitry Andric }
25930b57cec5SDimitry Andric 
25940b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
25950b57cec5SDimitry Andric   return VisitCXXMethodDecl(D);
25960b57cec5SDimitry Andric }
25970b57cec5SDimitry Andric 
25980b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
25990b57cec5SDimitry Andric   return VisitCXXMethodDecl(D);
26000b57cec5SDimitry Andric }
26010b57cec5SDimitry Andric 
26020b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
26030b57cec5SDimitry Andric   return VisitCXXMethodDecl(D);
26040b57cec5SDimitry Andric }
26050b57cec5SDimitry Andric 
26060b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
26070b57cec5SDimitry Andric   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
26080b57cec5SDimitry Andric                                   /*ExpectParameterPack=*/ false);
26090b57cec5SDimitry Andric }
26100b57cec5SDimitry Andric 
26110b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
26120b57cec5SDimitry Andric                                                     TemplateTypeParmDecl *D) {
26130b57cec5SDimitry Andric   // TODO: don't always clone when decls are refcounted.
26140b57cec5SDimitry Andric   assert(D->getTypeForDecl()->isTemplateTypeParmType());
26150b57cec5SDimitry Andric 
2616480093f4SDimitry Andric   Optional<unsigned> NumExpanded;
2617480093f4SDimitry Andric 
2618480093f4SDimitry Andric   if (const TypeConstraint *TC = D->getTypeConstraint()) {
2619480093f4SDimitry Andric     if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2620480093f4SDimitry Andric       assert(TC->getTemplateArgsAsWritten() &&
2621480093f4SDimitry Andric              "type parameter can only be an expansion when explicit arguments "
2622480093f4SDimitry Andric              "are specified");
2623480093f4SDimitry Andric       // The template type parameter pack's type is a pack expansion of types.
2624480093f4SDimitry Andric       // Determine whether we need to expand this parameter pack into separate
2625480093f4SDimitry Andric       // types.
2626480093f4SDimitry Andric       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2627480093f4SDimitry Andric       for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2628480093f4SDimitry Andric         SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2629480093f4SDimitry Andric 
2630480093f4SDimitry Andric       // Determine whether the set of unexpanded parameter packs can and should
2631480093f4SDimitry Andric       // be expanded.
2632480093f4SDimitry Andric       bool Expand = true;
2633480093f4SDimitry Andric       bool RetainExpansion = false;
2634480093f4SDimitry Andric       if (SemaRef.CheckParameterPacksForExpansion(
2635480093f4SDimitry Andric               cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2636480093f4SDimitry Andric                   ->getEllipsisLoc(),
2637480093f4SDimitry Andric               SourceRange(TC->getConceptNameLoc(),
2638480093f4SDimitry Andric                           TC->hasExplicitTemplateArgs() ?
2639480093f4SDimitry Andric                           TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2640480093f4SDimitry Andric                           TC->getConceptNameInfo().getEndLoc()),
2641480093f4SDimitry Andric               Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2642480093f4SDimitry Andric         return nullptr;
2643480093f4SDimitry Andric     }
2644480093f4SDimitry Andric   }
2645480093f4SDimitry Andric 
26460b57cec5SDimitry Andric   TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
26470b57cec5SDimitry Andric       SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
26480b57cec5SDimitry Andric       D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2649480093f4SDimitry Andric       D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2650480093f4SDimitry Andric       D->hasTypeConstraint(), NumExpanded);
2651480093f4SDimitry Andric 
26520b57cec5SDimitry Andric   Inst->setAccess(AS_public);
2653a7dea167SDimitry Andric   Inst->setImplicit(D->isImplicit());
2654480093f4SDimitry Andric   if (auto *TC = D->getTypeConstraint()) {
265513138422SDimitry Andric     if (!D->isImplicit()) {
265613138422SDimitry Andric       // Invented template parameter type constraints will be instantiated with
265713138422SDimitry Andric       // the corresponding auto-typed parameter as it might reference other
265813138422SDimitry Andric       // parameters.
265913138422SDimitry Andric 
2660480093f4SDimitry Andric       // TODO: Concepts: do not instantiate the constraint (delayed constraint
2661480093f4SDimitry Andric       // substitution)
2662480093f4SDimitry Andric       const ASTTemplateArgumentListInfo *TemplArgInfo
2663480093f4SDimitry Andric         = TC->getTemplateArgsAsWritten();
2664480093f4SDimitry Andric       TemplateArgumentListInfo InstArgs;
26650b57cec5SDimitry Andric 
2666480093f4SDimitry Andric       if (TemplArgInfo) {
2667480093f4SDimitry Andric         InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2668480093f4SDimitry Andric         InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2669480093f4SDimitry Andric         if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2670480093f4SDimitry Andric                           TemplArgInfo->NumTemplateArgs,
2671480093f4SDimitry Andric                           InstArgs, TemplateArgs))
2672480093f4SDimitry Andric           return nullptr;
2673480093f4SDimitry Andric       }
2674480093f4SDimitry Andric       if (SemaRef.AttachTypeConstraint(
2675480093f4SDimitry Andric               TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2676480093f4SDimitry Andric               TC->getNamedConcept(), &InstArgs, Inst,
2677480093f4SDimitry Andric               D->isParameterPack()
2678480093f4SDimitry Andric                   ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2679480093f4SDimitry Andric                       ->getEllipsisLoc()
2680480093f4SDimitry Andric                   : SourceLocation()))
2681480093f4SDimitry Andric         return nullptr;
2682480093f4SDimitry Andric     }
268313138422SDimitry Andric   }
26840b57cec5SDimitry Andric   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
26850b57cec5SDimitry Andric     TypeSourceInfo *InstantiatedDefaultArg =
26860b57cec5SDimitry Andric         SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
26870b57cec5SDimitry Andric                           D->getDefaultArgumentLoc(), D->getDeclName());
26880b57cec5SDimitry Andric     if (InstantiatedDefaultArg)
26890b57cec5SDimitry Andric       Inst->setDefaultArgument(InstantiatedDefaultArg);
26900b57cec5SDimitry Andric   }
26910b57cec5SDimitry Andric 
26920b57cec5SDimitry Andric   // Introduce this template parameter's instantiation into the instantiation
26930b57cec5SDimitry Andric   // scope.
26940b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric   return Inst;
26970b57cec5SDimitry Andric }
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
27000b57cec5SDimitry Andric                                                  NonTypeTemplateParmDecl *D) {
27010b57cec5SDimitry Andric   // Substitute into the type of the non-type template parameter.
27020b57cec5SDimitry Andric   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
27030b57cec5SDimitry Andric   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
27040b57cec5SDimitry Andric   SmallVector<QualType, 4> ExpandedParameterPackTypes;
27050b57cec5SDimitry Andric   bool IsExpandedParameterPack = false;
27060b57cec5SDimitry Andric   TypeSourceInfo *DI;
27070b57cec5SDimitry Andric   QualType T;
27080b57cec5SDimitry Andric   bool Invalid = false;
27090b57cec5SDimitry Andric 
27100b57cec5SDimitry Andric   if (D->isExpandedParameterPack()) {
27110b57cec5SDimitry Andric     // The non-type template parameter pack is an already-expanded pack
27120b57cec5SDimitry Andric     // expansion of types. Substitute into each of the expanded types.
27130b57cec5SDimitry Andric     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
27140b57cec5SDimitry Andric     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
27150b57cec5SDimitry Andric     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
27160b57cec5SDimitry Andric       TypeSourceInfo *NewDI =
27170b57cec5SDimitry Andric           SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
27180b57cec5SDimitry Andric                             D->getLocation(), D->getDeclName());
27190b57cec5SDimitry Andric       if (!NewDI)
27200b57cec5SDimitry Andric         return nullptr;
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric       QualType NewT =
27230b57cec5SDimitry Andric           SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
27240b57cec5SDimitry Andric       if (NewT.isNull())
27250b57cec5SDimitry Andric         return nullptr;
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
27280b57cec5SDimitry Andric       ExpandedParameterPackTypes.push_back(NewT);
27290b57cec5SDimitry Andric     }
27300b57cec5SDimitry Andric 
27310b57cec5SDimitry Andric     IsExpandedParameterPack = true;
27320b57cec5SDimitry Andric     DI = D->getTypeSourceInfo();
27330b57cec5SDimitry Andric     T = DI->getType();
27340b57cec5SDimitry Andric   } else if (D->isPackExpansion()) {
27350b57cec5SDimitry Andric     // The non-type template parameter pack's type is a pack expansion of types.
27360b57cec5SDimitry Andric     // Determine whether we need to expand this parameter pack into separate
27370b57cec5SDimitry Andric     // types.
27380b57cec5SDimitry Andric     PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
27390b57cec5SDimitry Andric     TypeLoc Pattern = Expansion.getPatternLoc();
27400b57cec5SDimitry Andric     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
27410b57cec5SDimitry Andric     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
27420b57cec5SDimitry Andric 
27430b57cec5SDimitry Andric     // Determine whether the set of unexpanded parameter packs can and should
27440b57cec5SDimitry Andric     // be expanded.
27450b57cec5SDimitry Andric     bool Expand = true;
27460b57cec5SDimitry Andric     bool RetainExpansion = false;
27470b57cec5SDimitry Andric     Optional<unsigned> OrigNumExpansions
27480b57cec5SDimitry Andric       = Expansion.getTypePtr()->getNumExpansions();
27490b57cec5SDimitry Andric     Optional<unsigned> NumExpansions = OrigNumExpansions;
27500b57cec5SDimitry Andric     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
27510b57cec5SDimitry Andric                                                 Pattern.getSourceRange(),
27520b57cec5SDimitry Andric                                                 Unexpanded,
27530b57cec5SDimitry Andric                                                 TemplateArgs,
27540b57cec5SDimitry Andric                                                 Expand, RetainExpansion,
27550b57cec5SDimitry Andric                                                 NumExpansions))
27560b57cec5SDimitry Andric       return nullptr;
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric     if (Expand) {
27590b57cec5SDimitry Andric       for (unsigned I = 0; I != *NumExpansions; ++I) {
27600b57cec5SDimitry Andric         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
27610b57cec5SDimitry Andric         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
27620b57cec5SDimitry Andric                                                   D->getLocation(),
27630b57cec5SDimitry Andric                                                   D->getDeclName());
27640b57cec5SDimitry Andric         if (!NewDI)
27650b57cec5SDimitry Andric           return nullptr;
27660b57cec5SDimitry Andric 
27670b57cec5SDimitry Andric         QualType NewT =
27680b57cec5SDimitry Andric             SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
27690b57cec5SDimitry Andric         if (NewT.isNull())
27700b57cec5SDimitry Andric           return nullptr;
27710b57cec5SDimitry Andric 
27720b57cec5SDimitry Andric         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
27730b57cec5SDimitry Andric         ExpandedParameterPackTypes.push_back(NewT);
27740b57cec5SDimitry Andric       }
27750b57cec5SDimitry Andric 
27760b57cec5SDimitry Andric       // Note that we have an expanded parameter pack. The "type" of this
27770b57cec5SDimitry Andric       // expanded parameter pack is the original expansion type, but callers
27780b57cec5SDimitry Andric       // will end up using the expanded parameter pack types for type-checking.
27790b57cec5SDimitry Andric       IsExpandedParameterPack = true;
27800b57cec5SDimitry Andric       DI = D->getTypeSourceInfo();
27810b57cec5SDimitry Andric       T = DI->getType();
27820b57cec5SDimitry Andric     } else {
27830b57cec5SDimitry Andric       // We cannot fully expand the pack expansion now, so substitute into the
27840b57cec5SDimitry Andric       // pattern and create a new pack expansion type.
27850b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
27860b57cec5SDimitry Andric       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
27870b57cec5SDimitry Andric                                                      D->getLocation(),
27880b57cec5SDimitry Andric                                                      D->getDeclName());
27890b57cec5SDimitry Andric       if (!NewPattern)
27900b57cec5SDimitry Andric         return nullptr;
27910b57cec5SDimitry Andric 
27920b57cec5SDimitry Andric       SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
27930b57cec5SDimitry Andric       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
27940b57cec5SDimitry Andric                                       NumExpansions);
27950b57cec5SDimitry Andric       if (!DI)
27960b57cec5SDimitry Andric         return nullptr;
27970b57cec5SDimitry Andric 
27980b57cec5SDimitry Andric       T = DI->getType();
27990b57cec5SDimitry Andric     }
28000b57cec5SDimitry Andric   } else {
28010b57cec5SDimitry Andric     // Simple case: substitution into a parameter that is not a parameter pack.
28020b57cec5SDimitry Andric     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
28030b57cec5SDimitry Andric                            D->getLocation(), D->getDeclName());
28040b57cec5SDimitry Andric     if (!DI)
28050b57cec5SDimitry Andric       return nullptr;
28060b57cec5SDimitry Andric 
28070b57cec5SDimitry Andric     // Check that this type is acceptable for a non-type template parameter.
28080b57cec5SDimitry Andric     T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
28090b57cec5SDimitry Andric     if (T.isNull()) {
28100b57cec5SDimitry Andric       T = SemaRef.Context.IntTy;
28110b57cec5SDimitry Andric       Invalid = true;
28120b57cec5SDimitry Andric     }
28130b57cec5SDimitry Andric   }
28140b57cec5SDimitry Andric 
28150b57cec5SDimitry Andric   NonTypeTemplateParmDecl *Param;
28160b57cec5SDimitry Andric   if (IsExpandedParameterPack)
28170b57cec5SDimitry Andric     Param = NonTypeTemplateParmDecl::Create(
28180b57cec5SDimitry Andric         SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
28190b57cec5SDimitry Andric         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
28200b57cec5SDimitry Andric         D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
28210b57cec5SDimitry Andric         ExpandedParameterPackTypesAsWritten);
28220b57cec5SDimitry Andric   else
28230b57cec5SDimitry Andric     Param = NonTypeTemplateParmDecl::Create(
28240b57cec5SDimitry Andric         SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
28250b57cec5SDimitry Andric         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
28260b57cec5SDimitry Andric         D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
28270b57cec5SDimitry Andric 
282855e4f9d5SDimitry Andric   if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
282955e4f9d5SDimitry Andric     if (AutoLoc.isConstrained())
283055e4f9d5SDimitry Andric       if (SemaRef.AttachTypeConstraint(
283155e4f9d5SDimitry Andric               AutoLoc, Param,
283255e4f9d5SDimitry Andric               IsExpandedParameterPack
283355e4f9d5SDimitry Andric                 ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
283455e4f9d5SDimitry Andric                     .getEllipsisLoc()
283555e4f9d5SDimitry Andric                 : SourceLocation()))
283655e4f9d5SDimitry Andric         Invalid = true;
283755e4f9d5SDimitry Andric 
28380b57cec5SDimitry Andric   Param->setAccess(AS_public);
2839a7dea167SDimitry Andric   Param->setImplicit(D->isImplicit());
28400b57cec5SDimitry Andric   if (Invalid)
28410b57cec5SDimitry Andric     Param->setInvalidDecl();
28420b57cec5SDimitry Andric 
28430b57cec5SDimitry Andric   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
28440b57cec5SDimitry Andric     EnterExpressionEvaluationContext ConstantEvaluated(
28450b57cec5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
28460b57cec5SDimitry Andric     ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
28470b57cec5SDimitry Andric     if (!Value.isInvalid())
28480b57cec5SDimitry Andric       Param->setDefaultArgument(Value.get());
28490b57cec5SDimitry Andric   }
28500b57cec5SDimitry Andric 
28510b57cec5SDimitry Andric   // Introduce this template parameter's instantiation into the instantiation
28520b57cec5SDimitry Andric   // scope.
28530b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
28540b57cec5SDimitry Andric   return Param;
28550b57cec5SDimitry Andric }
28560b57cec5SDimitry Andric 
28570b57cec5SDimitry Andric static void collectUnexpandedParameterPacks(
28580b57cec5SDimitry Andric     Sema &S,
28590b57cec5SDimitry Andric     TemplateParameterList *Params,
28600b57cec5SDimitry Andric     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
28610b57cec5SDimitry Andric   for (const auto &P : *Params) {
28620b57cec5SDimitry Andric     if (P->isTemplateParameterPack())
28630b57cec5SDimitry Andric       continue;
28640b57cec5SDimitry Andric     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
28650b57cec5SDimitry Andric       S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
28660b57cec5SDimitry Andric                                         Unexpanded);
28670b57cec5SDimitry Andric     if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
28680b57cec5SDimitry Andric       collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
28690b57cec5SDimitry Andric                                       Unexpanded);
28700b57cec5SDimitry Andric   }
28710b57cec5SDimitry Andric }
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric Decl *
28740b57cec5SDimitry Andric TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
28750b57cec5SDimitry Andric                                                   TemplateTemplateParmDecl *D) {
28760b57cec5SDimitry Andric   // Instantiate the template parameter list of the template template parameter.
28770b57cec5SDimitry Andric   TemplateParameterList *TempParams = D->getTemplateParameters();
28780b57cec5SDimitry Andric   TemplateParameterList *InstParams;
28790b57cec5SDimitry Andric   SmallVector<TemplateParameterList*, 8> ExpandedParams;
28800b57cec5SDimitry Andric 
28810b57cec5SDimitry Andric   bool IsExpandedParameterPack = false;
28820b57cec5SDimitry Andric 
28830b57cec5SDimitry Andric   if (D->isExpandedParameterPack()) {
28840b57cec5SDimitry Andric     // The template template parameter pack is an already-expanded pack
28850b57cec5SDimitry Andric     // expansion of template parameters. Substitute into each of the expanded
28860b57cec5SDimitry Andric     // parameters.
28870b57cec5SDimitry Andric     ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
28880b57cec5SDimitry Andric     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
28890b57cec5SDimitry Andric          I != N; ++I) {
28900b57cec5SDimitry Andric       LocalInstantiationScope Scope(SemaRef);
28910b57cec5SDimitry Andric       TemplateParameterList *Expansion =
28920b57cec5SDimitry Andric         SubstTemplateParams(D->getExpansionTemplateParameters(I));
28930b57cec5SDimitry Andric       if (!Expansion)
28940b57cec5SDimitry Andric         return nullptr;
28950b57cec5SDimitry Andric       ExpandedParams.push_back(Expansion);
28960b57cec5SDimitry Andric     }
28970b57cec5SDimitry Andric 
28980b57cec5SDimitry Andric     IsExpandedParameterPack = true;
28990b57cec5SDimitry Andric     InstParams = TempParams;
29000b57cec5SDimitry Andric   } else if (D->isPackExpansion()) {
29010b57cec5SDimitry Andric     // The template template parameter pack expands to a pack of template
29020b57cec5SDimitry Andric     // template parameters. Determine whether we need to expand this parameter
29030b57cec5SDimitry Andric     // pack into separate parameters.
29040b57cec5SDimitry Andric     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
29050b57cec5SDimitry Andric     collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
29060b57cec5SDimitry Andric                                     Unexpanded);
29070b57cec5SDimitry Andric 
29080b57cec5SDimitry Andric     // Determine whether the set of unexpanded parameter packs can and should
29090b57cec5SDimitry Andric     // be expanded.
29100b57cec5SDimitry Andric     bool Expand = true;
29110b57cec5SDimitry Andric     bool RetainExpansion = false;
29120b57cec5SDimitry Andric     Optional<unsigned> NumExpansions;
29130b57cec5SDimitry Andric     if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
29140b57cec5SDimitry Andric                                                 TempParams->getSourceRange(),
29150b57cec5SDimitry Andric                                                 Unexpanded,
29160b57cec5SDimitry Andric                                                 TemplateArgs,
29170b57cec5SDimitry Andric                                                 Expand, RetainExpansion,
29180b57cec5SDimitry Andric                                                 NumExpansions))
29190b57cec5SDimitry Andric       return nullptr;
29200b57cec5SDimitry Andric 
29210b57cec5SDimitry Andric     if (Expand) {
29220b57cec5SDimitry Andric       for (unsigned I = 0; I != *NumExpansions; ++I) {
29230b57cec5SDimitry Andric         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
29240b57cec5SDimitry Andric         LocalInstantiationScope Scope(SemaRef);
29250b57cec5SDimitry Andric         TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
29260b57cec5SDimitry Andric         if (!Expansion)
29270b57cec5SDimitry Andric           return nullptr;
29280b57cec5SDimitry Andric         ExpandedParams.push_back(Expansion);
29290b57cec5SDimitry Andric       }
29300b57cec5SDimitry Andric 
29310b57cec5SDimitry Andric       // Note that we have an expanded parameter pack. The "type" of this
29320b57cec5SDimitry Andric       // expanded parameter pack is the original expansion type, but callers
29330b57cec5SDimitry Andric       // will end up using the expanded parameter pack types for type-checking.
29340b57cec5SDimitry Andric       IsExpandedParameterPack = true;
29350b57cec5SDimitry Andric       InstParams = TempParams;
29360b57cec5SDimitry Andric     } else {
29370b57cec5SDimitry Andric       // We cannot fully expand the pack expansion now, so just substitute
29380b57cec5SDimitry Andric       // into the pattern.
29390b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
29400b57cec5SDimitry Andric 
29410b57cec5SDimitry Andric       LocalInstantiationScope Scope(SemaRef);
29420b57cec5SDimitry Andric       InstParams = SubstTemplateParams(TempParams);
29430b57cec5SDimitry Andric       if (!InstParams)
29440b57cec5SDimitry Andric         return nullptr;
29450b57cec5SDimitry Andric     }
29460b57cec5SDimitry Andric   } else {
29470b57cec5SDimitry Andric     // Perform the actual substitution of template parameters within a new,
29480b57cec5SDimitry Andric     // local instantiation scope.
29490b57cec5SDimitry Andric     LocalInstantiationScope Scope(SemaRef);
29500b57cec5SDimitry Andric     InstParams = SubstTemplateParams(TempParams);
29510b57cec5SDimitry Andric     if (!InstParams)
29520b57cec5SDimitry Andric       return nullptr;
29530b57cec5SDimitry Andric   }
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric   // Build the template template parameter.
29560b57cec5SDimitry Andric   TemplateTemplateParmDecl *Param;
29570b57cec5SDimitry Andric   if (IsExpandedParameterPack)
29580b57cec5SDimitry Andric     Param = TemplateTemplateParmDecl::Create(
29590b57cec5SDimitry Andric         SemaRef.Context, Owner, D->getLocation(),
29600b57cec5SDimitry Andric         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
29610b57cec5SDimitry Andric         D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
29620b57cec5SDimitry Andric   else
29630b57cec5SDimitry Andric     Param = TemplateTemplateParmDecl::Create(
29640b57cec5SDimitry Andric         SemaRef.Context, Owner, D->getLocation(),
29650b57cec5SDimitry Andric         D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
29660b57cec5SDimitry Andric         D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
29670b57cec5SDimitry Andric   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
29680b57cec5SDimitry Andric     NestedNameSpecifierLoc QualifierLoc =
29690b57cec5SDimitry Andric         D->getDefaultArgument().getTemplateQualifierLoc();
29700b57cec5SDimitry Andric     QualifierLoc =
29710b57cec5SDimitry Andric         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
29720b57cec5SDimitry Andric     TemplateName TName = SemaRef.SubstTemplateName(
29730b57cec5SDimitry Andric         QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
29740b57cec5SDimitry Andric         D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
29750b57cec5SDimitry Andric     if (!TName.isNull())
29760b57cec5SDimitry Andric       Param->setDefaultArgument(
29770b57cec5SDimitry Andric           SemaRef.Context,
2978*e8d8bef9SDimitry Andric           TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
29790b57cec5SDimitry Andric                               D->getDefaultArgument().getTemplateQualifierLoc(),
29800b57cec5SDimitry Andric                               D->getDefaultArgument().getTemplateNameLoc()));
29810b57cec5SDimitry Andric   }
29820b57cec5SDimitry Andric   Param->setAccess(AS_public);
2983a7dea167SDimitry Andric   Param->setImplicit(D->isImplicit());
29840b57cec5SDimitry Andric 
29850b57cec5SDimitry Andric   // Introduce this template parameter's instantiation into the instantiation
29860b57cec5SDimitry Andric   // scope.
29870b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
29880b57cec5SDimitry Andric 
29890b57cec5SDimitry Andric   return Param;
29900b57cec5SDimitry Andric }
29910b57cec5SDimitry Andric 
29920b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
29930b57cec5SDimitry Andric   // Using directives are never dependent (and never contain any types or
29940b57cec5SDimitry Andric   // expressions), so they require no explicit instantiation work.
29950b57cec5SDimitry Andric 
29960b57cec5SDimitry Andric   UsingDirectiveDecl *Inst
29970b57cec5SDimitry Andric     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
29980b57cec5SDimitry Andric                                  D->getNamespaceKeyLocation(),
29990b57cec5SDimitry Andric                                  D->getQualifierLoc(),
30000b57cec5SDimitry Andric                                  D->getIdentLocation(),
30010b57cec5SDimitry Andric                                  D->getNominatedNamespace(),
30020b57cec5SDimitry Andric                                  D->getCommonAncestor());
30030b57cec5SDimitry Andric 
30040b57cec5SDimitry Andric   // Add the using directive to its declaration context
30050b57cec5SDimitry Andric   // only if this is not a function or method.
30060b57cec5SDimitry Andric   if (!Owner->isFunctionOrMethod())
30070b57cec5SDimitry Andric     Owner->addDecl(Inst);
30080b57cec5SDimitry Andric 
30090b57cec5SDimitry Andric   return Inst;
30100b57cec5SDimitry Andric }
30110b57cec5SDimitry Andric 
30120b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
30130b57cec5SDimitry Andric 
30140b57cec5SDimitry Andric   // The nested name specifier may be dependent, for example
30150b57cec5SDimitry Andric   //     template <typename T> struct t {
30160b57cec5SDimitry Andric   //       struct s1 { T f1(); };
30170b57cec5SDimitry Andric   //       struct s2 : s1 { using s1::f1; };
30180b57cec5SDimitry Andric   //     };
30190b57cec5SDimitry Andric   //     template struct t<int>;
30200b57cec5SDimitry Andric   // Here, in using s1::f1, s1 refers to t<T>::s1;
30210b57cec5SDimitry Andric   // we need to substitute for t<int>::s1.
30220b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc
30230b57cec5SDimitry Andric     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
30240b57cec5SDimitry Andric                                           TemplateArgs);
30250b57cec5SDimitry Andric   if (!QualifierLoc)
30260b57cec5SDimitry Andric     return nullptr;
30270b57cec5SDimitry Andric 
30280b57cec5SDimitry Andric   // For an inheriting constructor declaration, the name of the using
30290b57cec5SDimitry Andric   // declaration is the name of a constructor in this class, not in the
30300b57cec5SDimitry Andric   // base class.
30310b57cec5SDimitry Andric   DeclarationNameInfo NameInfo = D->getNameInfo();
30320b57cec5SDimitry Andric   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
30330b57cec5SDimitry Andric     if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
30340b57cec5SDimitry Andric       NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
30350b57cec5SDimitry Andric           SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
30360b57cec5SDimitry Andric 
30370b57cec5SDimitry Andric   // We only need to do redeclaration lookups if we're in a class
30380b57cec5SDimitry Andric   // scope (in fact, it's not really even possible in non-class
30390b57cec5SDimitry Andric   // scopes).
30400b57cec5SDimitry Andric   bool CheckRedeclaration = Owner->isRecord();
30410b57cec5SDimitry Andric 
30420b57cec5SDimitry Andric   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
30430b57cec5SDimitry Andric                     Sema::ForVisibleRedeclaration);
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
30460b57cec5SDimitry Andric                                        D->getUsingLoc(),
30470b57cec5SDimitry Andric                                        QualifierLoc,
30480b57cec5SDimitry Andric                                        NameInfo,
30490b57cec5SDimitry Andric                                        D->hasTypename());
30500b57cec5SDimitry Andric 
30510b57cec5SDimitry Andric   CXXScopeSpec SS;
30520b57cec5SDimitry Andric   SS.Adopt(QualifierLoc);
30530b57cec5SDimitry Andric   if (CheckRedeclaration) {
30540b57cec5SDimitry Andric     Prev.setHideTags(false);
30550b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(Prev, Owner);
30560b57cec5SDimitry Andric 
30570b57cec5SDimitry Andric     // Check for invalid redeclarations.
30580b57cec5SDimitry Andric     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
30590b57cec5SDimitry Andric                                             D->hasTypename(), SS,
30600b57cec5SDimitry Andric                                             D->getLocation(), Prev))
30610b57cec5SDimitry Andric       NewUD->setInvalidDecl();
30620b57cec5SDimitry Andric 
30630b57cec5SDimitry Andric   }
30640b57cec5SDimitry Andric 
30650b57cec5SDimitry Andric   if (!NewUD->isInvalidDecl() &&
30660b57cec5SDimitry Andric       SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
30670b57cec5SDimitry Andric                                       SS, NameInfo, D->getLocation()))
30680b57cec5SDimitry Andric     NewUD->setInvalidDecl();
30690b57cec5SDimitry Andric 
30700b57cec5SDimitry Andric   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
30710b57cec5SDimitry Andric   NewUD->setAccess(D->getAccess());
30720b57cec5SDimitry Andric   Owner->addDecl(NewUD);
30730b57cec5SDimitry Andric 
30740b57cec5SDimitry Andric   // Don't process the shadow decls for an invalid decl.
30750b57cec5SDimitry Andric   if (NewUD->isInvalidDecl())
30760b57cec5SDimitry Andric     return NewUD;
30770b57cec5SDimitry Andric 
30780b57cec5SDimitry Andric   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
30790b57cec5SDimitry Andric     SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric   bool isFunctionScope = Owner->isFunctionOrMethod();
30820b57cec5SDimitry Andric 
30830b57cec5SDimitry Andric   // Process the shadow decls.
30840b57cec5SDimitry Andric   for (auto *Shadow : D->shadows()) {
30850b57cec5SDimitry Andric     // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
30860b57cec5SDimitry Andric     // reconstruct it in the case where it matters.
30870b57cec5SDimitry Andric     NamedDecl *OldTarget = Shadow->getTargetDecl();
30880b57cec5SDimitry Andric     if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
30890b57cec5SDimitry Andric       if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
30900b57cec5SDimitry Andric         OldTarget = BaseShadow;
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric     NamedDecl *InstTarget =
30930b57cec5SDimitry Andric         cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
30940b57cec5SDimitry Andric             Shadow->getLocation(), OldTarget, TemplateArgs));
30950b57cec5SDimitry Andric     if (!InstTarget)
30960b57cec5SDimitry Andric       return nullptr;
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric     UsingShadowDecl *PrevDecl = nullptr;
30990b57cec5SDimitry Andric     if (CheckRedeclaration) {
31000b57cec5SDimitry Andric       if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
31010b57cec5SDimitry Andric         continue;
31020b57cec5SDimitry Andric     } else if (UsingShadowDecl *OldPrev =
31030b57cec5SDimitry Andric                    getPreviousDeclForInstantiation(Shadow)) {
31040b57cec5SDimitry Andric       PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
31050b57cec5SDimitry Andric           Shadow->getLocation(), OldPrev, TemplateArgs));
31060b57cec5SDimitry Andric     }
31070b57cec5SDimitry Andric 
31080b57cec5SDimitry Andric     UsingShadowDecl *InstShadow =
31090b57cec5SDimitry Andric         SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
31100b57cec5SDimitry Andric                                      PrevDecl);
31110b57cec5SDimitry Andric     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
31120b57cec5SDimitry Andric 
31130b57cec5SDimitry Andric     if (isFunctionScope)
31140b57cec5SDimitry Andric       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
31150b57cec5SDimitry Andric   }
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric   return NewUD;
31180b57cec5SDimitry Andric }
31190b57cec5SDimitry Andric 
31200b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
31210b57cec5SDimitry Andric   // Ignore these;  we handle them in bulk when processing the UsingDecl.
31220b57cec5SDimitry Andric   return nullptr;
31230b57cec5SDimitry Andric }
31240b57cec5SDimitry Andric 
31250b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
31260b57cec5SDimitry Andric     ConstructorUsingShadowDecl *D) {
31270b57cec5SDimitry Andric   // Ignore these;  we handle them in bulk when processing the UsingDecl.
31280b57cec5SDimitry Andric   return nullptr;
31290b57cec5SDimitry Andric }
31300b57cec5SDimitry Andric 
31310b57cec5SDimitry Andric template <typename T>
31320b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
31330b57cec5SDimitry Andric     T *D, bool InstantiatingPackElement) {
31340b57cec5SDimitry Andric   // If this is a pack expansion, expand it now.
31350b57cec5SDimitry Andric   if (D->isPackExpansion() && !InstantiatingPackElement) {
31360b57cec5SDimitry Andric     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
31370b57cec5SDimitry Andric     SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
31380b57cec5SDimitry Andric     SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
31390b57cec5SDimitry Andric 
31400b57cec5SDimitry Andric     // Determine whether the set of unexpanded parameter packs can and should
31410b57cec5SDimitry Andric     // be expanded.
31420b57cec5SDimitry Andric     bool Expand = true;
31430b57cec5SDimitry Andric     bool RetainExpansion = false;
31440b57cec5SDimitry Andric     Optional<unsigned> NumExpansions;
31450b57cec5SDimitry Andric     if (SemaRef.CheckParameterPacksForExpansion(
31460b57cec5SDimitry Andric           D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
31470b57cec5SDimitry Andric             Expand, RetainExpansion, NumExpansions))
31480b57cec5SDimitry Andric       return nullptr;
31490b57cec5SDimitry Andric 
31500b57cec5SDimitry Andric     // This declaration cannot appear within a function template signature,
31510b57cec5SDimitry Andric     // so we can't have a partial argument list for a parameter pack.
31520b57cec5SDimitry Andric     assert(!RetainExpansion &&
31530b57cec5SDimitry Andric            "should never need to retain an expansion for UsingPackDecl");
31540b57cec5SDimitry Andric 
31550b57cec5SDimitry Andric     if (!Expand) {
31560b57cec5SDimitry Andric       // We cannot fully expand the pack expansion now, so substitute into the
31570b57cec5SDimitry Andric       // pattern and create a new pack expansion.
31580b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
31590b57cec5SDimitry Andric       return instantiateUnresolvedUsingDecl(D, true);
31600b57cec5SDimitry Andric     }
31610b57cec5SDimitry Andric 
31620b57cec5SDimitry Andric     // Within a function, we don't have any normal way to check for conflicts
31630b57cec5SDimitry Andric     // between shadow declarations from different using declarations in the
31640b57cec5SDimitry Andric     // same pack expansion, but this is always ill-formed because all expansions
31650b57cec5SDimitry Andric     // must produce (conflicting) enumerators.
31660b57cec5SDimitry Andric     //
31670b57cec5SDimitry Andric     // Sadly we can't just reject this in the template definition because it
31680b57cec5SDimitry Andric     // could be valid if the pack is empty or has exactly one expansion.
31690b57cec5SDimitry Andric     if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
31700b57cec5SDimitry Andric       SemaRef.Diag(D->getEllipsisLoc(),
31710b57cec5SDimitry Andric                    diag::err_using_decl_redeclaration_expansion);
31720b57cec5SDimitry Andric       return nullptr;
31730b57cec5SDimitry Andric     }
31740b57cec5SDimitry Andric 
31750b57cec5SDimitry Andric     // Instantiate the slices of this pack and build a UsingPackDecl.
31760b57cec5SDimitry Andric     SmallVector<NamedDecl*, 8> Expansions;
31770b57cec5SDimitry Andric     for (unsigned I = 0; I != *NumExpansions; ++I) {
31780b57cec5SDimitry Andric       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
31790b57cec5SDimitry Andric       Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
31800b57cec5SDimitry Andric       if (!Slice)
31810b57cec5SDimitry Andric         return nullptr;
31820b57cec5SDimitry Andric       // Note that we can still get unresolved using declarations here, if we
31830b57cec5SDimitry Andric       // had arguments for all packs but the pattern also contained other
31840b57cec5SDimitry Andric       // template arguments (this only happens during partial substitution, eg
31850b57cec5SDimitry Andric       // into the body of a generic lambda in a function template).
31860b57cec5SDimitry Andric       Expansions.push_back(cast<NamedDecl>(Slice));
31870b57cec5SDimitry Andric     }
31880b57cec5SDimitry Andric 
31890b57cec5SDimitry Andric     auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
31900b57cec5SDimitry Andric     if (isDeclWithinFunction(D))
31910b57cec5SDimitry Andric       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
31920b57cec5SDimitry Andric     return NewD;
31930b57cec5SDimitry Andric   }
31940b57cec5SDimitry Andric 
31950b57cec5SDimitry Andric   UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
31960b57cec5SDimitry Andric   SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric   NestedNameSpecifierLoc QualifierLoc
31990b57cec5SDimitry Andric     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
32000b57cec5SDimitry Andric                                           TemplateArgs);
32010b57cec5SDimitry Andric   if (!QualifierLoc)
32020b57cec5SDimitry Andric     return nullptr;
32030b57cec5SDimitry Andric 
32040b57cec5SDimitry Andric   CXXScopeSpec SS;
32050b57cec5SDimitry Andric   SS.Adopt(QualifierLoc);
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric   DeclarationNameInfo NameInfo
32080b57cec5SDimitry Andric     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric   // Produce a pack expansion only if we're not instantiating a particular
32110b57cec5SDimitry Andric   // slice of a pack expansion.
32120b57cec5SDimitry Andric   bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
32130b57cec5SDimitry Andric                             SemaRef.ArgumentPackSubstitutionIndex != -1;
32140b57cec5SDimitry Andric   SourceLocation EllipsisLoc =
32150b57cec5SDimitry Andric       InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric   NamedDecl *UD = SemaRef.BuildUsingDeclaration(
32180b57cec5SDimitry Andric       /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
32190b57cec5SDimitry Andric       /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
32200b57cec5SDimitry Andric       ParsedAttributesView(),
32210b57cec5SDimitry Andric       /*IsInstantiation*/ true);
32220b57cec5SDimitry Andric   if (UD)
32230b57cec5SDimitry Andric     SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
32240b57cec5SDimitry Andric 
32250b57cec5SDimitry Andric   return UD;
32260b57cec5SDimitry Andric }
32270b57cec5SDimitry Andric 
32280b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
32290b57cec5SDimitry Andric     UnresolvedUsingTypenameDecl *D) {
32300b57cec5SDimitry Andric   return instantiateUnresolvedUsingDecl(D);
32310b57cec5SDimitry Andric }
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
32340b57cec5SDimitry Andric     UnresolvedUsingValueDecl *D) {
32350b57cec5SDimitry Andric   return instantiateUnresolvedUsingDecl(D);
32360b57cec5SDimitry Andric }
32370b57cec5SDimitry Andric 
32380b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
32390b57cec5SDimitry Andric   SmallVector<NamedDecl*, 8> Expansions;
32400b57cec5SDimitry Andric   for (auto *UD : D->expansions()) {
32410b57cec5SDimitry Andric     if (NamedDecl *NewUD =
32420b57cec5SDimitry Andric             SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
32430b57cec5SDimitry Andric       Expansions.push_back(NewUD);
32440b57cec5SDimitry Andric     else
32450b57cec5SDimitry Andric       return nullptr;
32460b57cec5SDimitry Andric   }
32470b57cec5SDimitry Andric 
32480b57cec5SDimitry Andric   auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
32490b57cec5SDimitry Andric   if (isDeclWithinFunction(D))
32500b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
32510b57cec5SDimitry Andric   return NewD;
32520b57cec5SDimitry Andric }
32530b57cec5SDimitry Andric 
32540b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
32550b57cec5SDimitry Andric     ClassScopeFunctionSpecializationDecl *Decl) {
32560b57cec5SDimitry Andric   CXXMethodDecl *OldFD = Decl->getSpecialization();
32570b57cec5SDimitry Andric   return cast_or_null<CXXMethodDecl>(
32580b57cec5SDimitry Andric       VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
32590b57cec5SDimitry Andric }
32600b57cec5SDimitry Andric 
32610b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
32620b57cec5SDimitry Andric                                      OMPThreadPrivateDecl *D) {
32630b57cec5SDimitry Andric   SmallVector<Expr *, 5> Vars;
32640b57cec5SDimitry Andric   for (auto *I : D->varlists()) {
32650b57cec5SDimitry Andric     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
32660b57cec5SDimitry Andric     assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
32670b57cec5SDimitry Andric     Vars.push_back(Var);
32680b57cec5SDimitry Andric   }
32690b57cec5SDimitry Andric 
32700b57cec5SDimitry Andric   OMPThreadPrivateDecl *TD =
32710b57cec5SDimitry Andric     SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
32720b57cec5SDimitry Andric 
32730b57cec5SDimitry Andric   TD->setAccess(AS_public);
32740b57cec5SDimitry Andric   Owner->addDecl(TD);
32750b57cec5SDimitry Andric 
32760b57cec5SDimitry Andric   return TD;
32770b57cec5SDimitry Andric }
32780b57cec5SDimitry Andric 
32790b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
32800b57cec5SDimitry Andric   SmallVector<Expr *, 5> Vars;
32810b57cec5SDimitry Andric   for (auto *I : D->varlists()) {
32820b57cec5SDimitry Andric     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
32830b57cec5SDimitry Andric     assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
32840b57cec5SDimitry Andric     Vars.push_back(Var);
32850b57cec5SDimitry Andric   }
32860b57cec5SDimitry Andric   SmallVector<OMPClause *, 4> Clauses;
32870b57cec5SDimitry Andric   // Copy map clauses from the original mapper.
32880b57cec5SDimitry Andric   for (OMPClause *C : D->clauselists()) {
32890b57cec5SDimitry Andric     auto *AC = cast<OMPAllocatorClause>(C);
32900b57cec5SDimitry Andric     ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
32910b57cec5SDimitry Andric     if (!NewE.isUsable())
32920b57cec5SDimitry Andric       continue;
32930b57cec5SDimitry Andric     OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
32940b57cec5SDimitry Andric         NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
32950b57cec5SDimitry Andric     Clauses.push_back(IC);
32960b57cec5SDimitry Andric   }
32970b57cec5SDimitry Andric 
32980b57cec5SDimitry Andric   Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
32990b57cec5SDimitry Andric       D->getLocation(), Vars, Clauses, Owner);
33000b57cec5SDimitry Andric   if (Res.get().isNull())
33010b57cec5SDimitry Andric     return nullptr;
33020b57cec5SDimitry Andric   return Res.get().getSingleDecl();
33030b57cec5SDimitry Andric }
33040b57cec5SDimitry Andric 
33050b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
33060b57cec5SDimitry Andric   llvm_unreachable(
33070b57cec5SDimitry Andric       "Requires directive cannot be instantiated within a dependent context");
33080b57cec5SDimitry Andric }
33090b57cec5SDimitry Andric 
33100b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
33110b57cec5SDimitry Andric     OMPDeclareReductionDecl *D) {
33120b57cec5SDimitry Andric   // Instantiate type and check if it is allowed.
33130b57cec5SDimitry Andric   const bool RequiresInstantiation =
33140b57cec5SDimitry Andric       D->getType()->isDependentType() ||
33150b57cec5SDimitry Andric       D->getType()->isInstantiationDependentType() ||
33160b57cec5SDimitry Andric       D->getType()->containsUnexpandedParameterPack();
33170b57cec5SDimitry Andric   QualType SubstReductionType;
33180b57cec5SDimitry Andric   if (RequiresInstantiation) {
33190b57cec5SDimitry Andric     SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
33200b57cec5SDimitry Andric         D->getLocation(),
33210b57cec5SDimitry Andric         ParsedType::make(SemaRef.SubstType(
33220b57cec5SDimitry Andric             D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
33230b57cec5SDimitry Andric   } else {
33240b57cec5SDimitry Andric     SubstReductionType = D->getType();
33250b57cec5SDimitry Andric   }
33260b57cec5SDimitry Andric   if (SubstReductionType.isNull())
33270b57cec5SDimitry Andric     return nullptr;
3328480093f4SDimitry Andric   Expr *Combiner = D->getCombiner();
3329480093f4SDimitry Andric   Expr *Init = D->getInitializer();
3330480093f4SDimitry Andric   bool IsCorrect = true;
33310b57cec5SDimitry Andric   // Create instantiated copy.
33320b57cec5SDimitry Andric   std::pair<QualType, SourceLocation> ReductionTypes[] = {
33330b57cec5SDimitry Andric       std::make_pair(SubstReductionType, D->getLocation())};
33340b57cec5SDimitry Andric   auto *PrevDeclInScope = D->getPrevDeclInScope();
33350b57cec5SDimitry Andric   if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
33360b57cec5SDimitry Andric     PrevDeclInScope = cast<OMPDeclareReductionDecl>(
33370b57cec5SDimitry Andric         SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
33380b57cec5SDimitry Andric             ->get<Decl *>());
33390b57cec5SDimitry Andric   }
33400b57cec5SDimitry Andric   auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
33410b57cec5SDimitry Andric       /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
33420b57cec5SDimitry Andric       PrevDeclInScope);
33430b57cec5SDimitry Andric   auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
33440b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
33450b57cec5SDimitry Andric   Expr *SubstCombiner = nullptr;
33460b57cec5SDimitry Andric   Expr *SubstInitializer = nullptr;
33470b57cec5SDimitry Andric   // Combiners instantiation sequence.
3348480093f4SDimitry Andric   if (Combiner) {
33490b57cec5SDimitry Andric     SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
33500b57cec5SDimitry Andric         /*S=*/nullptr, NewDRD);
33510b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
33520b57cec5SDimitry Andric         cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
33530b57cec5SDimitry Andric         cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
33540b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
33550b57cec5SDimitry Andric         cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
33560b57cec5SDimitry Andric         cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
33570b57cec5SDimitry Andric     auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
33580b57cec5SDimitry Andric     Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
33590b57cec5SDimitry Andric                                      ThisContext);
3360480093f4SDimitry Andric     SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
33610b57cec5SDimitry Andric     SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3362480093f4SDimitry Andric   }
33630b57cec5SDimitry Andric   // Initializers instantiation sequence.
3364480093f4SDimitry Andric   if (Init) {
3365480093f4SDimitry Andric     VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
33660b57cec5SDimitry Andric         /*S=*/nullptr, NewDRD);
33670b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
33680b57cec5SDimitry Andric         cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
33690b57cec5SDimitry Andric         cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
33700b57cec5SDimitry Andric     SemaRef.CurrentInstantiationScope->InstantiatedLocal(
33710b57cec5SDimitry Andric         cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
33720b57cec5SDimitry Andric         cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
33730b57cec5SDimitry Andric     if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3374480093f4SDimitry Andric       SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
33750b57cec5SDimitry Andric     } else {
3376480093f4SDimitry Andric       auto *OldPrivParm =
3377480093f4SDimitry Andric           cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3378480093f4SDimitry Andric       IsCorrect = IsCorrect && OldPrivParm->hasInit();
3379480093f4SDimitry Andric       if (IsCorrect)
3380480093f4SDimitry Andric         SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3381480093f4SDimitry Andric                                                TemplateArgs);
33820b57cec5SDimitry Andric     }
3383480093f4SDimitry Andric     SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3384480093f4SDimitry Andric                                                       OmpPrivParm);
33850b57cec5SDimitry Andric   }
3386480093f4SDimitry Andric   IsCorrect = IsCorrect && SubstCombiner &&
3387480093f4SDimitry Andric               (!Init ||
33880b57cec5SDimitry Andric                (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
33890b57cec5SDimitry Andric                 SubstInitializer) ||
33900b57cec5SDimitry Andric                (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3391480093f4SDimitry Andric                 !SubstInitializer));
33920b57cec5SDimitry Andric 
3393480093f4SDimitry Andric   (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3394480093f4SDimitry Andric       /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
33950b57cec5SDimitry Andric 
33960b57cec5SDimitry Andric   return NewDRD;
33970b57cec5SDimitry Andric }
33980b57cec5SDimitry Andric 
33990b57cec5SDimitry Andric Decl *
34000b57cec5SDimitry Andric TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
34010b57cec5SDimitry Andric   // Instantiate type and check if it is allowed.
34020b57cec5SDimitry Andric   const bool RequiresInstantiation =
34030b57cec5SDimitry Andric       D->getType()->isDependentType() ||
34040b57cec5SDimitry Andric       D->getType()->isInstantiationDependentType() ||
34050b57cec5SDimitry Andric       D->getType()->containsUnexpandedParameterPack();
34060b57cec5SDimitry Andric   QualType SubstMapperTy;
34070b57cec5SDimitry Andric   DeclarationName VN = D->getVarName();
34080b57cec5SDimitry Andric   if (RequiresInstantiation) {
34090b57cec5SDimitry Andric     SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
34100b57cec5SDimitry Andric         D->getLocation(),
34110b57cec5SDimitry Andric         ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
34120b57cec5SDimitry Andric                                            D->getLocation(), VN)));
34130b57cec5SDimitry Andric   } else {
34140b57cec5SDimitry Andric     SubstMapperTy = D->getType();
34150b57cec5SDimitry Andric   }
34160b57cec5SDimitry Andric   if (SubstMapperTy.isNull())
34170b57cec5SDimitry Andric     return nullptr;
34180b57cec5SDimitry Andric   // Create an instantiated copy of mapper.
34190b57cec5SDimitry Andric   auto *PrevDeclInScope = D->getPrevDeclInScope();
34200b57cec5SDimitry Andric   if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
34210b57cec5SDimitry Andric     PrevDeclInScope = cast<OMPDeclareMapperDecl>(
34220b57cec5SDimitry Andric         SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
34230b57cec5SDimitry Andric             ->get<Decl *>());
34240b57cec5SDimitry Andric   }
34250b57cec5SDimitry Andric   bool IsCorrect = true;
3426*e8d8bef9SDimitry Andric   SmallVector<OMPClause *, 6> Clauses;
34270b57cec5SDimitry Andric   // Instantiate the mapper variable.
34280b57cec5SDimitry Andric   DeclarationNameInfo DirName;
3429480093f4SDimitry Andric   SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3430480093f4SDimitry Andric                               /*S=*/nullptr,
34310b57cec5SDimitry Andric                               (*D->clauselist_begin())->getBeginLoc());
3432*e8d8bef9SDimitry Andric   ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3433*e8d8bef9SDimitry Andric       /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
34340b57cec5SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(
34350b57cec5SDimitry Andric       cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3436*e8d8bef9SDimitry Andric       cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
34370b57cec5SDimitry Andric   auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
34380b57cec5SDimitry Andric   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
34390b57cec5SDimitry Andric                                    ThisContext);
34400b57cec5SDimitry Andric   // Instantiate map clauses.
34410b57cec5SDimitry Andric   for (OMPClause *C : D->clauselists()) {
34420b57cec5SDimitry Andric     auto *OldC = cast<OMPMapClause>(C);
34430b57cec5SDimitry Andric     SmallVector<Expr *, 4> NewVars;
34440b57cec5SDimitry Andric     for (Expr *OE : OldC->varlists()) {
34450b57cec5SDimitry Andric       Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
34460b57cec5SDimitry Andric       if (!NE) {
34470b57cec5SDimitry Andric         IsCorrect = false;
34480b57cec5SDimitry Andric         break;
34490b57cec5SDimitry Andric       }
34500b57cec5SDimitry Andric       NewVars.push_back(NE);
34510b57cec5SDimitry Andric     }
34520b57cec5SDimitry Andric     if (!IsCorrect)
34530b57cec5SDimitry Andric       break;
34540b57cec5SDimitry Andric     NestedNameSpecifierLoc NewQualifierLoc =
34550b57cec5SDimitry Andric         SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
34560b57cec5SDimitry Andric                                             TemplateArgs);
34570b57cec5SDimitry Andric     CXXScopeSpec SS;
34580b57cec5SDimitry Andric     SS.Adopt(NewQualifierLoc);
3459*e8d8bef9SDimitry Andric     DeclarationNameInfo NewNameInfo =
3460*e8d8bef9SDimitry Andric         SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
34610b57cec5SDimitry Andric     OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
34620b57cec5SDimitry Andric                          OldC->getEndLoc());
34630b57cec5SDimitry Andric     OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
34640b57cec5SDimitry Andric         OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
34650b57cec5SDimitry Andric         NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
34660b57cec5SDimitry Andric         OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
34670b57cec5SDimitry Andric     Clauses.push_back(NewC);
34680b57cec5SDimitry Andric   }
34690b57cec5SDimitry Andric   SemaRef.EndOpenMPDSABlock(nullptr);
34700b57cec5SDimitry Andric   if (!IsCorrect)
34710b57cec5SDimitry Andric     return nullptr;
3472*e8d8bef9SDimitry Andric   Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
3473*e8d8bef9SDimitry Andric       /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3474*e8d8bef9SDimitry Andric       VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3475*e8d8bef9SDimitry Andric   Decl *NewDMD = DG.get().getSingleDecl();
3476*e8d8bef9SDimitry Andric   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
34770b57cec5SDimitry Andric   return NewDMD;
34780b57cec5SDimitry Andric }
34790b57cec5SDimitry Andric 
34800b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
34810b57cec5SDimitry Andric     OMPCapturedExprDecl * /*D*/) {
34820b57cec5SDimitry Andric   llvm_unreachable("Should not be met in templates");
34830b57cec5SDimitry Andric }
34840b57cec5SDimitry Andric 
34850b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
34860b57cec5SDimitry Andric   return VisitFunctionDecl(D, nullptr);
34870b57cec5SDimitry Andric }
34880b57cec5SDimitry Andric 
34890b57cec5SDimitry Andric Decl *
34900b57cec5SDimitry Andric TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
34910b57cec5SDimitry Andric   Decl *Inst = VisitFunctionDecl(D, nullptr);
34920b57cec5SDimitry Andric   if (Inst && !D->getDescribedFunctionTemplate())
34930b57cec5SDimitry Andric     Owner->addDecl(Inst);
34940b57cec5SDimitry Andric   return Inst;
34950b57cec5SDimitry Andric }
34960b57cec5SDimitry Andric 
34970b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
34980b57cec5SDimitry Andric   return VisitCXXMethodDecl(D, nullptr);
34990b57cec5SDimitry Andric }
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
35020b57cec5SDimitry Andric   llvm_unreachable("There are only CXXRecordDecls in C++");
35030b57cec5SDimitry Andric }
35040b57cec5SDimitry Andric 
35050b57cec5SDimitry Andric Decl *
35060b57cec5SDimitry Andric TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
35070b57cec5SDimitry Andric     ClassTemplateSpecializationDecl *D) {
35080b57cec5SDimitry Andric   // As a MS extension, we permit class-scope explicit specialization
35090b57cec5SDimitry Andric   // of member class templates.
35100b57cec5SDimitry Andric   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
35110b57cec5SDimitry Andric   assert(ClassTemplate->getDeclContext()->isRecord() &&
35120b57cec5SDimitry Andric          D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
35130b57cec5SDimitry Andric          "can only instantiate an explicit specialization "
35140b57cec5SDimitry Andric          "for a member class template");
35150b57cec5SDimitry Andric 
35160b57cec5SDimitry Andric   // Lookup the already-instantiated declaration in the instantiation
35170b57cec5SDimitry Andric   // of the class template.
35180b57cec5SDimitry Andric   ClassTemplateDecl *InstClassTemplate =
35190b57cec5SDimitry Andric       cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
35200b57cec5SDimitry Andric           D->getLocation(), ClassTemplate, TemplateArgs));
35210b57cec5SDimitry Andric   if (!InstClassTemplate)
35220b57cec5SDimitry Andric     return nullptr;
35230b57cec5SDimitry Andric 
35240b57cec5SDimitry Andric   // Substitute into the template arguments of the class template explicit
35250b57cec5SDimitry Andric   // specialization.
35260b57cec5SDimitry Andric   TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
35270b57cec5SDimitry Andric                                         castAs<TemplateSpecializationTypeLoc>();
35280b57cec5SDimitry Andric   TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
35290b57cec5SDimitry Andric                                             Loc.getRAngleLoc());
35300b57cec5SDimitry Andric   SmallVector<TemplateArgumentLoc, 4> ArgLocs;
35310b57cec5SDimitry Andric   for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
35320b57cec5SDimitry Andric     ArgLocs.push_back(Loc.getArgLoc(I));
35330b57cec5SDimitry Andric   if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
35340b57cec5SDimitry Andric                     InstTemplateArgs, TemplateArgs))
35350b57cec5SDimitry Andric     return nullptr;
35360b57cec5SDimitry Andric 
35370b57cec5SDimitry Andric   // Check that the template argument list is well-formed for this
35380b57cec5SDimitry Andric   // class template.
35390b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Converted;
35400b57cec5SDimitry Andric   if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
35410b57cec5SDimitry Andric                                         D->getLocation(),
35420b57cec5SDimitry Andric                                         InstTemplateArgs,
35430b57cec5SDimitry Andric                                         false,
3544480093f4SDimitry Andric                                         Converted,
3545480093f4SDimitry Andric                                         /*UpdateArgsWithConversion=*/true))
35460b57cec5SDimitry Andric     return nullptr;
35470b57cec5SDimitry Andric 
35480b57cec5SDimitry Andric   // Figure out where to insert this class template explicit specialization
35490b57cec5SDimitry Andric   // in the member template's set of class template explicit specializations.
35500b57cec5SDimitry Andric   void *InsertPos = nullptr;
35510b57cec5SDimitry Andric   ClassTemplateSpecializationDecl *PrevDecl =
35520b57cec5SDimitry Andric       InstClassTemplate->findSpecialization(Converted, InsertPos);
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric   // Check whether we've already seen a conflicting instantiation of this
35550b57cec5SDimitry Andric   // declaration (for instance, if there was a prior implicit instantiation).
35560b57cec5SDimitry Andric   bool Ignored;
35570b57cec5SDimitry Andric   if (PrevDecl &&
35580b57cec5SDimitry Andric       SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
35590b57cec5SDimitry Andric                                                      D->getSpecializationKind(),
35600b57cec5SDimitry Andric                                                      PrevDecl,
35610b57cec5SDimitry Andric                                                      PrevDecl->getSpecializationKind(),
35620b57cec5SDimitry Andric                                                      PrevDecl->getPointOfInstantiation(),
35630b57cec5SDimitry Andric                                                      Ignored))
35640b57cec5SDimitry Andric     return nullptr;
35650b57cec5SDimitry Andric 
35660b57cec5SDimitry Andric   // If PrevDecl was a definition and D is also a definition, diagnose.
35670b57cec5SDimitry Andric   // This happens in cases like:
35680b57cec5SDimitry Andric   //
35690b57cec5SDimitry Andric   //   template<typename T, typename U>
35700b57cec5SDimitry Andric   //   struct Outer {
35710b57cec5SDimitry Andric   //     template<typename X> struct Inner;
35720b57cec5SDimitry Andric   //     template<> struct Inner<T> {};
35730b57cec5SDimitry Andric   //     template<> struct Inner<U> {};
35740b57cec5SDimitry Andric   //   };
35750b57cec5SDimitry Andric   //
35760b57cec5SDimitry Andric   //   Outer<int, int> outer; // error: the explicit specializations of Inner
35770b57cec5SDimitry Andric   //                          // have the same signature.
35780b57cec5SDimitry Andric   if (PrevDecl && PrevDecl->getDefinition() &&
35790b57cec5SDimitry Andric       D->isThisDeclarationADefinition()) {
35800b57cec5SDimitry Andric     SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
35810b57cec5SDimitry Andric     SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
35820b57cec5SDimitry Andric                  diag::note_previous_definition);
35830b57cec5SDimitry Andric     return nullptr;
35840b57cec5SDimitry Andric   }
35850b57cec5SDimitry Andric 
35860b57cec5SDimitry Andric   // Create the class template partial specialization declaration.
35870b57cec5SDimitry Andric   ClassTemplateSpecializationDecl *InstD =
35880b57cec5SDimitry Andric       ClassTemplateSpecializationDecl::Create(
35890b57cec5SDimitry Andric           SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
35900b57cec5SDimitry Andric           D->getLocation(), InstClassTemplate, Converted, PrevDecl);
35910b57cec5SDimitry Andric 
35920b57cec5SDimitry Andric   // Add this partial specialization to the set of class template partial
35930b57cec5SDimitry Andric   // specializations.
35940b57cec5SDimitry Andric   if (!PrevDecl)
35950b57cec5SDimitry Andric     InstClassTemplate->AddSpecialization(InstD, InsertPos);
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
35980b57cec5SDimitry Andric   if (SubstQualifier(D, InstD))
35990b57cec5SDimitry Andric     return nullptr;
36000b57cec5SDimitry Andric 
36010b57cec5SDimitry Andric   // Build the canonical type that describes the converted template
36020b57cec5SDimitry Andric   // arguments of the class template explicit specialization.
36030b57cec5SDimitry Andric   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
36040b57cec5SDimitry Andric       TemplateName(InstClassTemplate), Converted,
36050b57cec5SDimitry Andric       SemaRef.Context.getRecordType(InstD));
36060b57cec5SDimitry Andric 
36070b57cec5SDimitry Andric   // Build the fully-sugared type for this class template
36080b57cec5SDimitry Andric   // specialization as the user wrote in the specialization
36090b57cec5SDimitry Andric   // itself. This means that we'll pretty-print the type retrieved
36100b57cec5SDimitry Andric   // from the specialization's declaration the way that the user
36110b57cec5SDimitry Andric   // actually wrote the specialization, rather than formatting the
36120b57cec5SDimitry Andric   // name based on the "canonical" representation used to store the
36130b57cec5SDimitry Andric   // template arguments in the specialization.
36140b57cec5SDimitry Andric   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
36150b57cec5SDimitry Andric       TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
36160b57cec5SDimitry Andric       CanonType);
36170b57cec5SDimitry Andric 
36180b57cec5SDimitry Andric   InstD->setAccess(D->getAccess());
36190b57cec5SDimitry Andric   InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
36200b57cec5SDimitry Andric   InstD->setSpecializationKind(D->getSpecializationKind());
36210b57cec5SDimitry Andric   InstD->setTypeAsWritten(WrittenTy);
36220b57cec5SDimitry Andric   InstD->setExternLoc(D->getExternLoc());
36230b57cec5SDimitry Andric   InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
36240b57cec5SDimitry Andric 
36250b57cec5SDimitry Andric   Owner->addDecl(InstD);
36260b57cec5SDimitry Andric 
36270b57cec5SDimitry Andric   // Instantiate the members of the class-scope explicit specialization eagerly.
36280b57cec5SDimitry Andric   // We don't have support for lazy instantiation of an explicit specialization
36290b57cec5SDimitry Andric   // yet, and MSVC eagerly instantiates in this case.
36300b57cec5SDimitry Andric   // FIXME: This is wrong in standard C++.
36310b57cec5SDimitry Andric   if (D->isThisDeclarationADefinition() &&
36320b57cec5SDimitry Andric       SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
36330b57cec5SDimitry Andric                                TSK_ImplicitInstantiation,
36340b57cec5SDimitry Andric                                /*Complain=*/true))
36350b57cec5SDimitry Andric     return nullptr;
36360b57cec5SDimitry Andric 
36370b57cec5SDimitry Andric   return InstD;
36380b57cec5SDimitry Andric }
36390b57cec5SDimitry Andric 
36400b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
36410b57cec5SDimitry Andric     VarTemplateSpecializationDecl *D) {
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric   TemplateArgumentListInfo VarTemplateArgsInfo;
36440b57cec5SDimitry Andric   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
36450b57cec5SDimitry Andric   assert(VarTemplate &&
36460b57cec5SDimitry Andric          "A template specialization without specialized template?");
36470b57cec5SDimitry Andric 
36480b57cec5SDimitry Andric   VarTemplateDecl *InstVarTemplate =
36490b57cec5SDimitry Andric       cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
36500b57cec5SDimitry Andric           D->getLocation(), VarTemplate, TemplateArgs));
36510b57cec5SDimitry Andric   if (!InstVarTemplate)
36520b57cec5SDimitry Andric     return nullptr;
36530b57cec5SDimitry Andric 
36540b57cec5SDimitry Andric   // Substitute the current template arguments.
36550b57cec5SDimitry Andric   const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
36560b57cec5SDimitry Andric   VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
36570b57cec5SDimitry Andric   VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
36580b57cec5SDimitry Andric 
36590b57cec5SDimitry Andric   if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
36600b57cec5SDimitry Andric                     TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
36610b57cec5SDimitry Andric     return nullptr;
36620b57cec5SDimitry Andric 
36630b57cec5SDimitry Andric   // Check that the template argument list is well-formed for this template.
36640b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Converted;
36650b57cec5SDimitry Andric   if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3666480093f4SDimitry Andric                                         VarTemplateArgsInfo, false, Converted,
3667480093f4SDimitry Andric                                         /*UpdateArgsWithConversion=*/true))
36680b57cec5SDimitry Andric     return nullptr;
36690b57cec5SDimitry Andric 
36700b57cec5SDimitry Andric   // Check whether we've already seen a declaration of this specialization.
36710b57cec5SDimitry Andric   void *InsertPos = nullptr;
36720b57cec5SDimitry Andric   VarTemplateSpecializationDecl *PrevDecl =
36730b57cec5SDimitry Andric       InstVarTemplate->findSpecialization(Converted, InsertPos);
36740b57cec5SDimitry Andric 
36750b57cec5SDimitry Andric   // Check whether we've already seen a conflicting instantiation of this
36760b57cec5SDimitry Andric   // declaration (for instance, if there was a prior implicit instantiation).
36770b57cec5SDimitry Andric   bool Ignored;
36780b57cec5SDimitry Andric   if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
36790b57cec5SDimitry Andric                       D->getLocation(), D->getSpecializationKind(), PrevDecl,
36800b57cec5SDimitry Andric                       PrevDecl->getSpecializationKind(),
36810b57cec5SDimitry Andric                       PrevDecl->getPointOfInstantiation(), Ignored))
36820b57cec5SDimitry Andric     return nullptr;
36830b57cec5SDimitry Andric 
36840b57cec5SDimitry Andric   return VisitVarTemplateSpecializationDecl(
3685*e8d8bef9SDimitry Andric       InstVarTemplate, D, VarTemplateArgsInfo, Converted, PrevDecl);
36860b57cec5SDimitry Andric }
36870b57cec5SDimitry Andric 
36880b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3689*e8d8bef9SDimitry Andric     VarTemplateDecl *VarTemplate, VarDecl *D,
36900b57cec5SDimitry Andric     const TemplateArgumentListInfo &TemplateArgsInfo,
36910b57cec5SDimitry Andric     ArrayRef<TemplateArgument> Converted,
36920b57cec5SDimitry Andric     VarTemplateSpecializationDecl *PrevDecl) {
36930b57cec5SDimitry Andric 
36940b57cec5SDimitry Andric   // Do substitution on the type of the declaration
36950b57cec5SDimitry Andric   TypeSourceInfo *DI =
36960b57cec5SDimitry Andric       SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
36970b57cec5SDimitry Andric                         D->getTypeSpecStartLoc(), D->getDeclName());
36980b57cec5SDimitry Andric   if (!DI)
36990b57cec5SDimitry Andric     return nullptr;
37000b57cec5SDimitry Andric 
37010b57cec5SDimitry Andric   if (DI->getType()->isFunctionType()) {
37020b57cec5SDimitry Andric     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
37030b57cec5SDimitry Andric         << D->isStaticDataMember() << DI->getType();
37040b57cec5SDimitry Andric     return nullptr;
37050b57cec5SDimitry Andric   }
37060b57cec5SDimitry Andric 
37070b57cec5SDimitry Andric   // Build the instantiated declaration
37080b57cec5SDimitry Andric   VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
37090b57cec5SDimitry Andric       SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
37100b57cec5SDimitry Andric       VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
37110b57cec5SDimitry Andric   Var->setTemplateArgsInfo(TemplateArgsInfo);
3712eaeb601bSDimitry Andric   if (!PrevDecl) {
3713eaeb601bSDimitry Andric     void *InsertPos = nullptr;
3714eaeb601bSDimitry Andric     VarTemplate->findSpecialization(Converted, InsertPos);
37150b57cec5SDimitry Andric     VarTemplate->AddSpecialization(Var, InsertPos);
3716eaeb601bSDimitry Andric   }
37170b57cec5SDimitry Andric 
37185ffd83dbSDimitry Andric   if (SemaRef.getLangOpts().OpenCL)
37195ffd83dbSDimitry Andric     SemaRef.deduceOpenCLAddressSpace(Var);
37205ffd83dbSDimitry Andric 
37210b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
37220b57cec5SDimitry Andric   if (SubstQualifier(D, Var))
37230b57cec5SDimitry Andric     return nullptr;
37240b57cec5SDimitry Andric 
37250b57cec5SDimitry Andric   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
37260b57cec5SDimitry Andric                                      StartingScope, false, PrevDecl);
37270b57cec5SDimitry Andric 
37280b57cec5SDimitry Andric   return Var;
37290b57cec5SDimitry Andric }
37300b57cec5SDimitry Andric 
37310b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
37320b57cec5SDimitry Andric   llvm_unreachable("@defs is not supported in Objective-C++");
37330b57cec5SDimitry Andric }
37340b57cec5SDimitry Andric 
37350b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
37360b57cec5SDimitry Andric   // FIXME: We need to be able to instantiate FriendTemplateDecls.
37370b57cec5SDimitry Andric   unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
37380b57cec5SDimitry Andric                                                DiagnosticsEngine::Error,
37390b57cec5SDimitry Andric                                                "cannot instantiate %0 yet");
37400b57cec5SDimitry Andric   SemaRef.Diag(D->getLocation(), DiagID)
37410b57cec5SDimitry Andric     << D->getDeclKindName();
37420b57cec5SDimitry Andric 
37430b57cec5SDimitry Andric   return nullptr;
37440b57cec5SDimitry Andric }
37450b57cec5SDimitry Andric 
37460b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
37470b57cec5SDimitry Andric   llvm_unreachable("Concept definitions cannot reside inside a template");
37480b57cec5SDimitry Andric }
37490b57cec5SDimitry Andric 
375055e4f9d5SDimitry Andric Decl *
375155e4f9d5SDimitry Andric TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
375255e4f9d5SDimitry Andric   return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
375355e4f9d5SDimitry Andric                                       D->getBeginLoc());
375455e4f9d5SDimitry Andric }
375555e4f9d5SDimitry Andric 
37560b57cec5SDimitry Andric Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
37570b57cec5SDimitry Andric   llvm_unreachable("Unexpected decl");
37580b57cec5SDimitry Andric }
37590b57cec5SDimitry Andric 
37600b57cec5SDimitry Andric Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
37610b57cec5SDimitry Andric                       const MultiLevelTemplateArgumentList &TemplateArgs) {
37620b57cec5SDimitry Andric   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
37630b57cec5SDimitry Andric   if (D->isInvalidDecl())
37640b57cec5SDimitry Andric     return nullptr;
37650b57cec5SDimitry Andric 
3766a7dea167SDimitry Andric   Decl *SubstD;
3767a7dea167SDimitry Andric   runWithSufficientStackSpace(D->getLocation(), [&] {
3768a7dea167SDimitry Andric     SubstD = Instantiator.Visit(D);
3769a7dea167SDimitry Andric   });
3770a7dea167SDimitry Andric   return SubstD;
37710b57cec5SDimitry Andric }
37720b57cec5SDimitry Andric 
3773480093f4SDimitry Andric void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
3774480093f4SDimitry Andric                                                 FunctionDecl *Orig, QualType &T,
3775480093f4SDimitry Andric                                                 TypeSourceInfo *&TInfo,
3776480093f4SDimitry Andric                                                 DeclarationNameInfo &NameInfo) {
3777480093f4SDimitry Andric   assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
3778480093f4SDimitry Andric 
3779480093f4SDimitry Andric   // C++2a [class.compare.default]p3:
3780480093f4SDimitry Andric   //   the return type is replaced with bool
3781480093f4SDimitry Andric   auto *FPT = T->castAs<FunctionProtoType>();
3782480093f4SDimitry Andric   T = SemaRef.Context.getFunctionType(
3783480093f4SDimitry Andric       SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
3784480093f4SDimitry Andric 
3785480093f4SDimitry Andric   // Update the return type in the source info too. The most straightforward
3786480093f4SDimitry Andric   // way is to create new TypeSourceInfo for the new type. Use the location of
3787480093f4SDimitry Andric   // the '= default' as the location of the new type.
3788480093f4SDimitry Andric   //
3789480093f4SDimitry Andric   // FIXME: Set the correct return type when we initially transform the type,
3790480093f4SDimitry Andric   // rather than delaying it to now.
3791480093f4SDimitry Andric   TypeSourceInfo *NewTInfo =
3792480093f4SDimitry Andric       SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
3793480093f4SDimitry Andric   auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
3794480093f4SDimitry Andric   assert(OldLoc && "type of function is not a function type?");
3795480093f4SDimitry Andric   auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
3796480093f4SDimitry Andric   for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
3797480093f4SDimitry Andric     NewLoc.setParam(I, OldLoc.getParam(I));
3798480093f4SDimitry Andric   TInfo = NewTInfo;
3799480093f4SDimitry Andric 
3800480093f4SDimitry Andric   //   and the declarator-id is replaced with operator==
3801480093f4SDimitry Andric   NameInfo.setName(
3802480093f4SDimitry Andric       SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
3803480093f4SDimitry Andric }
3804480093f4SDimitry Andric 
3805480093f4SDimitry Andric FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
3806480093f4SDimitry Andric                                                FunctionDecl *Spaceship) {
3807480093f4SDimitry Andric   if (Spaceship->isInvalidDecl())
3808480093f4SDimitry Andric     return nullptr;
3809480093f4SDimitry Andric 
3810480093f4SDimitry Andric   // C++2a [class.compare.default]p3:
3811480093f4SDimitry Andric   //   an == operator function is declared implicitly [...] with the same
3812480093f4SDimitry Andric   //   access and function-definition and in the same class scope as the
3813480093f4SDimitry Andric   //   three-way comparison operator function
3814480093f4SDimitry Andric   MultiLevelTemplateArgumentList NoTemplateArgs;
38155ffd83dbSDimitry Andric   NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
38165ffd83dbSDimitry Andric   NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
3817480093f4SDimitry Andric   TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
3818480093f4SDimitry Andric   Decl *R;
3819480093f4SDimitry Andric   if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
3820480093f4SDimitry Andric     R = Instantiator.VisitCXXMethodDecl(
3821480093f4SDimitry Andric         MD, nullptr, None,
3822480093f4SDimitry Andric         TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3823480093f4SDimitry Andric   } else {
3824480093f4SDimitry Andric     assert(Spaceship->getFriendObjectKind() &&
3825480093f4SDimitry Andric            "defaulted spaceship is neither a member nor a friend");
3826480093f4SDimitry Andric 
3827480093f4SDimitry Andric     R = Instantiator.VisitFunctionDecl(
3828480093f4SDimitry Andric         Spaceship, nullptr,
3829480093f4SDimitry Andric         TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3830480093f4SDimitry Andric     if (!R)
3831480093f4SDimitry Andric       return nullptr;
3832480093f4SDimitry Andric 
3833480093f4SDimitry Andric     FriendDecl *FD =
3834480093f4SDimitry Andric         FriendDecl::Create(Context, RD, Spaceship->getLocation(),
3835480093f4SDimitry Andric                            cast<NamedDecl>(R), Spaceship->getBeginLoc());
3836480093f4SDimitry Andric     FD->setAccess(AS_public);
3837480093f4SDimitry Andric     RD->addDecl(FD);
3838480093f4SDimitry Andric   }
3839480093f4SDimitry Andric   return cast_or_null<FunctionDecl>(R);
3840480093f4SDimitry Andric }
3841480093f4SDimitry Andric 
38420b57cec5SDimitry Andric /// Instantiates a nested template parameter list in the current
38430b57cec5SDimitry Andric /// instantiation context.
38440b57cec5SDimitry Andric ///
38450b57cec5SDimitry Andric /// \param L The parameter list to instantiate
38460b57cec5SDimitry Andric ///
38470b57cec5SDimitry Andric /// \returns NULL if there was an error
38480b57cec5SDimitry Andric TemplateParameterList *
38490b57cec5SDimitry Andric TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
38500b57cec5SDimitry Andric   // Get errors for all the parameters before bailing out.
38510b57cec5SDimitry Andric   bool Invalid = false;
38520b57cec5SDimitry Andric 
38530b57cec5SDimitry Andric   unsigned N = L->size();
38540b57cec5SDimitry Andric   typedef SmallVector<NamedDecl *, 8> ParamVector;
38550b57cec5SDimitry Andric   ParamVector Params;
38560b57cec5SDimitry Andric   Params.reserve(N);
38570b57cec5SDimitry Andric   for (auto &P : *L) {
38580b57cec5SDimitry Andric     NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
38590b57cec5SDimitry Andric     Params.push_back(D);
38600b57cec5SDimitry Andric     Invalid = Invalid || !D || D->isInvalidDecl();
38610b57cec5SDimitry Andric   }
38620b57cec5SDimitry Andric 
38630b57cec5SDimitry Andric   // Clean up if we had an error.
38640b57cec5SDimitry Andric   if (Invalid)
38650b57cec5SDimitry Andric     return nullptr;
38660b57cec5SDimitry Andric 
3867a7dea167SDimitry Andric   // FIXME: Concepts: Substitution into requires clause should only happen when
3868a7dea167SDimitry Andric   // checking satisfaction.
3869a7dea167SDimitry Andric   Expr *InstRequiresClause = nullptr;
3870a7dea167SDimitry Andric   if (Expr *E = L->getRequiresClause()) {
387155e4f9d5SDimitry Andric     EnterExpressionEvaluationContext ConstantEvaluated(
387255e4f9d5SDimitry Andric         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
3873a7dea167SDimitry Andric     ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs);
3874a7dea167SDimitry Andric     if (Res.isInvalid() || !Res.isUsable()) {
3875a7dea167SDimitry Andric       return nullptr;
3876a7dea167SDimitry Andric     }
3877a7dea167SDimitry Andric     InstRequiresClause = Res.get();
3878a7dea167SDimitry Andric   }
38790b57cec5SDimitry Andric 
38800b57cec5SDimitry Andric   TemplateParameterList *InstL
38810b57cec5SDimitry Andric     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
38820b57cec5SDimitry Andric                                     L->getLAngleLoc(), Params,
3883a7dea167SDimitry Andric                                     L->getRAngleLoc(), InstRequiresClause);
38840b57cec5SDimitry Andric   return InstL;
38850b57cec5SDimitry Andric }
38860b57cec5SDimitry Andric 
38870b57cec5SDimitry Andric TemplateParameterList *
38880b57cec5SDimitry Andric Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
38890b57cec5SDimitry Andric                           const MultiLevelTemplateArgumentList &TemplateArgs) {
38900b57cec5SDimitry Andric   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
38910b57cec5SDimitry Andric   return Instantiator.SubstTemplateParams(Params);
38920b57cec5SDimitry Andric }
38930b57cec5SDimitry Andric 
38940b57cec5SDimitry Andric /// Instantiate the declaration of a class template partial
38950b57cec5SDimitry Andric /// specialization.
38960b57cec5SDimitry Andric ///
38970b57cec5SDimitry Andric /// \param ClassTemplate the (instantiated) class template that is partially
38980b57cec5SDimitry Andric // specialized by the instantiation of \p PartialSpec.
38990b57cec5SDimitry Andric ///
39000b57cec5SDimitry Andric /// \param PartialSpec the (uninstantiated) class template partial
39010b57cec5SDimitry Andric /// specialization that we are instantiating.
39020b57cec5SDimitry Andric ///
39030b57cec5SDimitry Andric /// \returns The instantiated partial specialization, if successful; otherwise,
39040b57cec5SDimitry Andric /// NULL to indicate an error.
39050b57cec5SDimitry Andric ClassTemplatePartialSpecializationDecl *
39060b57cec5SDimitry Andric TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
39070b57cec5SDimitry Andric                                             ClassTemplateDecl *ClassTemplate,
39080b57cec5SDimitry Andric                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
39090b57cec5SDimitry Andric   // Create a local instantiation scope for this class template partial
39100b57cec5SDimitry Andric   // specialization, which will contain the instantiations of the template
39110b57cec5SDimitry Andric   // parameters.
39120b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric   // Substitute into the template parameters of the class template partial
39150b57cec5SDimitry Andric   // specialization.
39160b57cec5SDimitry Andric   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
39170b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
39180b57cec5SDimitry Andric   if (!InstParams)
39190b57cec5SDimitry Andric     return nullptr;
39200b57cec5SDimitry Andric 
39210b57cec5SDimitry Andric   // Substitute into the template arguments of the class template partial
39220b57cec5SDimitry Andric   // specialization.
39230b57cec5SDimitry Andric   const ASTTemplateArgumentListInfo *TemplArgInfo
39240b57cec5SDimitry Andric     = PartialSpec->getTemplateArgsAsWritten();
39250b57cec5SDimitry Andric   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
39260b57cec5SDimitry Andric                                             TemplArgInfo->RAngleLoc);
39270b57cec5SDimitry Andric   if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
39280b57cec5SDimitry Andric                     TemplArgInfo->NumTemplateArgs,
39290b57cec5SDimitry Andric                     InstTemplateArgs, TemplateArgs))
39300b57cec5SDimitry Andric     return nullptr;
39310b57cec5SDimitry Andric 
39320b57cec5SDimitry Andric   // Check that the template argument list is well-formed for this
39330b57cec5SDimitry Andric   // class template.
39340b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Converted;
39350b57cec5SDimitry Andric   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
39360b57cec5SDimitry Andric                                         PartialSpec->getLocation(),
39370b57cec5SDimitry Andric                                         InstTemplateArgs,
39380b57cec5SDimitry Andric                                         false,
39390b57cec5SDimitry Andric                                         Converted))
39400b57cec5SDimitry Andric     return nullptr;
39410b57cec5SDimitry Andric 
39420b57cec5SDimitry Andric   // Check these arguments are valid for a template partial specialization.
39430b57cec5SDimitry Andric   if (SemaRef.CheckTemplatePartialSpecializationArgs(
39440b57cec5SDimitry Andric           PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
39450b57cec5SDimitry Andric           Converted))
39460b57cec5SDimitry Andric     return nullptr;
39470b57cec5SDimitry Andric 
39480b57cec5SDimitry Andric   // Figure out where to insert this class template partial specialization
39490b57cec5SDimitry Andric   // in the member template's set of class template partial specializations.
39500b57cec5SDimitry Andric   void *InsertPos = nullptr;
39510b57cec5SDimitry Andric   ClassTemplateSpecializationDecl *PrevDecl
3952480093f4SDimitry Andric     = ClassTemplate->findPartialSpecialization(Converted, InstParams,
3953480093f4SDimitry Andric                                                InsertPos);
39540b57cec5SDimitry Andric 
39550b57cec5SDimitry Andric   // Build the canonical type that describes the converted template
39560b57cec5SDimitry Andric   // arguments of the class template partial specialization.
39570b57cec5SDimitry Andric   QualType CanonType
39580b57cec5SDimitry Andric     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
39590b57cec5SDimitry Andric                                                     Converted);
39600b57cec5SDimitry Andric 
39610b57cec5SDimitry Andric   // Build the fully-sugared type for this class template
39620b57cec5SDimitry Andric   // specialization as the user wrote in the specialization
39630b57cec5SDimitry Andric   // itself. This means that we'll pretty-print the type retrieved
39640b57cec5SDimitry Andric   // from the specialization's declaration the way that the user
39650b57cec5SDimitry Andric   // actually wrote the specialization, rather than formatting the
39660b57cec5SDimitry Andric   // name based on the "canonical" representation used to store the
39670b57cec5SDimitry Andric   // template arguments in the specialization.
39680b57cec5SDimitry Andric   TypeSourceInfo *WrittenTy
39690b57cec5SDimitry Andric     = SemaRef.Context.getTemplateSpecializationTypeInfo(
39700b57cec5SDimitry Andric                                                     TemplateName(ClassTemplate),
39710b57cec5SDimitry Andric                                                     PartialSpec->getLocation(),
39720b57cec5SDimitry Andric                                                     InstTemplateArgs,
39730b57cec5SDimitry Andric                                                     CanonType);
39740b57cec5SDimitry Andric 
39750b57cec5SDimitry Andric   if (PrevDecl) {
39760b57cec5SDimitry Andric     // We've already seen a partial specialization with the same template
39770b57cec5SDimitry Andric     // parameters and template arguments. This can happen, for example, when
39780b57cec5SDimitry Andric     // substituting the outer template arguments ends up causing two
39790b57cec5SDimitry Andric     // class template partial specializations of a member class template
39800b57cec5SDimitry Andric     // to have identical forms, e.g.,
39810b57cec5SDimitry Andric     //
39820b57cec5SDimitry Andric     //   template<typename T, typename U>
39830b57cec5SDimitry Andric     //   struct Outer {
39840b57cec5SDimitry Andric     //     template<typename X, typename Y> struct Inner;
39850b57cec5SDimitry Andric     //     template<typename Y> struct Inner<T, Y>;
39860b57cec5SDimitry Andric     //     template<typename Y> struct Inner<U, Y>;
39870b57cec5SDimitry Andric     //   };
39880b57cec5SDimitry Andric     //
39890b57cec5SDimitry Andric     //   Outer<int, int> outer; // error: the partial specializations of Inner
39900b57cec5SDimitry Andric     //                          // have the same signature.
39910b57cec5SDimitry Andric     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
39920b57cec5SDimitry Andric       << WrittenTy->getType();
39930b57cec5SDimitry Andric     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
39940b57cec5SDimitry Andric       << SemaRef.Context.getTypeDeclType(PrevDecl);
39950b57cec5SDimitry Andric     return nullptr;
39960b57cec5SDimitry Andric   }
39970b57cec5SDimitry Andric 
39980b57cec5SDimitry Andric 
39990b57cec5SDimitry Andric   // Create the class template partial specialization declaration.
40000b57cec5SDimitry Andric   ClassTemplatePartialSpecializationDecl *InstPartialSpec =
40010b57cec5SDimitry Andric       ClassTemplatePartialSpecializationDecl::Create(
40020b57cec5SDimitry Andric           SemaRef.Context, PartialSpec->getTagKind(), Owner,
40030b57cec5SDimitry Andric           PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
40040b57cec5SDimitry Andric           ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
40050b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
40060b57cec5SDimitry Andric   if (SubstQualifier(PartialSpec, InstPartialSpec))
40070b57cec5SDimitry Andric     return nullptr;
40080b57cec5SDimitry Andric 
40090b57cec5SDimitry Andric   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
40100b57cec5SDimitry Andric   InstPartialSpec->setTypeAsWritten(WrittenTy);
40110b57cec5SDimitry Andric 
40120b57cec5SDimitry Andric   // Check the completed partial specialization.
40130b57cec5SDimitry Andric   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
40140b57cec5SDimitry Andric 
40150b57cec5SDimitry Andric   // Add this partial specialization to the set of class template partial
40160b57cec5SDimitry Andric   // specializations.
40170b57cec5SDimitry Andric   ClassTemplate->AddPartialSpecialization(InstPartialSpec,
40180b57cec5SDimitry Andric                                           /*InsertPos=*/nullptr);
40190b57cec5SDimitry Andric   return InstPartialSpec;
40200b57cec5SDimitry Andric }
40210b57cec5SDimitry Andric 
40220b57cec5SDimitry Andric /// Instantiate the declaration of a variable template partial
40230b57cec5SDimitry Andric /// specialization.
40240b57cec5SDimitry Andric ///
40250b57cec5SDimitry Andric /// \param VarTemplate the (instantiated) variable template that is partially
40260b57cec5SDimitry Andric /// specialized by the instantiation of \p PartialSpec.
40270b57cec5SDimitry Andric ///
40280b57cec5SDimitry Andric /// \param PartialSpec the (uninstantiated) variable template partial
40290b57cec5SDimitry Andric /// specialization that we are instantiating.
40300b57cec5SDimitry Andric ///
40310b57cec5SDimitry Andric /// \returns The instantiated partial specialization, if successful; otherwise,
40320b57cec5SDimitry Andric /// NULL to indicate an error.
40330b57cec5SDimitry Andric VarTemplatePartialSpecializationDecl *
40340b57cec5SDimitry Andric TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
40350b57cec5SDimitry Andric     VarTemplateDecl *VarTemplate,
40360b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *PartialSpec) {
40370b57cec5SDimitry Andric   // Create a local instantiation scope for this variable template partial
40380b57cec5SDimitry Andric   // specialization, which will contain the instantiations of the template
40390b57cec5SDimitry Andric   // parameters.
40400b57cec5SDimitry Andric   LocalInstantiationScope Scope(SemaRef);
40410b57cec5SDimitry Andric 
40420b57cec5SDimitry Andric   // Substitute into the template parameters of the variable template partial
40430b57cec5SDimitry Andric   // specialization.
40440b57cec5SDimitry Andric   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
40450b57cec5SDimitry Andric   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
40460b57cec5SDimitry Andric   if (!InstParams)
40470b57cec5SDimitry Andric     return nullptr;
40480b57cec5SDimitry Andric 
40490b57cec5SDimitry Andric   // Substitute into the template arguments of the variable template partial
40500b57cec5SDimitry Andric   // specialization.
40510b57cec5SDimitry Andric   const ASTTemplateArgumentListInfo *TemplArgInfo
40520b57cec5SDimitry Andric     = PartialSpec->getTemplateArgsAsWritten();
40530b57cec5SDimitry Andric   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
40540b57cec5SDimitry Andric                                             TemplArgInfo->RAngleLoc);
40550b57cec5SDimitry Andric   if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
40560b57cec5SDimitry Andric                     TemplArgInfo->NumTemplateArgs,
40570b57cec5SDimitry Andric                     InstTemplateArgs, TemplateArgs))
40580b57cec5SDimitry Andric     return nullptr;
40590b57cec5SDimitry Andric 
40600b57cec5SDimitry Andric   // Check that the template argument list is well-formed for this
40610b57cec5SDimitry Andric   // class template.
40620b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Converted;
40630b57cec5SDimitry Andric   if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
40640b57cec5SDimitry Andric                                         InstTemplateArgs, false, Converted))
40650b57cec5SDimitry Andric     return nullptr;
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric   // Check these arguments are valid for a template partial specialization.
40680b57cec5SDimitry Andric   if (SemaRef.CheckTemplatePartialSpecializationArgs(
40690b57cec5SDimitry Andric           PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
40700b57cec5SDimitry Andric           Converted))
40710b57cec5SDimitry Andric     return nullptr;
40720b57cec5SDimitry Andric 
40730b57cec5SDimitry Andric   // Figure out where to insert this variable template partial specialization
40740b57cec5SDimitry Andric   // in the member template's set of variable template partial specializations.
40750b57cec5SDimitry Andric   void *InsertPos = nullptr;
40760b57cec5SDimitry Andric   VarTemplateSpecializationDecl *PrevDecl =
4077480093f4SDimitry Andric       VarTemplate->findPartialSpecialization(Converted, InstParams, InsertPos);
40780b57cec5SDimitry Andric 
40790b57cec5SDimitry Andric   // Build the canonical type that describes the converted template
40800b57cec5SDimitry Andric   // arguments of the variable template partial specialization.
40810b57cec5SDimitry Andric   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
40820b57cec5SDimitry Andric       TemplateName(VarTemplate), Converted);
40830b57cec5SDimitry Andric 
40840b57cec5SDimitry Andric   // Build the fully-sugared type for this variable template
40850b57cec5SDimitry Andric   // specialization as the user wrote in the specialization
40860b57cec5SDimitry Andric   // itself. This means that we'll pretty-print the type retrieved
40870b57cec5SDimitry Andric   // from the specialization's declaration the way that the user
40880b57cec5SDimitry Andric   // actually wrote the specialization, rather than formatting the
40890b57cec5SDimitry Andric   // name based on the "canonical" representation used to store the
40900b57cec5SDimitry Andric   // template arguments in the specialization.
40910b57cec5SDimitry Andric   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
40920b57cec5SDimitry Andric       TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
40930b57cec5SDimitry Andric       CanonType);
40940b57cec5SDimitry Andric 
40950b57cec5SDimitry Andric   if (PrevDecl) {
40960b57cec5SDimitry Andric     // We've already seen a partial specialization with the same template
40970b57cec5SDimitry Andric     // parameters and template arguments. This can happen, for example, when
40980b57cec5SDimitry Andric     // substituting the outer template arguments ends up causing two
40990b57cec5SDimitry Andric     // variable template partial specializations of a member variable template
41000b57cec5SDimitry Andric     // to have identical forms, e.g.,
41010b57cec5SDimitry Andric     //
41020b57cec5SDimitry Andric     //   template<typename T, typename U>
41030b57cec5SDimitry Andric     //   struct Outer {
41040b57cec5SDimitry Andric     //     template<typename X, typename Y> pair<X,Y> p;
41050b57cec5SDimitry Andric     //     template<typename Y> pair<T, Y> p;
41060b57cec5SDimitry Andric     //     template<typename Y> pair<U, Y> p;
41070b57cec5SDimitry Andric     //   };
41080b57cec5SDimitry Andric     //
41090b57cec5SDimitry Andric     //   Outer<int, int> outer; // error: the partial specializations of Inner
41100b57cec5SDimitry Andric     //                          // have the same signature.
41110b57cec5SDimitry Andric     SemaRef.Diag(PartialSpec->getLocation(),
41120b57cec5SDimitry Andric                  diag::err_var_partial_spec_redeclared)
41130b57cec5SDimitry Andric         << WrittenTy->getType();
41140b57cec5SDimitry Andric     SemaRef.Diag(PrevDecl->getLocation(),
41150b57cec5SDimitry Andric                  diag::note_var_prev_partial_spec_here);
41160b57cec5SDimitry Andric     return nullptr;
41170b57cec5SDimitry Andric   }
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   // Do substitution on the type of the declaration
41200b57cec5SDimitry Andric   TypeSourceInfo *DI = SemaRef.SubstType(
41210b57cec5SDimitry Andric       PartialSpec->getTypeSourceInfo(), TemplateArgs,
41220b57cec5SDimitry Andric       PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
41230b57cec5SDimitry Andric   if (!DI)
41240b57cec5SDimitry Andric     return nullptr;
41250b57cec5SDimitry Andric 
41260b57cec5SDimitry Andric   if (DI->getType()->isFunctionType()) {
41270b57cec5SDimitry Andric     SemaRef.Diag(PartialSpec->getLocation(),
41280b57cec5SDimitry Andric                  diag::err_variable_instantiates_to_function)
41290b57cec5SDimitry Andric         << PartialSpec->isStaticDataMember() << DI->getType();
41300b57cec5SDimitry Andric     return nullptr;
41310b57cec5SDimitry Andric   }
41320b57cec5SDimitry Andric 
41330b57cec5SDimitry Andric   // Create the variable template partial specialization declaration.
41340b57cec5SDimitry Andric   VarTemplatePartialSpecializationDecl *InstPartialSpec =
41350b57cec5SDimitry Andric       VarTemplatePartialSpecializationDecl::Create(
41360b57cec5SDimitry Andric           SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
41370b57cec5SDimitry Andric           PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
41380b57cec5SDimitry Andric           DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
41390b57cec5SDimitry Andric 
41400b57cec5SDimitry Andric   // Substitute the nested name specifier, if any.
41410b57cec5SDimitry Andric   if (SubstQualifier(PartialSpec, InstPartialSpec))
41420b57cec5SDimitry Andric     return nullptr;
41430b57cec5SDimitry Andric 
41440b57cec5SDimitry Andric   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
41450b57cec5SDimitry Andric   InstPartialSpec->setTypeAsWritten(WrittenTy);
41460b57cec5SDimitry Andric 
41470b57cec5SDimitry Andric   // Check the completed partial specialization.
41480b57cec5SDimitry Andric   SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
41490b57cec5SDimitry Andric 
41500b57cec5SDimitry Andric   // Add this partial specialization to the set of variable template partial
41510b57cec5SDimitry Andric   // specializations. The instantiation of the initializer is not necessary.
41520b57cec5SDimitry Andric   VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
41530b57cec5SDimitry Andric 
41540b57cec5SDimitry Andric   SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
41550b57cec5SDimitry Andric                                      LateAttrs, Owner, StartingScope);
41560b57cec5SDimitry Andric 
41570b57cec5SDimitry Andric   return InstPartialSpec;
41580b57cec5SDimitry Andric }
41590b57cec5SDimitry Andric 
41600b57cec5SDimitry Andric TypeSourceInfo*
41610b57cec5SDimitry Andric TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
41620b57cec5SDimitry Andric                               SmallVectorImpl<ParmVarDecl *> &Params) {
41630b57cec5SDimitry Andric   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
41640b57cec5SDimitry Andric   assert(OldTInfo && "substituting function without type source info");
41650b57cec5SDimitry Andric   assert(Params.empty() && "parameter vector is non-empty at start");
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric   CXXRecordDecl *ThisContext = nullptr;
41680b57cec5SDimitry Andric   Qualifiers ThisTypeQuals;
41690b57cec5SDimitry Andric   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
41700b57cec5SDimitry Andric     ThisContext = cast<CXXRecordDecl>(Owner);
41710b57cec5SDimitry Andric     ThisTypeQuals = Method->getMethodQualifiers();
41720b57cec5SDimitry Andric   }
41730b57cec5SDimitry Andric 
41740b57cec5SDimitry Andric   TypeSourceInfo *NewTInfo
41750b57cec5SDimitry Andric     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
41760b57cec5SDimitry Andric                                     D->getTypeSpecStartLoc(),
41770b57cec5SDimitry Andric                                     D->getDeclName(),
41780b57cec5SDimitry Andric                                     ThisContext, ThisTypeQuals);
41790b57cec5SDimitry Andric   if (!NewTInfo)
41800b57cec5SDimitry Andric     return nullptr;
41810b57cec5SDimitry Andric 
41820b57cec5SDimitry Andric   TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
41830b57cec5SDimitry Andric   if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
41840b57cec5SDimitry Andric     if (NewTInfo != OldTInfo) {
41850b57cec5SDimitry Andric       // Get parameters from the new type info.
41860b57cec5SDimitry Andric       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
41870b57cec5SDimitry Andric       FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
41880b57cec5SDimitry Andric       unsigned NewIdx = 0;
41890b57cec5SDimitry Andric       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
41900b57cec5SDimitry Andric            OldIdx != NumOldParams; ++OldIdx) {
41910b57cec5SDimitry Andric         ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4192*e8d8bef9SDimitry Andric         if (!OldParam)
4193*e8d8bef9SDimitry Andric           return nullptr;
4194*e8d8bef9SDimitry Andric 
41950b57cec5SDimitry Andric         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
41960b57cec5SDimitry Andric 
41970b57cec5SDimitry Andric         Optional<unsigned> NumArgumentsInExpansion;
41980b57cec5SDimitry Andric         if (OldParam->isParameterPack())
41990b57cec5SDimitry Andric           NumArgumentsInExpansion =
42000b57cec5SDimitry Andric               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
42010b57cec5SDimitry Andric                                                  TemplateArgs);
42020b57cec5SDimitry Andric         if (!NumArgumentsInExpansion) {
42030b57cec5SDimitry Andric           // Simple case: normal parameter, or a parameter pack that's
42040b57cec5SDimitry Andric           // instantiated to a (still-dependent) parameter pack.
42050b57cec5SDimitry Andric           ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
42060b57cec5SDimitry Andric           Params.push_back(NewParam);
42070b57cec5SDimitry Andric           Scope->InstantiatedLocal(OldParam, NewParam);
42080b57cec5SDimitry Andric         } else {
42090b57cec5SDimitry Andric           // Parameter pack expansion: make the instantiation an argument pack.
42100b57cec5SDimitry Andric           Scope->MakeInstantiatedLocalArgPack(OldParam);
42110b57cec5SDimitry Andric           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
42120b57cec5SDimitry Andric             ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
42130b57cec5SDimitry Andric             Params.push_back(NewParam);
42140b57cec5SDimitry Andric             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
42150b57cec5SDimitry Andric           }
42160b57cec5SDimitry Andric         }
42170b57cec5SDimitry Andric       }
42180b57cec5SDimitry Andric     } else {
42190b57cec5SDimitry Andric       // The function type itself was not dependent and therefore no
42200b57cec5SDimitry Andric       // substitution occurred. However, we still need to instantiate
42210b57cec5SDimitry Andric       // the function parameters themselves.
42220b57cec5SDimitry Andric       const FunctionProtoType *OldProto =
42230b57cec5SDimitry Andric           cast<FunctionProtoType>(OldProtoLoc.getType());
42240b57cec5SDimitry Andric       for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
42250b57cec5SDimitry Andric            ++i) {
42260b57cec5SDimitry Andric         ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
42270b57cec5SDimitry Andric         if (!OldParam) {
42280b57cec5SDimitry Andric           Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
42290b57cec5SDimitry Andric               D, D->getLocation(), OldProto->getParamType(i)));
42300b57cec5SDimitry Andric           continue;
42310b57cec5SDimitry Andric         }
42320b57cec5SDimitry Andric 
42330b57cec5SDimitry Andric         ParmVarDecl *Parm =
42340b57cec5SDimitry Andric             cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
42350b57cec5SDimitry Andric         if (!Parm)
42360b57cec5SDimitry Andric           return nullptr;
42370b57cec5SDimitry Andric         Params.push_back(Parm);
42380b57cec5SDimitry Andric       }
42390b57cec5SDimitry Andric     }
42400b57cec5SDimitry Andric   } else {
42410b57cec5SDimitry Andric     // If the type of this function, after ignoring parentheses, is not
42420b57cec5SDimitry Andric     // *directly* a function type, then we're instantiating a function that
42430b57cec5SDimitry Andric     // was declared via a typedef or with attributes, e.g.,
42440b57cec5SDimitry Andric     //
42450b57cec5SDimitry Andric     //   typedef int functype(int, int);
42460b57cec5SDimitry Andric     //   functype func;
42470b57cec5SDimitry Andric     //   int __cdecl meth(int, int);
42480b57cec5SDimitry Andric     //
42490b57cec5SDimitry Andric     // In this case, we'll just go instantiate the ParmVarDecls that we
42500b57cec5SDimitry Andric     // synthesized in the method declaration.
42510b57cec5SDimitry Andric     SmallVector<QualType, 4> ParamTypes;
42520b57cec5SDimitry Andric     Sema::ExtParameterInfoBuilder ExtParamInfos;
42530b57cec5SDimitry Andric     if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
42540b57cec5SDimitry Andric                                TemplateArgs, ParamTypes, &Params,
42550b57cec5SDimitry Andric                                ExtParamInfos))
42560b57cec5SDimitry Andric       return nullptr;
42570b57cec5SDimitry Andric   }
42580b57cec5SDimitry Andric 
42590b57cec5SDimitry Andric   return NewTInfo;
42600b57cec5SDimitry Andric }
42610b57cec5SDimitry Andric 
42620b57cec5SDimitry Andric /// Introduce the instantiated function parameters into the local
42630b57cec5SDimitry Andric /// instantiation scope, and set the parameter names to those used
42640b57cec5SDimitry Andric /// in the template.
42650b57cec5SDimitry Andric static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
42660b57cec5SDimitry Andric                                              const FunctionDecl *PatternDecl,
42670b57cec5SDimitry Andric                                              LocalInstantiationScope &Scope,
42680b57cec5SDimitry Andric                            const MultiLevelTemplateArgumentList &TemplateArgs) {
42690b57cec5SDimitry Andric   unsigned FParamIdx = 0;
42700b57cec5SDimitry Andric   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
42710b57cec5SDimitry Andric     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
42720b57cec5SDimitry Andric     if (!PatternParam->isParameterPack()) {
42730b57cec5SDimitry Andric       // Simple case: not a parameter pack.
42740b57cec5SDimitry Andric       assert(FParamIdx < Function->getNumParams());
42750b57cec5SDimitry Andric       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
42760b57cec5SDimitry Andric       FunctionParam->setDeclName(PatternParam->getDeclName());
42770b57cec5SDimitry Andric       // If the parameter's type is not dependent, update it to match the type
42780b57cec5SDimitry Andric       // in the pattern. They can differ in top-level cv-qualifiers, and we want
42790b57cec5SDimitry Andric       // the pattern's type here. If the type is dependent, they can't differ,
42800b57cec5SDimitry Andric       // per core issue 1668. Substitute into the type from the pattern, in case
42810b57cec5SDimitry Andric       // it's instantiation-dependent.
42820b57cec5SDimitry Andric       // FIXME: Updating the type to work around this is at best fragile.
42830b57cec5SDimitry Andric       if (!PatternDecl->getType()->isDependentType()) {
42840b57cec5SDimitry Andric         QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
42850b57cec5SDimitry Andric                                  FunctionParam->getLocation(),
42860b57cec5SDimitry Andric                                  FunctionParam->getDeclName());
42870b57cec5SDimitry Andric         if (T.isNull())
42880b57cec5SDimitry Andric           return true;
42890b57cec5SDimitry Andric         FunctionParam->setType(T);
42900b57cec5SDimitry Andric       }
42910b57cec5SDimitry Andric 
42920b57cec5SDimitry Andric       Scope.InstantiatedLocal(PatternParam, FunctionParam);
42930b57cec5SDimitry Andric       ++FParamIdx;
42940b57cec5SDimitry Andric       continue;
42950b57cec5SDimitry Andric     }
42960b57cec5SDimitry Andric 
42970b57cec5SDimitry Andric     // Expand the parameter pack.
42980b57cec5SDimitry Andric     Scope.MakeInstantiatedLocalArgPack(PatternParam);
42990b57cec5SDimitry Andric     Optional<unsigned> NumArgumentsInExpansion
43000b57cec5SDimitry Andric       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
43010b57cec5SDimitry Andric     if (NumArgumentsInExpansion) {
43020b57cec5SDimitry Andric       QualType PatternType =
43030b57cec5SDimitry Andric           PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
43040b57cec5SDimitry Andric       for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
43050b57cec5SDimitry Andric         ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
43060b57cec5SDimitry Andric         FunctionParam->setDeclName(PatternParam->getDeclName());
43070b57cec5SDimitry Andric         if (!PatternDecl->getType()->isDependentType()) {
43080b57cec5SDimitry Andric           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
43090b57cec5SDimitry Andric           QualType T = S.SubstType(PatternType, TemplateArgs,
43100b57cec5SDimitry Andric                                    FunctionParam->getLocation(),
43110b57cec5SDimitry Andric                                    FunctionParam->getDeclName());
43120b57cec5SDimitry Andric           if (T.isNull())
43130b57cec5SDimitry Andric             return true;
43140b57cec5SDimitry Andric           FunctionParam->setType(T);
43150b57cec5SDimitry Andric         }
43160b57cec5SDimitry Andric 
43170b57cec5SDimitry Andric         Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
43180b57cec5SDimitry Andric         ++FParamIdx;
43190b57cec5SDimitry Andric       }
43200b57cec5SDimitry Andric     }
43210b57cec5SDimitry Andric   }
43220b57cec5SDimitry Andric 
43230b57cec5SDimitry Andric   return false;
43240b57cec5SDimitry Andric }
43250b57cec5SDimitry Andric 
43265ffd83dbSDimitry Andric bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
43275ffd83dbSDimitry Andric                                       ParmVarDecl *Param) {
43285ffd83dbSDimitry Andric   assert(Param->hasUninstantiatedDefaultArg());
43295ffd83dbSDimitry Andric   Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
43305ffd83dbSDimitry Andric 
43315ffd83dbSDimitry Andric   EnterExpressionEvaluationContext EvalContext(
43325ffd83dbSDimitry Andric       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
43335ffd83dbSDimitry Andric 
43345ffd83dbSDimitry Andric   // Instantiate the expression.
43355ffd83dbSDimitry Andric   //
43365ffd83dbSDimitry Andric   // FIXME: Pass in a correct Pattern argument, otherwise
43375ffd83dbSDimitry Andric   // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
43385ffd83dbSDimitry Andric   //
43395ffd83dbSDimitry Andric   // template<typename T>
43405ffd83dbSDimitry Andric   // struct A {
43415ffd83dbSDimitry Andric   //   static int FooImpl();
43425ffd83dbSDimitry Andric   //
43435ffd83dbSDimitry Andric   //   template<typename Tp>
43445ffd83dbSDimitry Andric   //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
43455ffd83dbSDimitry Andric   //   // template argument list [[T], [Tp]], should be [[Tp]].
43465ffd83dbSDimitry Andric   //   friend A<Tp> Foo(int a);
43475ffd83dbSDimitry Andric   // };
43485ffd83dbSDimitry Andric   //
43495ffd83dbSDimitry Andric   // template<typename T>
43505ffd83dbSDimitry Andric   // A<T> Foo(int a = A<T>::FooImpl());
43515ffd83dbSDimitry Andric   MultiLevelTemplateArgumentList TemplateArgs
43525ffd83dbSDimitry Andric     = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
43535ffd83dbSDimitry Andric 
43545ffd83dbSDimitry Andric   InstantiatingTemplate Inst(*this, CallLoc, Param,
43555ffd83dbSDimitry Andric                              TemplateArgs.getInnermost());
43565ffd83dbSDimitry Andric   if (Inst.isInvalid())
43575ffd83dbSDimitry Andric     return true;
43585ffd83dbSDimitry Andric   if (Inst.isAlreadyInstantiating()) {
43595ffd83dbSDimitry Andric     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
43605ffd83dbSDimitry Andric     Param->setInvalidDecl();
43615ffd83dbSDimitry Andric     return true;
43625ffd83dbSDimitry Andric   }
43635ffd83dbSDimitry Andric 
43645ffd83dbSDimitry Andric   ExprResult Result;
43655ffd83dbSDimitry Andric   {
43665ffd83dbSDimitry Andric     // C++ [dcl.fct.default]p5:
43675ffd83dbSDimitry Andric     //   The names in the [default argument] expression are bound, and
43685ffd83dbSDimitry Andric     //   the semantic constraints are checked, at the point where the
43695ffd83dbSDimitry Andric     //   default argument expression appears.
43705ffd83dbSDimitry Andric     ContextRAII SavedContext(*this, FD);
43715ffd83dbSDimitry Andric     LocalInstantiationScope Local(*this);
43725ffd83dbSDimitry Andric 
43735ffd83dbSDimitry Andric     FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(
43745ffd83dbSDimitry Andric         /*ForDefinition*/ false);
43755ffd83dbSDimitry Andric     if (addInstantiatedParametersToScope(*this, FD, Pattern, Local,
43765ffd83dbSDimitry Andric                                          TemplateArgs))
43775ffd83dbSDimitry Andric       return true;
43785ffd83dbSDimitry Andric 
43795ffd83dbSDimitry Andric     runWithSufficientStackSpace(CallLoc, [&] {
43805ffd83dbSDimitry Andric       Result = SubstInitializer(UninstExpr, TemplateArgs,
43815ffd83dbSDimitry Andric                                 /*DirectInit*/false);
43825ffd83dbSDimitry Andric     });
43835ffd83dbSDimitry Andric   }
43845ffd83dbSDimitry Andric   if (Result.isInvalid())
43855ffd83dbSDimitry Andric     return true;
43865ffd83dbSDimitry Andric 
43875ffd83dbSDimitry Andric   // Check the expression as an initializer for the parameter.
43885ffd83dbSDimitry Andric   InitializedEntity Entity
43895ffd83dbSDimitry Andric     = InitializedEntity::InitializeParameter(Context, Param);
43905ffd83dbSDimitry Andric   InitializationKind Kind = InitializationKind::CreateCopy(
43915ffd83dbSDimitry Andric       Param->getLocation(),
43925ffd83dbSDimitry Andric       /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
43935ffd83dbSDimitry Andric   Expr *ResultE = Result.getAs<Expr>();
43945ffd83dbSDimitry Andric 
43955ffd83dbSDimitry Andric   InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
43965ffd83dbSDimitry Andric   Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
43975ffd83dbSDimitry Andric   if (Result.isInvalid())
43985ffd83dbSDimitry Andric     return true;
43995ffd83dbSDimitry Andric 
44005ffd83dbSDimitry Andric   Result =
44015ffd83dbSDimitry Andric       ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
44025ffd83dbSDimitry Andric                           /*DiscardedValue*/ false);
44035ffd83dbSDimitry Andric   if (Result.isInvalid())
44045ffd83dbSDimitry Andric     return true;
44055ffd83dbSDimitry Andric 
44065ffd83dbSDimitry Andric   // Remember the instantiated default argument.
44075ffd83dbSDimitry Andric   Param->setDefaultArg(Result.getAs<Expr>());
44085ffd83dbSDimitry Andric   if (ASTMutationListener *L = getASTMutationListener())
44095ffd83dbSDimitry Andric     L->DefaultArgumentInstantiated(Param);
44105ffd83dbSDimitry Andric 
44115ffd83dbSDimitry Andric   return false;
44125ffd83dbSDimitry Andric }
44135ffd83dbSDimitry Andric 
44140b57cec5SDimitry Andric void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
44150b57cec5SDimitry Andric                                     FunctionDecl *Decl) {
44160b57cec5SDimitry Andric   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
44170b57cec5SDimitry Andric   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
44180b57cec5SDimitry Andric     return;
44190b57cec5SDimitry Andric 
44200b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
44210b57cec5SDimitry Andric                              InstantiatingTemplate::ExceptionSpecification());
44220b57cec5SDimitry Andric   if (Inst.isInvalid()) {
44230b57cec5SDimitry Andric     // We hit the instantiation depth limit. Clear the exception specification
44240b57cec5SDimitry Andric     // so that our callers don't have to cope with EST_Uninstantiated.
44250b57cec5SDimitry Andric     UpdateExceptionSpec(Decl, EST_None);
44260b57cec5SDimitry Andric     return;
44270b57cec5SDimitry Andric   }
44280b57cec5SDimitry Andric   if (Inst.isAlreadyInstantiating()) {
44290b57cec5SDimitry Andric     // This exception specification indirectly depends on itself. Reject.
44300b57cec5SDimitry Andric     // FIXME: Corresponding rule in the standard?
44310b57cec5SDimitry Andric     Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
44320b57cec5SDimitry Andric     UpdateExceptionSpec(Decl, EST_None);
44330b57cec5SDimitry Andric     return;
44340b57cec5SDimitry Andric   }
44350b57cec5SDimitry Andric 
44360b57cec5SDimitry Andric   // Enter the scope of this instantiation. We don't use
44370b57cec5SDimitry Andric   // PushDeclContext because we don't have a scope.
44380b57cec5SDimitry Andric   Sema::ContextRAII savedContext(*this, Decl);
44390b57cec5SDimitry Andric   LocalInstantiationScope Scope(*this);
44400b57cec5SDimitry Andric 
44410b57cec5SDimitry Andric   MultiLevelTemplateArgumentList TemplateArgs =
44420b57cec5SDimitry Andric     getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
44430b57cec5SDimitry Andric 
44445ffd83dbSDimitry Andric   // FIXME: We can't use getTemplateInstantiationPattern(false) in general
44455ffd83dbSDimitry Andric   // here, because for a non-defining friend declaration in a class template,
44465ffd83dbSDimitry Andric   // we don't store enough information to map back to the friend declaration in
44475ffd83dbSDimitry Andric   // the template.
44480b57cec5SDimitry Andric   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
44490b57cec5SDimitry Andric   if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
44500b57cec5SDimitry Andric                                        TemplateArgs)) {
44510b57cec5SDimitry Andric     UpdateExceptionSpec(Decl, EST_None);
44520b57cec5SDimitry Andric     return;
44530b57cec5SDimitry Andric   }
44540b57cec5SDimitry Andric 
44550b57cec5SDimitry Andric   SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
44560b57cec5SDimitry Andric                      TemplateArgs);
44570b57cec5SDimitry Andric }
44580b57cec5SDimitry Andric 
4459480093f4SDimitry Andric bool Sema::CheckInstantiatedFunctionTemplateConstraints(
4460480093f4SDimitry Andric     SourceLocation PointOfInstantiation, FunctionDecl *Decl,
4461480093f4SDimitry Andric     ArrayRef<TemplateArgument> TemplateArgs,
4462480093f4SDimitry Andric     ConstraintSatisfaction &Satisfaction) {
4463480093f4SDimitry Andric   // In most cases we're not going to have constraints, so check for that first.
4464480093f4SDimitry Andric   FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
4465480093f4SDimitry Andric   // Note - code synthesis context for the constraints check is created
4466480093f4SDimitry Andric   // inside CheckConstraintsSatisfaction.
4467480093f4SDimitry Andric   SmallVector<const Expr *, 3> TemplateAC;
4468480093f4SDimitry Andric   Template->getAssociatedConstraints(TemplateAC);
4469480093f4SDimitry Andric   if (TemplateAC.empty()) {
4470480093f4SDimitry Andric     Satisfaction.IsSatisfied = true;
4471480093f4SDimitry Andric     return false;
4472480093f4SDimitry Andric   }
4473480093f4SDimitry Andric 
4474480093f4SDimitry Andric   // Enter the scope of this instantiation. We don't use
4475480093f4SDimitry Andric   // PushDeclContext because we don't have a scope.
4476480093f4SDimitry Andric   Sema::ContextRAII savedContext(*this, Decl);
4477480093f4SDimitry Andric   LocalInstantiationScope Scope(*this);
4478480093f4SDimitry Andric 
4479480093f4SDimitry Andric   // If this is not an explicit specialization - we need to get the instantiated
4480480093f4SDimitry Andric   // version of the template arguments and add them to scope for the
4481480093f4SDimitry Andric   // substitution.
4482480093f4SDimitry Andric   if (Decl->isTemplateInstantiation()) {
4483480093f4SDimitry Andric     InstantiatingTemplate Inst(*this, Decl->getPointOfInstantiation(),
4484480093f4SDimitry Andric         InstantiatingTemplate::ConstraintsCheck{}, Decl->getPrimaryTemplate(),
448513138422SDimitry Andric         TemplateArgs, SourceRange());
4486480093f4SDimitry Andric     if (Inst.isInvalid())
4487480093f4SDimitry Andric       return true;
448813138422SDimitry Andric     MultiLevelTemplateArgumentList MLTAL(
448913138422SDimitry Andric         *Decl->getTemplateSpecializationArgs());
449055e4f9d5SDimitry Andric     if (addInstantiatedParametersToScope(
449155e4f9d5SDimitry Andric             *this, Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(),
4492480093f4SDimitry Andric             Scope, MLTAL))
4493480093f4SDimitry Andric       return true;
4494480093f4SDimitry Andric   }
449513138422SDimitry Andric   Qualifiers ThisQuals;
449613138422SDimitry Andric   CXXRecordDecl *Record = nullptr;
449713138422SDimitry Andric   if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
449813138422SDimitry Andric     ThisQuals = Method->getMethodQualifiers();
449913138422SDimitry Andric     Record = Method->getParent();
450013138422SDimitry Andric   }
450113138422SDimitry Andric   CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
4502480093f4SDimitry Andric   return CheckConstraintSatisfaction(Template, TemplateAC, TemplateArgs,
4503480093f4SDimitry Andric                                      PointOfInstantiation, Satisfaction);
4504480093f4SDimitry Andric }
4505480093f4SDimitry Andric 
45060b57cec5SDimitry Andric /// Initializes the common fields of an instantiation function
45070b57cec5SDimitry Andric /// declaration (New) from the corresponding fields of its template (Tmpl).
45080b57cec5SDimitry Andric ///
45090b57cec5SDimitry Andric /// \returns true if there was an error
45100b57cec5SDimitry Andric bool
45110b57cec5SDimitry Andric TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
45120b57cec5SDimitry Andric                                                     FunctionDecl *Tmpl) {
45130b57cec5SDimitry Andric   New->setImplicit(Tmpl->isImplicit());
45140b57cec5SDimitry Andric 
45150b57cec5SDimitry Andric   // Forward the mangling number from the template to the instantiated decl.
45160b57cec5SDimitry Andric   SemaRef.Context.setManglingNumber(New,
45170b57cec5SDimitry Andric                                     SemaRef.Context.getManglingNumber(Tmpl));
45180b57cec5SDimitry Andric 
45190b57cec5SDimitry Andric   // If we are performing substituting explicitly-specified template arguments
45200b57cec5SDimitry Andric   // or deduced template arguments into a function template and we reach this
45210b57cec5SDimitry Andric   // point, we are now past the point where SFINAE applies and have committed
45220b57cec5SDimitry Andric   // to keeping the new function template specialization. We therefore
45230b57cec5SDimitry Andric   // convert the active template instantiation for the function template
45240b57cec5SDimitry Andric   // into a template instantiation for this specific function template
45250b57cec5SDimitry Andric   // specialization, which is not a SFINAE context, so that we diagnose any
45260b57cec5SDimitry Andric   // further errors in the declaration itself.
4527*e8d8bef9SDimitry Andric   //
4528*e8d8bef9SDimitry Andric   // FIXME: This is a hack.
45290b57cec5SDimitry Andric   typedef Sema::CodeSynthesisContext ActiveInstType;
45300b57cec5SDimitry Andric   ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
45310b57cec5SDimitry Andric   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
45320b57cec5SDimitry Andric       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
45330b57cec5SDimitry Andric     if (FunctionTemplateDecl *FunTmpl
45340b57cec5SDimitry Andric           = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
45350b57cec5SDimitry Andric       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
45360b57cec5SDimitry Andric              "Deduction from the wrong function template?");
45370b57cec5SDimitry Andric       (void) FunTmpl;
4538*e8d8bef9SDimitry Andric       SemaRef.InstantiatingSpecializations.erase(
4539*e8d8bef9SDimitry Andric           {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
45400b57cec5SDimitry Andric       atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
45410b57cec5SDimitry Andric       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
45420b57cec5SDimitry Andric       ActiveInst.Entity = New;
45430b57cec5SDimitry Andric       atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
45440b57cec5SDimitry Andric     }
45450b57cec5SDimitry Andric   }
45460b57cec5SDimitry Andric 
45470b57cec5SDimitry Andric   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
45480b57cec5SDimitry Andric   assert(Proto && "Function template without prototype?");
45490b57cec5SDimitry Andric 
45500b57cec5SDimitry Andric   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
45510b57cec5SDimitry Andric     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
45520b57cec5SDimitry Andric 
45530b57cec5SDimitry Andric     // DR1330: In C++11, defer instantiation of a non-trivial
45540b57cec5SDimitry Andric     // exception specification.
45550b57cec5SDimitry Andric     // DR1484: Local classes and their members are instantiated along with the
45560b57cec5SDimitry Andric     // containing function.
45570b57cec5SDimitry Andric     if (SemaRef.getLangOpts().CPlusPlus11 &&
45580b57cec5SDimitry Andric         EPI.ExceptionSpec.Type != EST_None &&
45590b57cec5SDimitry Andric         EPI.ExceptionSpec.Type != EST_DynamicNone &&
45600b57cec5SDimitry Andric         EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
45615ffd83dbSDimitry Andric         !Tmpl->isInLocalScopeForInstantiation()) {
45620b57cec5SDimitry Andric       FunctionDecl *ExceptionSpecTemplate = Tmpl;
45630b57cec5SDimitry Andric       if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
45640b57cec5SDimitry Andric         ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
45650b57cec5SDimitry Andric       ExceptionSpecificationType NewEST = EST_Uninstantiated;
45660b57cec5SDimitry Andric       if (EPI.ExceptionSpec.Type == EST_Unevaluated)
45670b57cec5SDimitry Andric         NewEST = EST_Unevaluated;
45680b57cec5SDimitry Andric 
45690b57cec5SDimitry Andric       // Mark the function has having an uninstantiated exception specification.
45700b57cec5SDimitry Andric       const FunctionProtoType *NewProto
45710b57cec5SDimitry Andric         = New->getType()->getAs<FunctionProtoType>();
45720b57cec5SDimitry Andric       assert(NewProto && "Template instantiation without function prototype?");
45730b57cec5SDimitry Andric       EPI = NewProto->getExtProtoInfo();
45740b57cec5SDimitry Andric       EPI.ExceptionSpec.Type = NewEST;
45750b57cec5SDimitry Andric       EPI.ExceptionSpec.SourceDecl = New;
45760b57cec5SDimitry Andric       EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
45770b57cec5SDimitry Andric       New->setType(SemaRef.Context.getFunctionType(
45780b57cec5SDimitry Andric           NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
45790b57cec5SDimitry Andric     } else {
45800b57cec5SDimitry Andric       Sema::ContextRAII SwitchContext(SemaRef, New);
45810b57cec5SDimitry Andric       SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
45820b57cec5SDimitry Andric     }
45830b57cec5SDimitry Andric   }
45840b57cec5SDimitry Andric 
45850b57cec5SDimitry Andric   // Get the definition. Leaves the variable unchanged if undefined.
45860b57cec5SDimitry Andric   const FunctionDecl *Definition = Tmpl;
45870b57cec5SDimitry Andric   Tmpl->isDefined(Definition);
45880b57cec5SDimitry Andric 
45890b57cec5SDimitry Andric   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
45900b57cec5SDimitry Andric                            LateAttrs, StartingScope);
45910b57cec5SDimitry Andric 
45920b57cec5SDimitry Andric   return false;
45930b57cec5SDimitry Andric }
45940b57cec5SDimitry Andric 
45950b57cec5SDimitry Andric /// Initializes common fields of an instantiated method
45960b57cec5SDimitry Andric /// declaration (New) from the corresponding fields of its template
45970b57cec5SDimitry Andric /// (Tmpl).
45980b57cec5SDimitry Andric ///
45990b57cec5SDimitry Andric /// \returns true if there was an error
46000b57cec5SDimitry Andric bool
46010b57cec5SDimitry Andric TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
46020b57cec5SDimitry Andric                                                   CXXMethodDecl *Tmpl) {
46030b57cec5SDimitry Andric   if (InitFunctionInstantiation(New, Tmpl))
46040b57cec5SDimitry Andric     return true;
46050b57cec5SDimitry Andric 
46060b57cec5SDimitry Andric   if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
46070b57cec5SDimitry Andric     SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
46080b57cec5SDimitry Andric 
46090b57cec5SDimitry Andric   New->setAccess(Tmpl->getAccess());
46100b57cec5SDimitry Andric   if (Tmpl->isVirtualAsWritten())
46110b57cec5SDimitry Andric     New->setVirtualAsWritten(true);
46120b57cec5SDimitry Andric 
46130b57cec5SDimitry Andric   // FIXME: New needs a pointer to Tmpl
46140b57cec5SDimitry Andric   return false;
46150b57cec5SDimitry Andric }
46160b57cec5SDimitry Andric 
4617480093f4SDimitry Andric bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4618480093f4SDimitry Andric                                                       FunctionDecl *Tmpl) {
4619480093f4SDimitry Andric   // Transfer across any unqualified lookups.
4620480093f4SDimitry Andric   if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4621480093f4SDimitry Andric     SmallVector<DeclAccessPair, 32> Lookups;
4622480093f4SDimitry Andric     Lookups.reserve(DFI->getUnqualifiedLookups().size());
4623480093f4SDimitry Andric     bool AnyChanged = false;
4624480093f4SDimitry Andric     for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4625480093f4SDimitry Andric       NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4626480093f4SDimitry Andric                                                   DA.getDecl(), TemplateArgs);
4627480093f4SDimitry Andric       if (!D)
4628480093f4SDimitry Andric         return true;
4629480093f4SDimitry Andric       AnyChanged |= (D != DA.getDecl());
4630480093f4SDimitry Andric       Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4631480093f4SDimitry Andric     }
4632480093f4SDimitry Andric 
4633480093f4SDimitry Andric     // It's unlikely that substitution will change any declarations. Don't
4634480093f4SDimitry Andric     // store an unnecessary copy in that case.
4635480093f4SDimitry Andric     New->setDefaultedFunctionInfo(
4636480093f4SDimitry Andric         AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4637480093f4SDimitry Andric                          SemaRef.Context, Lookups)
4638480093f4SDimitry Andric                    : DFI);
4639480093f4SDimitry Andric   }
4640480093f4SDimitry Andric 
4641480093f4SDimitry Andric   SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4642480093f4SDimitry Andric   return false;
4643480093f4SDimitry Andric }
4644480093f4SDimitry Andric 
46450b57cec5SDimitry Andric /// Instantiate (or find existing instantiation of) a function template with a
46460b57cec5SDimitry Andric /// given set of template arguments.
46470b57cec5SDimitry Andric ///
46480b57cec5SDimitry Andric /// Usually this should not be used, and template argument deduction should be
46490b57cec5SDimitry Andric /// used in its place.
46500b57cec5SDimitry Andric FunctionDecl *
46510b57cec5SDimitry Andric Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
46520b57cec5SDimitry Andric                                      const TemplateArgumentList *Args,
46530b57cec5SDimitry Andric                                      SourceLocation Loc) {
46540b57cec5SDimitry Andric   FunctionDecl *FD = FTD->getTemplatedDecl();
46550b57cec5SDimitry Andric 
46560b57cec5SDimitry Andric   sema::TemplateDeductionInfo Info(Loc);
46570b57cec5SDimitry Andric   InstantiatingTemplate Inst(
46580b57cec5SDimitry Andric       *this, Loc, FTD, Args->asArray(),
46590b57cec5SDimitry Andric       CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
46600b57cec5SDimitry Andric   if (Inst.isInvalid())
46610b57cec5SDimitry Andric     return nullptr;
46620b57cec5SDimitry Andric 
46630b57cec5SDimitry Andric   ContextRAII SavedContext(*this, FD);
46640b57cec5SDimitry Andric   MultiLevelTemplateArgumentList MArgs(*Args);
46650b57cec5SDimitry Andric 
46660b57cec5SDimitry Andric   return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
46670b57cec5SDimitry Andric }
46680b57cec5SDimitry Andric 
46690b57cec5SDimitry Andric /// Instantiate the definition of the given function from its
46700b57cec5SDimitry Andric /// template.
46710b57cec5SDimitry Andric ///
46720b57cec5SDimitry Andric /// \param PointOfInstantiation the point at which the instantiation was
46730b57cec5SDimitry Andric /// required. Note that this is not precisely a "point of instantiation"
46740b57cec5SDimitry Andric /// for the function, but it's close.
46750b57cec5SDimitry Andric ///
46760b57cec5SDimitry Andric /// \param Function the already-instantiated declaration of a
46770b57cec5SDimitry Andric /// function template specialization or member function of a class template
46780b57cec5SDimitry Andric /// specialization.
46790b57cec5SDimitry Andric ///
46800b57cec5SDimitry Andric /// \param Recursive if true, recursively instantiates any functions that
46810b57cec5SDimitry Andric /// are required by this instantiation.
46820b57cec5SDimitry Andric ///
46830b57cec5SDimitry Andric /// \param DefinitionRequired if true, then we are performing an explicit
46840b57cec5SDimitry Andric /// instantiation where the body of the function is required. Complain if
46850b57cec5SDimitry Andric /// there is no such body.
46860b57cec5SDimitry Andric void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
46870b57cec5SDimitry Andric                                          FunctionDecl *Function,
46880b57cec5SDimitry Andric                                          bool Recursive,
46890b57cec5SDimitry Andric                                          bool DefinitionRequired,
46900b57cec5SDimitry Andric                                          bool AtEndOfTU) {
4691*e8d8bef9SDimitry Andric   if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
46920b57cec5SDimitry Andric     return;
46930b57cec5SDimitry Andric 
46940b57cec5SDimitry Andric   // Never instantiate an explicit specialization except if it is a class scope
46950b57cec5SDimitry Andric   // explicit specialization.
46960b57cec5SDimitry Andric   TemplateSpecializationKind TSK =
46970b57cec5SDimitry Andric       Function->getTemplateSpecializationKindForInstantiation();
46980b57cec5SDimitry Andric   if (TSK == TSK_ExplicitSpecialization)
46990b57cec5SDimitry Andric     return;
47000b57cec5SDimitry Andric 
4701*e8d8bef9SDimitry Andric   // Don't instantiate a definition if we already have one.
4702*e8d8bef9SDimitry Andric   const FunctionDecl *ExistingDefn = nullptr;
4703*e8d8bef9SDimitry Andric   if (Function->isDefined(ExistingDefn,
4704*e8d8bef9SDimitry Andric                           /*CheckForPendingFriendDefinition=*/true)) {
4705*e8d8bef9SDimitry Andric     if (ExistingDefn->isThisDeclarationADefinition())
4706*e8d8bef9SDimitry Andric       return;
4707*e8d8bef9SDimitry Andric 
4708*e8d8bef9SDimitry Andric     // If we're asked to instantiate a function whose body comes from an
4709*e8d8bef9SDimitry Andric     // instantiated friend declaration, attach the instantiated body to the
4710*e8d8bef9SDimitry Andric     // corresponding declaration of the function.
4711*e8d8bef9SDimitry Andric     assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition());
4712*e8d8bef9SDimitry Andric     Function = const_cast<FunctionDecl*>(ExistingDefn);
4713*e8d8bef9SDimitry Andric   }
4714*e8d8bef9SDimitry Andric 
47150b57cec5SDimitry Andric   // Find the function body that we'll be substituting.
47160b57cec5SDimitry Andric   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
47170b57cec5SDimitry Andric   assert(PatternDecl && "instantiating a non-template");
47180b57cec5SDimitry Andric 
47190b57cec5SDimitry Andric   const FunctionDecl *PatternDef = PatternDecl->getDefinition();
47200b57cec5SDimitry Andric   Stmt *Pattern = nullptr;
47210b57cec5SDimitry Andric   if (PatternDef) {
47220b57cec5SDimitry Andric     Pattern = PatternDef->getBody(PatternDef);
47230b57cec5SDimitry Andric     PatternDecl = PatternDef;
47240b57cec5SDimitry Andric     if (PatternDef->willHaveBody())
47250b57cec5SDimitry Andric       PatternDef = nullptr;
47260b57cec5SDimitry Andric   }
47270b57cec5SDimitry Andric 
47280b57cec5SDimitry Andric   // FIXME: We need to track the instantiation stack in order to know which
47290b57cec5SDimitry Andric   // definitions should be visible within this instantiation.
47300b57cec5SDimitry Andric   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
47310b57cec5SDimitry Andric                                 Function->getInstantiatedFromMemberFunction(),
47320b57cec5SDimitry Andric                                      PatternDecl, PatternDef, TSK,
47330b57cec5SDimitry Andric                                      /*Complain*/DefinitionRequired)) {
47340b57cec5SDimitry Andric     if (DefinitionRequired)
47350b57cec5SDimitry Andric       Function->setInvalidDecl();
47360b57cec5SDimitry Andric     else if (TSK == TSK_ExplicitInstantiationDefinition) {
47370b57cec5SDimitry Andric       // Try again at the end of the translation unit (at which point a
47380b57cec5SDimitry Andric       // definition will be required).
47390b57cec5SDimitry Andric       assert(!Recursive);
47400b57cec5SDimitry Andric       Function->setInstantiationIsPending(true);
47410b57cec5SDimitry Andric       PendingInstantiations.push_back(
47420b57cec5SDimitry Andric         std::make_pair(Function, PointOfInstantiation));
47430b57cec5SDimitry Andric     } else if (TSK == TSK_ImplicitInstantiation) {
47440b57cec5SDimitry Andric       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
47450b57cec5SDimitry Andric           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
47460b57cec5SDimitry Andric         Diag(PointOfInstantiation, diag::warn_func_template_missing)
47470b57cec5SDimitry Andric           << Function;
47480b57cec5SDimitry Andric         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
47490b57cec5SDimitry Andric         if (getLangOpts().CPlusPlus11)
47500b57cec5SDimitry Andric           Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
47510b57cec5SDimitry Andric             << Function;
47520b57cec5SDimitry Andric       }
47530b57cec5SDimitry Andric     }
47540b57cec5SDimitry Andric 
47550b57cec5SDimitry Andric     return;
47560b57cec5SDimitry Andric   }
47570b57cec5SDimitry Andric 
47580b57cec5SDimitry Andric   // Postpone late parsed template instantiations.
47590b57cec5SDimitry Andric   if (PatternDecl->isLateTemplateParsed() &&
47600b57cec5SDimitry Andric       !LateTemplateParser) {
47610b57cec5SDimitry Andric     Function->setInstantiationIsPending(true);
47620b57cec5SDimitry Andric     LateParsedInstantiations.push_back(
47630b57cec5SDimitry Andric         std::make_pair(Function, PointOfInstantiation));
47640b57cec5SDimitry Andric     return;
47650b57cec5SDimitry Andric   }
47660b57cec5SDimitry Andric 
47670b57cec5SDimitry Andric   llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
47680b57cec5SDimitry Andric     std::string Name;
47690b57cec5SDimitry Andric     llvm::raw_string_ostream OS(Name);
47700b57cec5SDimitry Andric     Function->getNameForDiagnostic(OS, getPrintingPolicy(),
47710b57cec5SDimitry Andric                                    /*Qualified=*/true);
47720b57cec5SDimitry Andric     return Name;
47730b57cec5SDimitry Andric   });
47740b57cec5SDimitry Andric 
47750b57cec5SDimitry Andric   // If we're performing recursive template instantiation, create our own
47760b57cec5SDimitry Andric   // queue of pending implicit instantiations that we will instantiate later,
47770b57cec5SDimitry Andric   // while we're still within our own instantiation context.
47780b57cec5SDimitry Andric   // This has to happen before LateTemplateParser below is called, so that
47790b57cec5SDimitry Andric   // it marks vtables used in late parsed templates as used.
47800b57cec5SDimitry Andric   GlobalEagerInstantiationScope GlobalInstantiations(*this,
47810b57cec5SDimitry Andric                                                      /*Enabled=*/Recursive);
47820b57cec5SDimitry Andric   LocalEagerInstantiationScope LocalInstantiations(*this);
47830b57cec5SDimitry Andric 
47840b57cec5SDimitry Andric   // Call the LateTemplateParser callback if there is a need to late parse
47850b57cec5SDimitry Andric   // a templated function definition.
47860b57cec5SDimitry Andric   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
47870b57cec5SDimitry Andric       LateTemplateParser) {
47880b57cec5SDimitry Andric     // FIXME: Optimize to allow individual templates to be deserialized.
47890b57cec5SDimitry Andric     if (PatternDecl->isFromASTFile())
47900b57cec5SDimitry Andric       ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
47910b57cec5SDimitry Andric 
47920b57cec5SDimitry Andric     auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
47930b57cec5SDimitry Andric     assert(LPTIter != LateParsedTemplateMap.end() &&
47940b57cec5SDimitry Andric            "missing LateParsedTemplate");
47950b57cec5SDimitry Andric     LateTemplateParser(OpaqueParser, *LPTIter->second);
47960b57cec5SDimitry Andric     Pattern = PatternDecl->getBody(PatternDecl);
47970b57cec5SDimitry Andric   }
47980b57cec5SDimitry Andric 
47990b57cec5SDimitry Andric   // Note, we should never try to instantiate a deleted function template.
48000b57cec5SDimitry Andric   assert((Pattern || PatternDecl->isDefaulted() ||
48010b57cec5SDimitry Andric           PatternDecl->hasSkippedBody()) &&
48020b57cec5SDimitry Andric          "unexpected kind of function template definition");
48030b57cec5SDimitry Andric 
48040b57cec5SDimitry Andric   // C++1y [temp.explicit]p10:
48050b57cec5SDimitry Andric   //   Except for inline functions, declarations with types deduced from their
48060b57cec5SDimitry Andric   //   initializer or return value, and class template specializations, other
48070b57cec5SDimitry Andric   //   explicit instantiation declarations have the effect of suppressing the
48080b57cec5SDimitry Andric   //   implicit instantiation of the entity to which they refer.
48090b57cec5SDimitry Andric   if (TSK == TSK_ExplicitInstantiationDeclaration &&
48100b57cec5SDimitry Andric       !PatternDecl->isInlined() &&
48110b57cec5SDimitry Andric       !PatternDecl->getReturnType()->getContainedAutoType())
48120b57cec5SDimitry Andric     return;
48130b57cec5SDimitry Andric 
48140b57cec5SDimitry Andric   if (PatternDecl->isInlined()) {
48150b57cec5SDimitry Andric     // Function, and all later redeclarations of it (from imported modules,
48160b57cec5SDimitry Andric     // for instance), are now implicitly inline.
48170b57cec5SDimitry Andric     for (auto *D = Function->getMostRecentDecl(); /**/;
48180b57cec5SDimitry Andric          D = D->getPreviousDecl()) {
48190b57cec5SDimitry Andric       D->setImplicitlyInline();
48200b57cec5SDimitry Andric       if (D == Function)
48210b57cec5SDimitry Andric         break;
48220b57cec5SDimitry Andric     }
48230b57cec5SDimitry Andric   }
48240b57cec5SDimitry Andric 
48250b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
48260b57cec5SDimitry Andric   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
48270b57cec5SDimitry Andric     return;
48280b57cec5SDimitry Andric   PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
48290b57cec5SDimitry Andric                                       "instantiating function definition");
48300b57cec5SDimitry Andric 
48310b57cec5SDimitry Andric   // The instantiation is visible here, even if it was first declared in an
48320b57cec5SDimitry Andric   // unimported module.
48330b57cec5SDimitry Andric   Function->setVisibleDespiteOwningModule();
48340b57cec5SDimitry Andric 
48350b57cec5SDimitry Andric   // Copy the inner loc start from the pattern.
48360b57cec5SDimitry Andric   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
48370b57cec5SDimitry Andric 
48380b57cec5SDimitry Andric   EnterExpressionEvaluationContext EvalContext(
48390b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
48400b57cec5SDimitry Andric 
48410b57cec5SDimitry Andric   // Introduce a new scope where local variable instantiations will be
48420b57cec5SDimitry Andric   // recorded, unless we're actually a member function within a local
48430b57cec5SDimitry Andric   // class, in which case we need to merge our results with the parent
48440b57cec5SDimitry Andric   // scope (of the enclosing function).
48450b57cec5SDimitry Andric   bool MergeWithParentScope = false;
48460b57cec5SDimitry Andric   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
48470b57cec5SDimitry Andric     MergeWithParentScope = Rec->isLocalClass();
48480b57cec5SDimitry Andric 
48490b57cec5SDimitry Andric   LocalInstantiationScope Scope(*this, MergeWithParentScope);
48500b57cec5SDimitry Andric 
48510b57cec5SDimitry Andric   if (PatternDecl->isDefaulted())
48520b57cec5SDimitry Andric     SetDeclDefaulted(Function, PatternDecl->getLocation());
48530b57cec5SDimitry Andric   else {
48540b57cec5SDimitry Andric     MultiLevelTemplateArgumentList TemplateArgs =
48550b57cec5SDimitry Andric       getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
48560b57cec5SDimitry Andric 
48570b57cec5SDimitry Andric     // Substitute into the qualifier; we can get a substitution failure here
48580b57cec5SDimitry Andric     // through evil use of alias templates.
48590b57cec5SDimitry Andric     // FIXME: Is CurContext correct for this? Should we go to the (instantiation
48600b57cec5SDimitry Andric     // of the) lexical context of the pattern?
48610b57cec5SDimitry Andric     SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
48620b57cec5SDimitry Andric 
48630b57cec5SDimitry Andric     ActOnStartOfFunctionDef(nullptr, Function);
48640b57cec5SDimitry Andric 
48650b57cec5SDimitry Andric     // Enter the scope of this instantiation. We don't use
48660b57cec5SDimitry Andric     // PushDeclContext because we don't have a scope.
48670b57cec5SDimitry Andric     Sema::ContextRAII savedContext(*this, Function);
48680b57cec5SDimitry Andric 
48690b57cec5SDimitry Andric     if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
48700b57cec5SDimitry Andric                                          TemplateArgs))
48710b57cec5SDimitry Andric       return;
48720b57cec5SDimitry Andric 
48730b57cec5SDimitry Andric     StmtResult Body;
48740b57cec5SDimitry Andric     if (PatternDecl->hasSkippedBody()) {
48750b57cec5SDimitry Andric       ActOnSkippedFunctionBody(Function);
48760b57cec5SDimitry Andric       Body = nullptr;
48770b57cec5SDimitry Andric     } else {
48780b57cec5SDimitry Andric       if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
48790b57cec5SDimitry Andric         // If this is a constructor, instantiate the member initializers.
48800b57cec5SDimitry Andric         InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
48810b57cec5SDimitry Andric                                    TemplateArgs);
48820b57cec5SDimitry Andric 
48830b57cec5SDimitry Andric         // If this is an MS ABI dllexport default constructor, instantiate any
48840b57cec5SDimitry Andric         // default arguments.
48850b57cec5SDimitry Andric         if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
48860b57cec5SDimitry Andric             Ctor->isDefaultConstructor()) {
4887*e8d8bef9SDimitry Andric           InstantiateDefaultCtorDefaultArgs(Ctor);
48880b57cec5SDimitry Andric         }
48890b57cec5SDimitry Andric       }
48900b57cec5SDimitry Andric 
48910b57cec5SDimitry Andric       // Instantiate the function body.
48920b57cec5SDimitry Andric       Body = SubstStmt(Pattern, TemplateArgs);
48930b57cec5SDimitry Andric 
48940b57cec5SDimitry Andric       if (Body.isInvalid())
48950b57cec5SDimitry Andric         Function->setInvalidDecl();
48960b57cec5SDimitry Andric     }
48970b57cec5SDimitry Andric     // FIXME: finishing the function body while in an expression evaluation
48980b57cec5SDimitry Andric     // context seems wrong. Investigate more.
48990b57cec5SDimitry Andric     ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
49000b57cec5SDimitry Andric 
49010b57cec5SDimitry Andric     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
49020b57cec5SDimitry Andric 
49030b57cec5SDimitry Andric     if (auto *Listener = getASTMutationListener())
49040b57cec5SDimitry Andric       Listener->FunctionDefinitionInstantiated(Function);
49050b57cec5SDimitry Andric 
49060b57cec5SDimitry Andric     savedContext.pop();
49070b57cec5SDimitry Andric   }
49080b57cec5SDimitry Andric 
49090b57cec5SDimitry Andric   DeclGroupRef DG(Function);
49100b57cec5SDimitry Andric   Consumer.HandleTopLevelDecl(DG);
49110b57cec5SDimitry Andric 
49120b57cec5SDimitry Andric   // This class may have local implicit instantiations that need to be
49130b57cec5SDimitry Andric   // instantiation within this scope.
49140b57cec5SDimitry Andric   LocalInstantiations.perform();
49150b57cec5SDimitry Andric   Scope.Exit();
49160b57cec5SDimitry Andric   GlobalInstantiations.perform();
49170b57cec5SDimitry Andric }
49180b57cec5SDimitry Andric 
49190b57cec5SDimitry Andric VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
49200b57cec5SDimitry Andric     VarTemplateDecl *VarTemplate, VarDecl *FromVar,
49210b57cec5SDimitry Andric     const TemplateArgumentList &TemplateArgList,
49220b57cec5SDimitry Andric     const TemplateArgumentListInfo &TemplateArgsInfo,
49230b57cec5SDimitry Andric     SmallVectorImpl<TemplateArgument> &Converted,
4924*e8d8bef9SDimitry Andric     SourceLocation PointOfInstantiation,
49250b57cec5SDimitry Andric     LateInstantiatedAttrVec *LateAttrs,
49260b57cec5SDimitry Andric     LocalInstantiationScope *StartingScope) {
49270b57cec5SDimitry Andric   if (FromVar->isInvalidDecl())
49280b57cec5SDimitry Andric     return nullptr;
49290b57cec5SDimitry Andric 
49300b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
49310b57cec5SDimitry Andric   if (Inst.isInvalid())
49320b57cec5SDimitry Andric     return nullptr;
49330b57cec5SDimitry Andric 
49340b57cec5SDimitry Andric   MultiLevelTemplateArgumentList TemplateArgLists;
49350b57cec5SDimitry Andric   TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
49360b57cec5SDimitry Andric 
49370b57cec5SDimitry Andric   // Instantiate the first declaration of the variable template: for a partial
49380b57cec5SDimitry Andric   // specialization of a static data member template, the first declaration may
49390b57cec5SDimitry Andric   // or may not be the declaration in the class; if it's in the class, we want
49400b57cec5SDimitry Andric   // to instantiate a member in the class (a declaration), and if it's outside,
49410b57cec5SDimitry Andric   // we want to instantiate a definition.
49420b57cec5SDimitry Andric   //
49430b57cec5SDimitry Andric   // If we're instantiating an explicitly-specialized member template or member
49440b57cec5SDimitry Andric   // partial specialization, don't do this. The member specialization completely
49450b57cec5SDimitry Andric   // replaces the original declaration in this case.
49460b57cec5SDimitry Andric   bool IsMemberSpec = false;
49470b57cec5SDimitry Andric   if (VarTemplatePartialSpecializationDecl *PartialSpec =
49480b57cec5SDimitry Andric           dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
49490b57cec5SDimitry Andric     IsMemberSpec = PartialSpec->isMemberSpecialization();
49500b57cec5SDimitry Andric   else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
49510b57cec5SDimitry Andric     IsMemberSpec = FromTemplate->isMemberSpecialization();
49520b57cec5SDimitry Andric   if (!IsMemberSpec)
49530b57cec5SDimitry Andric     FromVar = FromVar->getFirstDecl();
49540b57cec5SDimitry Andric 
49550b57cec5SDimitry Andric   MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
49560b57cec5SDimitry Andric   TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
49570b57cec5SDimitry Andric                                         MultiLevelList);
49580b57cec5SDimitry Andric 
49590b57cec5SDimitry Andric   // TODO: Set LateAttrs and StartingScope ...
49600b57cec5SDimitry Andric 
49610b57cec5SDimitry Andric   return cast_or_null<VarTemplateSpecializationDecl>(
49620b57cec5SDimitry Andric       Instantiator.VisitVarTemplateSpecializationDecl(
4963*e8d8bef9SDimitry Andric           VarTemplate, FromVar, TemplateArgsInfo, Converted));
49640b57cec5SDimitry Andric }
49650b57cec5SDimitry Andric 
49660b57cec5SDimitry Andric /// Instantiates a variable template specialization by completing it
49670b57cec5SDimitry Andric /// with appropriate type information and initializer.
49680b57cec5SDimitry Andric VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
49690b57cec5SDimitry Andric     VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
49700b57cec5SDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgs) {
49710b57cec5SDimitry Andric   assert(PatternDecl->isThisDeclarationADefinition() &&
49720b57cec5SDimitry Andric          "don't have a definition to instantiate from");
49730b57cec5SDimitry Andric 
49740b57cec5SDimitry Andric   // Do substitution on the type of the declaration
49750b57cec5SDimitry Andric   TypeSourceInfo *DI =
49760b57cec5SDimitry Andric       SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
49770b57cec5SDimitry Andric                 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
49780b57cec5SDimitry Andric   if (!DI)
49790b57cec5SDimitry Andric     return nullptr;
49800b57cec5SDimitry Andric 
49810b57cec5SDimitry Andric   // Update the type of this variable template specialization.
49820b57cec5SDimitry Andric   VarSpec->setType(DI->getType());
49830b57cec5SDimitry Andric 
49840b57cec5SDimitry Andric   // Convert the declaration into a definition now.
49850b57cec5SDimitry Andric   VarSpec->setCompleteDefinition();
49860b57cec5SDimitry Andric 
49870b57cec5SDimitry Andric   // Instantiate the initializer.
49880b57cec5SDimitry Andric   InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
49890b57cec5SDimitry Andric 
49905ffd83dbSDimitry Andric   if (getLangOpts().OpenCL)
49915ffd83dbSDimitry Andric     deduceOpenCLAddressSpace(VarSpec);
49925ffd83dbSDimitry Andric 
49930b57cec5SDimitry Andric   return VarSpec;
49940b57cec5SDimitry Andric }
49950b57cec5SDimitry Andric 
49960b57cec5SDimitry Andric /// BuildVariableInstantiation - Used after a new variable has been created.
49970b57cec5SDimitry Andric /// Sets basic variable data and decides whether to postpone the
49980b57cec5SDimitry Andric /// variable instantiation.
49990b57cec5SDimitry Andric void Sema::BuildVariableInstantiation(
50000b57cec5SDimitry Andric     VarDecl *NewVar, VarDecl *OldVar,
50010b57cec5SDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgs,
50020b57cec5SDimitry Andric     LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
50030b57cec5SDimitry Andric     LocalInstantiationScope *StartingScope,
50040b57cec5SDimitry Andric     bool InstantiatingVarTemplate,
50050b57cec5SDimitry Andric     VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
50060b57cec5SDimitry Andric   // Instantiating a partial specialization to produce a partial
50070b57cec5SDimitry Andric   // specialization.
50080b57cec5SDimitry Andric   bool InstantiatingVarTemplatePartialSpec =
50090b57cec5SDimitry Andric       isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
50100b57cec5SDimitry Andric       isa<VarTemplatePartialSpecializationDecl>(NewVar);
50110b57cec5SDimitry Andric   // Instantiating from a variable template (or partial specialization) to
50120b57cec5SDimitry Andric   // produce a variable template specialization.
50130b57cec5SDimitry Andric   bool InstantiatingSpecFromTemplate =
50140b57cec5SDimitry Andric       isa<VarTemplateSpecializationDecl>(NewVar) &&
50150b57cec5SDimitry Andric       (OldVar->getDescribedVarTemplate() ||
50160b57cec5SDimitry Andric        isa<VarTemplatePartialSpecializationDecl>(OldVar));
50170b57cec5SDimitry Andric 
50180b57cec5SDimitry Andric   // If we are instantiating a local extern declaration, the
50190b57cec5SDimitry Andric   // instantiation belongs lexically to the containing function.
50200b57cec5SDimitry Andric   // If we are instantiating a static data member defined
50210b57cec5SDimitry Andric   // out-of-line, the instantiation will have the same lexical
50220b57cec5SDimitry Andric   // context (which will be a namespace scope) as the template.
50230b57cec5SDimitry Andric   if (OldVar->isLocalExternDecl()) {
50240b57cec5SDimitry Andric     NewVar->setLocalExternDecl();
50250b57cec5SDimitry Andric     NewVar->setLexicalDeclContext(Owner);
50260b57cec5SDimitry Andric   } else if (OldVar->isOutOfLine())
50270b57cec5SDimitry Andric     NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
50280b57cec5SDimitry Andric   NewVar->setTSCSpec(OldVar->getTSCSpec());
50290b57cec5SDimitry Andric   NewVar->setInitStyle(OldVar->getInitStyle());
50300b57cec5SDimitry Andric   NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
50310b57cec5SDimitry Andric   NewVar->setObjCForDecl(OldVar->isObjCForDecl());
50320b57cec5SDimitry Andric   NewVar->setConstexpr(OldVar->isConstexpr());
50335ffd83dbSDimitry Andric   MaybeAddCUDAConstantAttr(NewVar);
50340b57cec5SDimitry Andric   NewVar->setInitCapture(OldVar->isInitCapture());
50350b57cec5SDimitry Andric   NewVar->setPreviousDeclInSameBlockScope(
50360b57cec5SDimitry Andric       OldVar->isPreviousDeclInSameBlockScope());
50370b57cec5SDimitry Andric   NewVar->setAccess(OldVar->getAccess());
50380b57cec5SDimitry Andric 
50390b57cec5SDimitry Andric   if (!OldVar->isStaticDataMember()) {
50400b57cec5SDimitry Andric     if (OldVar->isUsed(false))
50410b57cec5SDimitry Andric       NewVar->setIsUsed();
50420b57cec5SDimitry Andric     NewVar->setReferenced(OldVar->isReferenced());
50430b57cec5SDimitry Andric   }
50440b57cec5SDimitry Andric 
50450b57cec5SDimitry Andric   InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
50460b57cec5SDimitry Andric 
50470b57cec5SDimitry Andric   LookupResult Previous(
50480b57cec5SDimitry Andric       *this, NewVar->getDeclName(), NewVar->getLocation(),
50490b57cec5SDimitry Andric       NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
50500b57cec5SDimitry Andric                                   : Sema::LookupOrdinaryName,
50510b57cec5SDimitry Andric       NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
50520b57cec5SDimitry Andric                                   : forRedeclarationInCurContext());
50530b57cec5SDimitry Andric 
50540b57cec5SDimitry Andric   if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
50550b57cec5SDimitry Andric       (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
50560b57cec5SDimitry Andric        OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
50570b57cec5SDimitry Andric     // We have a previous declaration. Use that one, so we merge with the
50580b57cec5SDimitry Andric     // right type.
50590b57cec5SDimitry Andric     if (NamedDecl *NewPrev = FindInstantiatedDecl(
50600b57cec5SDimitry Andric             NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
50610b57cec5SDimitry Andric       Previous.addDecl(NewPrev);
50620b57cec5SDimitry Andric   } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
50630b57cec5SDimitry Andric              OldVar->hasLinkage()) {
50640b57cec5SDimitry Andric     LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
50650b57cec5SDimitry Andric   } else if (PrevDeclForVarTemplateSpecialization) {
50660b57cec5SDimitry Andric     Previous.addDecl(PrevDeclForVarTemplateSpecialization);
50670b57cec5SDimitry Andric   }
50680b57cec5SDimitry Andric   CheckVariableDeclaration(NewVar, Previous);
50690b57cec5SDimitry Andric 
50700b57cec5SDimitry Andric   if (!InstantiatingVarTemplate) {
50710b57cec5SDimitry Andric     NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
50720b57cec5SDimitry Andric     if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
50730b57cec5SDimitry Andric       NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
50740b57cec5SDimitry Andric   }
50750b57cec5SDimitry Andric 
50760b57cec5SDimitry Andric   if (!OldVar->isOutOfLine()) {
50770b57cec5SDimitry Andric     if (NewVar->getDeclContext()->isFunctionOrMethod())
50780b57cec5SDimitry Andric       CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
50790b57cec5SDimitry Andric   }
50800b57cec5SDimitry Andric 
50810b57cec5SDimitry Andric   // Link instantiations of static data members back to the template from
50820b57cec5SDimitry Andric   // which they were instantiated.
50830b57cec5SDimitry Andric   //
50840b57cec5SDimitry Andric   // Don't do this when instantiating a template (we link the template itself
50850b57cec5SDimitry Andric   // back in that case) nor when instantiating a static data member template
50860b57cec5SDimitry Andric   // (that's not a member specialization).
50870b57cec5SDimitry Andric   if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
50880b57cec5SDimitry Andric       !InstantiatingSpecFromTemplate)
50890b57cec5SDimitry Andric     NewVar->setInstantiationOfStaticDataMember(OldVar,
50900b57cec5SDimitry Andric                                                TSK_ImplicitInstantiation);
50910b57cec5SDimitry Andric 
50920b57cec5SDimitry Andric   // If the pattern is an (in-class) explicit specialization, then the result
50930b57cec5SDimitry Andric   // is also an explicit specialization.
50940b57cec5SDimitry Andric   if (VarTemplateSpecializationDecl *OldVTSD =
50950b57cec5SDimitry Andric           dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
50960b57cec5SDimitry Andric     if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
50970b57cec5SDimitry Andric         !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
50980b57cec5SDimitry Andric       cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
50990b57cec5SDimitry Andric           TSK_ExplicitSpecialization);
51000b57cec5SDimitry Andric   }
51010b57cec5SDimitry Andric 
51020b57cec5SDimitry Andric   // Forward the mangling number from the template to the instantiated decl.
51030b57cec5SDimitry Andric   Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
51040b57cec5SDimitry Andric   Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
51050b57cec5SDimitry Andric 
51060b57cec5SDimitry Andric   // Figure out whether to eagerly instantiate the initializer.
51070b57cec5SDimitry Andric   if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
51080b57cec5SDimitry Andric     // We're producing a template. Don't instantiate the initializer yet.
51090b57cec5SDimitry Andric   } else if (NewVar->getType()->isUndeducedType()) {
51100b57cec5SDimitry Andric     // We need the type to complete the declaration of the variable.
51110b57cec5SDimitry Andric     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
51120b57cec5SDimitry Andric   } else if (InstantiatingSpecFromTemplate ||
51130b57cec5SDimitry Andric              (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
51140b57cec5SDimitry Andric               !NewVar->isThisDeclarationADefinition())) {
51150b57cec5SDimitry Andric     // Delay instantiation of the initializer for variable template
51160b57cec5SDimitry Andric     // specializations or inline static data members until a definition of the
51170b57cec5SDimitry Andric     // variable is needed.
51180b57cec5SDimitry Andric   } else {
51190b57cec5SDimitry Andric     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
51200b57cec5SDimitry Andric   }
51210b57cec5SDimitry Andric 
51220b57cec5SDimitry Andric   // Diagnose unused local variables with dependent types, where the diagnostic
51230b57cec5SDimitry Andric   // will have been deferred.
51240b57cec5SDimitry Andric   if (!NewVar->isInvalidDecl() &&
51250b57cec5SDimitry Andric       NewVar->getDeclContext()->isFunctionOrMethod() &&
51260b57cec5SDimitry Andric       OldVar->getType()->isDependentType())
51270b57cec5SDimitry Andric     DiagnoseUnusedDecl(NewVar);
51280b57cec5SDimitry Andric }
51290b57cec5SDimitry Andric 
51300b57cec5SDimitry Andric /// Instantiate the initializer of a variable.
51310b57cec5SDimitry Andric void Sema::InstantiateVariableInitializer(
51320b57cec5SDimitry Andric     VarDecl *Var, VarDecl *OldVar,
51330b57cec5SDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgs) {
51340b57cec5SDimitry Andric   if (ASTMutationListener *L = getASTContext().getASTMutationListener())
51350b57cec5SDimitry Andric     L->VariableDefinitionInstantiated(Var);
51360b57cec5SDimitry Andric 
51370b57cec5SDimitry Andric   // We propagate the 'inline' flag with the initializer, because it
51380b57cec5SDimitry Andric   // would otherwise imply that the variable is a definition for a
51390b57cec5SDimitry Andric   // non-static data member.
51400b57cec5SDimitry Andric   if (OldVar->isInlineSpecified())
51410b57cec5SDimitry Andric     Var->setInlineSpecified();
51420b57cec5SDimitry Andric   else if (OldVar->isInline())
51430b57cec5SDimitry Andric     Var->setImplicitlyInline();
51440b57cec5SDimitry Andric 
51450b57cec5SDimitry Andric   if (OldVar->getInit()) {
51460b57cec5SDimitry Andric     EnterExpressionEvaluationContext Evaluated(
51470b57cec5SDimitry Andric         *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
51480b57cec5SDimitry Andric 
51490b57cec5SDimitry Andric     // Instantiate the initializer.
51500b57cec5SDimitry Andric     ExprResult Init;
51510b57cec5SDimitry Andric 
51520b57cec5SDimitry Andric     {
51530b57cec5SDimitry Andric       ContextRAII SwitchContext(*this, Var->getDeclContext());
51540b57cec5SDimitry Andric       Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
51550b57cec5SDimitry Andric                               OldVar->getInitStyle() == VarDecl::CallInit);
51560b57cec5SDimitry Andric     }
51570b57cec5SDimitry Andric 
51580b57cec5SDimitry Andric     if (!Init.isInvalid()) {
51590b57cec5SDimitry Andric       Expr *InitExpr = Init.get();
51600b57cec5SDimitry Andric 
51610b57cec5SDimitry Andric       if (Var->hasAttr<DLLImportAttr>() &&
51620b57cec5SDimitry Andric           (!InitExpr ||
51630b57cec5SDimitry Andric            !InitExpr->isConstantInitializer(getASTContext(), false))) {
51640b57cec5SDimitry Andric         // Do not dynamically initialize dllimport variables.
51650b57cec5SDimitry Andric       } else if (InitExpr) {
51660b57cec5SDimitry Andric         bool DirectInit = OldVar->isDirectInit();
51670b57cec5SDimitry Andric         AddInitializerToDecl(Var, InitExpr, DirectInit);
51680b57cec5SDimitry Andric       } else
51690b57cec5SDimitry Andric         ActOnUninitializedDecl(Var);
51700b57cec5SDimitry Andric     } else {
51710b57cec5SDimitry Andric       // FIXME: Not too happy about invalidating the declaration
51720b57cec5SDimitry Andric       // because of a bogus initializer.
51730b57cec5SDimitry Andric       Var->setInvalidDecl();
51740b57cec5SDimitry Andric     }
51750b57cec5SDimitry Andric   } else {
51760b57cec5SDimitry Andric     // `inline` variables are a definition and declaration all in one; we won't
51770b57cec5SDimitry Andric     // pick up an initializer from anywhere else.
51780b57cec5SDimitry Andric     if (Var->isStaticDataMember() && !Var->isInline()) {
51790b57cec5SDimitry Andric       if (!Var->isOutOfLine())
51800b57cec5SDimitry Andric         return;
51810b57cec5SDimitry Andric 
51820b57cec5SDimitry Andric       // If the declaration inside the class had an initializer, don't add
51830b57cec5SDimitry Andric       // another one to the out-of-line definition.
51840b57cec5SDimitry Andric       if (OldVar->getFirstDecl()->hasInit())
51850b57cec5SDimitry Andric         return;
51860b57cec5SDimitry Andric     }
51870b57cec5SDimitry Andric 
51880b57cec5SDimitry Andric     // We'll add an initializer to a for-range declaration later.
51890b57cec5SDimitry Andric     if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
51900b57cec5SDimitry Andric       return;
51910b57cec5SDimitry Andric 
51920b57cec5SDimitry Andric     ActOnUninitializedDecl(Var);
51930b57cec5SDimitry Andric   }
51940b57cec5SDimitry Andric 
51950b57cec5SDimitry Andric   if (getLangOpts().CUDA)
51960b57cec5SDimitry Andric     checkAllowedCUDAInitializer(Var);
51970b57cec5SDimitry Andric }
51980b57cec5SDimitry Andric 
51990b57cec5SDimitry Andric /// Instantiate the definition of the given variable from its
52000b57cec5SDimitry Andric /// template.
52010b57cec5SDimitry Andric ///
52020b57cec5SDimitry Andric /// \param PointOfInstantiation the point at which the instantiation was
52030b57cec5SDimitry Andric /// required. Note that this is not precisely a "point of instantiation"
52040b57cec5SDimitry Andric /// for the variable, but it's close.
52050b57cec5SDimitry Andric ///
52060b57cec5SDimitry Andric /// \param Var the already-instantiated declaration of a templated variable.
52070b57cec5SDimitry Andric ///
52080b57cec5SDimitry Andric /// \param Recursive if true, recursively instantiates any functions that
52090b57cec5SDimitry Andric /// are required by this instantiation.
52100b57cec5SDimitry Andric ///
52110b57cec5SDimitry Andric /// \param DefinitionRequired if true, then we are performing an explicit
52120b57cec5SDimitry Andric /// instantiation where a definition of the variable is required. Complain
52130b57cec5SDimitry Andric /// if there is no such definition.
52140b57cec5SDimitry Andric void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
52150b57cec5SDimitry Andric                                          VarDecl *Var, bool Recursive,
52160b57cec5SDimitry Andric                                       bool DefinitionRequired, bool AtEndOfTU) {
52170b57cec5SDimitry Andric   if (Var->isInvalidDecl())
52180b57cec5SDimitry Andric     return;
52190b57cec5SDimitry Andric 
52200b57cec5SDimitry Andric   // Never instantiate an explicitly-specialized entity.
52210b57cec5SDimitry Andric   TemplateSpecializationKind TSK =
52220b57cec5SDimitry Andric       Var->getTemplateSpecializationKindForInstantiation();
52230b57cec5SDimitry Andric   if (TSK == TSK_ExplicitSpecialization)
52240b57cec5SDimitry Andric     return;
52250b57cec5SDimitry Andric 
52260b57cec5SDimitry Andric   // Find the pattern and the arguments to substitute into it.
52270b57cec5SDimitry Andric   VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
52280b57cec5SDimitry Andric   assert(PatternDecl && "no pattern for templated variable");
52290b57cec5SDimitry Andric   MultiLevelTemplateArgumentList TemplateArgs =
52300b57cec5SDimitry Andric       getTemplateInstantiationArgs(Var);
52310b57cec5SDimitry Andric 
52320b57cec5SDimitry Andric   VarTemplateSpecializationDecl *VarSpec =
52330b57cec5SDimitry Andric       dyn_cast<VarTemplateSpecializationDecl>(Var);
52340b57cec5SDimitry Andric   if (VarSpec) {
52350b57cec5SDimitry Andric     // If this is a static data member template, there might be an
52360b57cec5SDimitry Andric     // uninstantiated initializer on the declaration. If so, instantiate
52370b57cec5SDimitry Andric     // it now.
52380b57cec5SDimitry Andric     //
52390b57cec5SDimitry Andric     // FIXME: This largely duplicates what we would do below. The difference
52400b57cec5SDimitry Andric     // is that along this path we may instantiate an initializer from an
52410b57cec5SDimitry Andric     // in-class declaration of the template and instantiate the definition
52420b57cec5SDimitry Andric     // from a separate out-of-class definition.
52430b57cec5SDimitry Andric     if (PatternDecl->isStaticDataMember() &&
52440b57cec5SDimitry Andric         (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
52450b57cec5SDimitry Andric         !Var->hasInit()) {
52460b57cec5SDimitry Andric       // FIXME: Factor out the duplicated instantiation context setup/tear down
52470b57cec5SDimitry Andric       // code here.
52480b57cec5SDimitry Andric       InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
52490b57cec5SDimitry Andric       if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
52500b57cec5SDimitry Andric         return;
52510b57cec5SDimitry Andric       PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
52520b57cec5SDimitry Andric                                           "instantiating variable initializer");
52530b57cec5SDimitry Andric 
52540b57cec5SDimitry Andric       // The instantiation is visible here, even if it was first declared in an
52550b57cec5SDimitry Andric       // unimported module.
52560b57cec5SDimitry Andric       Var->setVisibleDespiteOwningModule();
52570b57cec5SDimitry Andric 
52580b57cec5SDimitry Andric       // If we're performing recursive template instantiation, create our own
52590b57cec5SDimitry Andric       // queue of pending implicit instantiations that we will instantiate
52600b57cec5SDimitry Andric       // later, while we're still within our own instantiation context.
52610b57cec5SDimitry Andric       GlobalEagerInstantiationScope GlobalInstantiations(*this,
52620b57cec5SDimitry Andric                                                          /*Enabled=*/Recursive);
52630b57cec5SDimitry Andric       LocalInstantiationScope Local(*this);
52640b57cec5SDimitry Andric       LocalEagerInstantiationScope LocalInstantiations(*this);
52650b57cec5SDimitry Andric 
52660b57cec5SDimitry Andric       // Enter the scope of this instantiation. We don't use
52670b57cec5SDimitry Andric       // PushDeclContext because we don't have a scope.
52680b57cec5SDimitry Andric       ContextRAII PreviousContext(*this, Var->getDeclContext());
52690b57cec5SDimitry Andric       InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
52700b57cec5SDimitry Andric       PreviousContext.pop();
52710b57cec5SDimitry Andric 
52720b57cec5SDimitry Andric       // This variable may have local implicit instantiations that need to be
52730b57cec5SDimitry Andric       // instantiated within this scope.
52740b57cec5SDimitry Andric       LocalInstantiations.perform();
52750b57cec5SDimitry Andric       Local.Exit();
52760b57cec5SDimitry Andric       GlobalInstantiations.perform();
52770b57cec5SDimitry Andric     }
52780b57cec5SDimitry Andric   } else {
52790b57cec5SDimitry Andric     assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
52800b57cec5SDimitry Andric            "not a static data member?");
52810b57cec5SDimitry Andric   }
52820b57cec5SDimitry Andric 
52830b57cec5SDimitry Andric   VarDecl *Def = PatternDecl->getDefinition(getASTContext());
52840b57cec5SDimitry Andric 
52850b57cec5SDimitry Andric   // If we don't have a definition of the variable template, we won't perform
52860b57cec5SDimitry Andric   // any instantiation. Rather, we rely on the user to instantiate this
52870b57cec5SDimitry Andric   // definition (or provide a specialization for it) in another translation
52880b57cec5SDimitry Andric   // unit.
52890b57cec5SDimitry Andric   if (!Def && !DefinitionRequired) {
52900b57cec5SDimitry Andric     if (TSK == TSK_ExplicitInstantiationDefinition) {
52910b57cec5SDimitry Andric       PendingInstantiations.push_back(
52920b57cec5SDimitry Andric         std::make_pair(Var, PointOfInstantiation));
52930b57cec5SDimitry Andric     } else if (TSK == TSK_ImplicitInstantiation) {
52940b57cec5SDimitry Andric       // Warn about missing definition at the end of translation unit.
52950b57cec5SDimitry Andric       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
52960b57cec5SDimitry Andric           !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
52970b57cec5SDimitry Andric         Diag(PointOfInstantiation, diag::warn_var_template_missing)
52980b57cec5SDimitry Andric           << Var;
52990b57cec5SDimitry Andric         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
53000b57cec5SDimitry Andric         if (getLangOpts().CPlusPlus11)
53010b57cec5SDimitry Andric           Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
53020b57cec5SDimitry Andric       }
53030b57cec5SDimitry Andric       return;
53040b57cec5SDimitry Andric     }
53050b57cec5SDimitry Andric   }
53060b57cec5SDimitry Andric 
53070b57cec5SDimitry Andric   // FIXME: We need to track the instantiation stack in order to know which
53080b57cec5SDimitry Andric   // definitions should be visible within this instantiation.
53090b57cec5SDimitry Andric   // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
53100b57cec5SDimitry Andric   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
53110b57cec5SDimitry Andric                                      /*InstantiatedFromMember*/false,
53120b57cec5SDimitry Andric                                      PatternDecl, Def, TSK,
53130b57cec5SDimitry Andric                                      /*Complain*/DefinitionRequired))
53140b57cec5SDimitry Andric     return;
53150b57cec5SDimitry Andric 
53160b57cec5SDimitry Andric   // C++11 [temp.explicit]p10:
53170b57cec5SDimitry Andric   //   Except for inline functions, const variables of literal types, variables
53180b57cec5SDimitry Andric   //   of reference types, [...] explicit instantiation declarations
53190b57cec5SDimitry Andric   //   have the effect of suppressing the implicit instantiation of the entity
53200b57cec5SDimitry Andric   //   to which they refer.
53210b57cec5SDimitry Andric   //
53220b57cec5SDimitry Andric   // FIXME: That's not exactly the same as "might be usable in constant
53230b57cec5SDimitry Andric   // expressions", which only allows constexpr variables and const integral
53240b57cec5SDimitry Andric   // types, not arbitrary const literal types.
53250b57cec5SDimitry Andric   if (TSK == TSK_ExplicitInstantiationDeclaration &&
53260b57cec5SDimitry Andric       !Var->mightBeUsableInConstantExpressions(getASTContext()))
53270b57cec5SDimitry Andric     return;
53280b57cec5SDimitry Andric 
53290b57cec5SDimitry Andric   // Make sure to pass the instantiated variable to the consumer at the end.
53300b57cec5SDimitry Andric   struct PassToConsumerRAII {
53310b57cec5SDimitry Andric     ASTConsumer &Consumer;
53320b57cec5SDimitry Andric     VarDecl *Var;
53330b57cec5SDimitry Andric 
53340b57cec5SDimitry Andric     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
53350b57cec5SDimitry Andric       : Consumer(Consumer), Var(Var) { }
53360b57cec5SDimitry Andric 
53370b57cec5SDimitry Andric     ~PassToConsumerRAII() {
53380b57cec5SDimitry Andric       Consumer.HandleCXXStaticMemberVarInstantiation(Var);
53390b57cec5SDimitry Andric     }
53400b57cec5SDimitry Andric   } PassToConsumerRAII(Consumer, Var);
53410b57cec5SDimitry Andric 
53420b57cec5SDimitry Andric   // If we already have a definition, we're done.
53430b57cec5SDimitry Andric   if (VarDecl *Def = Var->getDefinition()) {
53440b57cec5SDimitry Andric     // We may be explicitly instantiating something we've already implicitly
53450b57cec5SDimitry Andric     // instantiated.
53460b57cec5SDimitry Andric     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
53470b57cec5SDimitry Andric                                        PointOfInstantiation);
53480b57cec5SDimitry Andric     return;
53490b57cec5SDimitry Andric   }
53500b57cec5SDimitry Andric 
53510b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
53520b57cec5SDimitry Andric   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
53530b57cec5SDimitry Andric     return;
53540b57cec5SDimitry Andric   PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
53550b57cec5SDimitry Andric                                       "instantiating variable definition");
53560b57cec5SDimitry Andric 
53570b57cec5SDimitry Andric   // If we're performing recursive template instantiation, create our own
53580b57cec5SDimitry Andric   // queue of pending implicit instantiations that we will instantiate later,
53590b57cec5SDimitry Andric   // while we're still within our own instantiation context.
53600b57cec5SDimitry Andric   GlobalEagerInstantiationScope GlobalInstantiations(*this,
53610b57cec5SDimitry Andric                                                      /*Enabled=*/Recursive);
53620b57cec5SDimitry Andric 
53630b57cec5SDimitry Andric   // Enter the scope of this instantiation. We don't use
53640b57cec5SDimitry Andric   // PushDeclContext because we don't have a scope.
53650b57cec5SDimitry Andric   ContextRAII PreviousContext(*this, Var->getDeclContext());
53660b57cec5SDimitry Andric   LocalInstantiationScope Local(*this);
53670b57cec5SDimitry Andric 
53680b57cec5SDimitry Andric   LocalEagerInstantiationScope LocalInstantiations(*this);
53690b57cec5SDimitry Andric 
53700b57cec5SDimitry Andric   VarDecl *OldVar = Var;
53710b57cec5SDimitry Andric   if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
53720b57cec5SDimitry Andric     // We're instantiating an inline static data member whose definition was
53730b57cec5SDimitry Andric     // provided inside the class.
53740b57cec5SDimitry Andric     InstantiateVariableInitializer(Var, Def, TemplateArgs);
53750b57cec5SDimitry Andric   } else if (!VarSpec) {
53760b57cec5SDimitry Andric     Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
53770b57cec5SDimitry Andric                                           TemplateArgs));
53780b57cec5SDimitry Andric   } else if (Var->isStaticDataMember() &&
53790b57cec5SDimitry Andric              Var->getLexicalDeclContext()->isRecord()) {
53800b57cec5SDimitry Andric     // We need to instantiate the definition of a static data member template,
53810b57cec5SDimitry Andric     // and all we have is the in-class declaration of it. Instantiate a separate
53820b57cec5SDimitry Andric     // declaration of the definition.
53830b57cec5SDimitry Andric     TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
53840b57cec5SDimitry Andric                                           TemplateArgs);
53850b57cec5SDimitry Andric     Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5386*e8d8bef9SDimitry Andric         VarSpec->getSpecializedTemplate(), Def, VarSpec->getTemplateArgsInfo(),
5387*e8d8bef9SDimitry Andric         VarSpec->getTemplateArgs().asArray(), VarSpec));
53880b57cec5SDimitry Andric     if (Var) {
53890b57cec5SDimitry Andric       llvm::PointerUnion<VarTemplateDecl *,
53900b57cec5SDimitry Andric                          VarTemplatePartialSpecializationDecl *> PatternPtr =
53910b57cec5SDimitry Andric           VarSpec->getSpecializedTemplateOrPartial();
53920b57cec5SDimitry Andric       if (VarTemplatePartialSpecializationDecl *Partial =
53930b57cec5SDimitry Andric           PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
53940b57cec5SDimitry Andric         cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
53950b57cec5SDimitry Andric             Partial, &VarSpec->getTemplateInstantiationArgs());
53960b57cec5SDimitry Andric 
53970b57cec5SDimitry Andric       // Attach the initializer.
53980b57cec5SDimitry Andric       InstantiateVariableInitializer(Var, Def, TemplateArgs);
53990b57cec5SDimitry Andric     }
54000b57cec5SDimitry Andric   } else
54010b57cec5SDimitry Andric     // Complete the existing variable's definition with an appropriately
54020b57cec5SDimitry Andric     // substituted type and initializer.
54030b57cec5SDimitry Andric     Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
54040b57cec5SDimitry Andric 
54050b57cec5SDimitry Andric   PreviousContext.pop();
54060b57cec5SDimitry Andric 
54070b57cec5SDimitry Andric   if (Var) {
54080b57cec5SDimitry Andric     PassToConsumerRAII.Var = Var;
54090b57cec5SDimitry Andric     Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
54100b57cec5SDimitry Andric                                        OldVar->getPointOfInstantiation());
54110b57cec5SDimitry Andric   }
54120b57cec5SDimitry Andric 
54130b57cec5SDimitry Andric   // This variable may have local implicit instantiations that need to be
54140b57cec5SDimitry Andric   // instantiated within this scope.
54150b57cec5SDimitry Andric   LocalInstantiations.perform();
54160b57cec5SDimitry Andric   Local.Exit();
54170b57cec5SDimitry Andric   GlobalInstantiations.perform();
54180b57cec5SDimitry Andric }
54190b57cec5SDimitry Andric 
54200b57cec5SDimitry Andric void
54210b57cec5SDimitry Andric Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
54220b57cec5SDimitry Andric                                  const CXXConstructorDecl *Tmpl,
54230b57cec5SDimitry Andric                            const MultiLevelTemplateArgumentList &TemplateArgs) {
54240b57cec5SDimitry Andric 
54250b57cec5SDimitry Andric   SmallVector<CXXCtorInitializer*, 4> NewInits;
54260b57cec5SDimitry Andric   bool AnyErrors = Tmpl->isInvalidDecl();
54270b57cec5SDimitry Andric 
54280b57cec5SDimitry Andric   // Instantiate all the initializers.
54290b57cec5SDimitry Andric   for (const auto *Init : Tmpl->inits()) {
54300b57cec5SDimitry Andric     // Only instantiate written initializers, let Sema re-construct implicit
54310b57cec5SDimitry Andric     // ones.
54320b57cec5SDimitry Andric     if (!Init->isWritten())
54330b57cec5SDimitry Andric       continue;
54340b57cec5SDimitry Andric 
54350b57cec5SDimitry Andric     SourceLocation EllipsisLoc;
54360b57cec5SDimitry Andric 
54370b57cec5SDimitry Andric     if (Init->isPackExpansion()) {
54380b57cec5SDimitry Andric       // This is a pack expansion. We should expand it now.
54390b57cec5SDimitry Andric       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
54400b57cec5SDimitry Andric       SmallVector<UnexpandedParameterPack, 4> Unexpanded;
54410b57cec5SDimitry Andric       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
54420b57cec5SDimitry Andric       collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
54430b57cec5SDimitry Andric       bool ShouldExpand = false;
54440b57cec5SDimitry Andric       bool RetainExpansion = false;
54450b57cec5SDimitry Andric       Optional<unsigned> NumExpansions;
54460b57cec5SDimitry Andric       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
54470b57cec5SDimitry Andric                                           BaseTL.getSourceRange(),
54480b57cec5SDimitry Andric                                           Unexpanded,
54490b57cec5SDimitry Andric                                           TemplateArgs, ShouldExpand,
54500b57cec5SDimitry Andric                                           RetainExpansion,
54510b57cec5SDimitry Andric                                           NumExpansions)) {
54520b57cec5SDimitry Andric         AnyErrors = true;
54530b57cec5SDimitry Andric         New->setInvalidDecl();
54540b57cec5SDimitry Andric         continue;
54550b57cec5SDimitry Andric       }
54560b57cec5SDimitry Andric       assert(ShouldExpand && "Partial instantiation of base initializer?");
54570b57cec5SDimitry Andric 
54580b57cec5SDimitry Andric       // Loop over all of the arguments in the argument pack(s),
54590b57cec5SDimitry Andric       for (unsigned I = 0; I != *NumExpansions; ++I) {
54600b57cec5SDimitry Andric         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric         // Instantiate the initializer.
54630b57cec5SDimitry Andric         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
54640b57cec5SDimitry Andric                                                /*CXXDirectInit=*/true);
54650b57cec5SDimitry Andric         if (TempInit.isInvalid()) {
54660b57cec5SDimitry Andric           AnyErrors = true;
54670b57cec5SDimitry Andric           break;
54680b57cec5SDimitry Andric         }
54690b57cec5SDimitry Andric 
54700b57cec5SDimitry Andric         // Instantiate the base type.
54710b57cec5SDimitry Andric         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
54720b57cec5SDimitry Andric                                               TemplateArgs,
54730b57cec5SDimitry Andric                                               Init->getSourceLocation(),
54740b57cec5SDimitry Andric                                               New->getDeclName());
54750b57cec5SDimitry Andric         if (!BaseTInfo) {
54760b57cec5SDimitry Andric           AnyErrors = true;
54770b57cec5SDimitry Andric           break;
54780b57cec5SDimitry Andric         }
54790b57cec5SDimitry Andric 
54800b57cec5SDimitry Andric         // Build the initializer.
54810b57cec5SDimitry Andric         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
54820b57cec5SDimitry Andric                                                      BaseTInfo, TempInit.get(),
54830b57cec5SDimitry Andric                                                      New->getParent(),
54840b57cec5SDimitry Andric                                                      SourceLocation());
54850b57cec5SDimitry Andric         if (NewInit.isInvalid()) {
54860b57cec5SDimitry Andric           AnyErrors = true;
54870b57cec5SDimitry Andric           break;
54880b57cec5SDimitry Andric         }
54890b57cec5SDimitry Andric 
54900b57cec5SDimitry Andric         NewInits.push_back(NewInit.get());
54910b57cec5SDimitry Andric       }
54920b57cec5SDimitry Andric 
54930b57cec5SDimitry Andric       continue;
54940b57cec5SDimitry Andric     }
54950b57cec5SDimitry Andric 
54960b57cec5SDimitry Andric     // Instantiate the initializer.
54970b57cec5SDimitry Andric     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
54980b57cec5SDimitry Andric                                            /*CXXDirectInit=*/true);
54990b57cec5SDimitry Andric     if (TempInit.isInvalid()) {
55000b57cec5SDimitry Andric       AnyErrors = true;
55010b57cec5SDimitry Andric       continue;
55020b57cec5SDimitry Andric     }
55030b57cec5SDimitry Andric 
55040b57cec5SDimitry Andric     MemInitResult NewInit;
55050b57cec5SDimitry Andric     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
55060b57cec5SDimitry Andric       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
55070b57cec5SDimitry Andric                                         TemplateArgs,
55080b57cec5SDimitry Andric                                         Init->getSourceLocation(),
55090b57cec5SDimitry Andric                                         New->getDeclName());
55100b57cec5SDimitry Andric       if (!TInfo) {
55110b57cec5SDimitry Andric         AnyErrors = true;
55120b57cec5SDimitry Andric         New->setInvalidDecl();
55130b57cec5SDimitry Andric         continue;
55140b57cec5SDimitry Andric       }
55150b57cec5SDimitry Andric 
55160b57cec5SDimitry Andric       if (Init->isBaseInitializer())
55170b57cec5SDimitry Andric         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
55180b57cec5SDimitry Andric                                        New->getParent(), EllipsisLoc);
55190b57cec5SDimitry Andric       else
55200b57cec5SDimitry Andric         NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
55210b57cec5SDimitry Andric                                   cast<CXXRecordDecl>(CurContext->getParent()));
55220b57cec5SDimitry Andric     } else if (Init->isMemberInitializer()) {
55230b57cec5SDimitry Andric       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
55240b57cec5SDimitry Andric                                                      Init->getMemberLocation(),
55250b57cec5SDimitry Andric                                                      Init->getMember(),
55260b57cec5SDimitry Andric                                                      TemplateArgs));
55270b57cec5SDimitry Andric       if (!Member) {
55280b57cec5SDimitry Andric         AnyErrors = true;
55290b57cec5SDimitry Andric         New->setInvalidDecl();
55300b57cec5SDimitry Andric         continue;
55310b57cec5SDimitry Andric       }
55320b57cec5SDimitry Andric 
55330b57cec5SDimitry Andric       NewInit = BuildMemberInitializer(Member, TempInit.get(),
55340b57cec5SDimitry Andric                                        Init->getSourceLocation());
55350b57cec5SDimitry Andric     } else if (Init->isIndirectMemberInitializer()) {
55360b57cec5SDimitry Andric       IndirectFieldDecl *IndirectMember =
55370b57cec5SDimitry Andric          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
55380b57cec5SDimitry Andric                                  Init->getMemberLocation(),
55390b57cec5SDimitry Andric                                  Init->getIndirectMember(), TemplateArgs));
55400b57cec5SDimitry Andric 
55410b57cec5SDimitry Andric       if (!IndirectMember) {
55420b57cec5SDimitry Andric         AnyErrors = true;
55430b57cec5SDimitry Andric         New->setInvalidDecl();
55440b57cec5SDimitry Andric         continue;
55450b57cec5SDimitry Andric       }
55460b57cec5SDimitry Andric 
55470b57cec5SDimitry Andric       NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
55480b57cec5SDimitry Andric                                        Init->getSourceLocation());
55490b57cec5SDimitry Andric     }
55500b57cec5SDimitry Andric 
55510b57cec5SDimitry Andric     if (NewInit.isInvalid()) {
55520b57cec5SDimitry Andric       AnyErrors = true;
55530b57cec5SDimitry Andric       New->setInvalidDecl();
55540b57cec5SDimitry Andric     } else {
55550b57cec5SDimitry Andric       NewInits.push_back(NewInit.get());
55560b57cec5SDimitry Andric     }
55570b57cec5SDimitry Andric   }
55580b57cec5SDimitry Andric 
55590b57cec5SDimitry Andric   // Assign all the initializers to the new constructor.
55600b57cec5SDimitry Andric   ActOnMemInitializers(New,
55610b57cec5SDimitry Andric                        /*FIXME: ColonLoc */
55620b57cec5SDimitry Andric                        SourceLocation(),
55630b57cec5SDimitry Andric                        NewInits,
55640b57cec5SDimitry Andric                        AnyErrors);
55650b57cec5SDimitry Andric }
55660b57cec5SDimitry Andric 
55670b57cec5SDimitry Andric // TODO: this could be templated if the various decl types used the
55680b57cec5SDimitry Andric // same method name.
55690b57cec5SDimitry Andric static bool isInstantiationOf(ClassTemplateDecl *Pattern,
55700b57cec5SDimitry Andric                               ClassTemplateDecl *Instance) {
55710b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
55720b57cec5SDimitry Andric 
55730b57cec5SDimitry Andric   do {
55740b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
55750b57cec5SDimitry Andric     if (Pattern == Instance) return true;
55760b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberTemplate();
55770b57cec5SDimitry Andric   } while (Instance);
55780b57cec5SDimitry Andric 
55790b57cec5SDimitry Andric   return false;
55800b57cec5SDimitry Andric }
55810b57cec5SDimitry Andric 
55820b57cec5SDimitry Andric static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
55830b57cec5SDimitry Andric                               FunctionTemplateDecl *Instance) {
55840b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
55850b57cec5SDimitry Andric 
55860b57cec5SDimitry Andric   do {
55870b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
55880b57cec5SDimitry Andric     if (Pattern == Instance) return true;
55890b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberTemplate();
55900b57cec5SDimitry Andric   } while (Instance);
55910b57cec5SDimitry Andric 
55920b57cec5SDimitry Andric   return false;
55930b57cec5SDimitry Andric }
55940b57cec5SDimitry Andric 
55950b57cec5SDimitry Andric static bool
55960b57cec5SDimitry Andric isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
55970b57cec5SDimitry Andric                   ClassTemplatePartialSpecializationDecl *Instance) {
55980b57cec5SDimitry Andric   Pattern
55990b57cec5SDimitry Andric     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
56000b57cec5SDimitry Andric   do {
56010b57cec5SDimitry Andric     Instance = cast<ClassTemplatePartialSpecializationDecl>(
56020b57cec5SDimitry Andric                                                 Instance->getCanonicalDecl());
56030b57cec5SDimitry Andric     if (Pattern == Instance)
56040b57cec5SDimitry Andric       return true;
56050b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMember();
56060b57cec5SDimitry Andric   } while (Instance);
56070b57cec5SDimitry Andric 
56080b57cec5SDimitry Andric   return false;
56090b57cec5SDimitry Andric }
56100b57cec5SDimitry Andric 
56110b57cec5SDimitry Andric static bool isInstantiationOf(CXXRecordDecl *Pattern,
56120b57cec5SDimitry Andric                               CXXRecordDecl *Instance) {
56130b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
56140b57cec5SDimitry Andric 
56150b57cec5SDimitry Andric   do {
56160b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
56170b57cec5SDimitry Andric     if (Pattern == Instance) return true;
56180b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberClass();
56190b57cec5SDimitry Andric   } while (Instance);
56200b57cec5SDimitry Andric 
56210b57cec5SDimitry Andric   return false;
56220b57cec5SDimitry Andric }
56230b57cec5SDimitry Andric 
56240b57cec5SDimitry Andric static bool isInstantiationOf(FunctionDecl *Pattern,
56250b57cec5SDimitry Andric                               FunctionDecl *Instance) {
56260b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
56270b57cec5SDimitry Andric 
56280b57cec5SDimitry Andric   do {
56290b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
56300b57cec5SDimitry Andric     if (Pattern == Instance) return true;
56310b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberFunction();
56320b57cec5SDimitry Andric   } while (Instance);
56330b57cec5SDimitry Andric 
56340b57cec5SDimitry Andric   return false;
56350b57cec5SDimitry Andric }
56360b57cec5SDimitry Andric 
56370b57cec5SDimitry Andric static bool isInstantiationOf(EnumDecl *Pattern,
56380b57cec5SDimitry Andric                               EnumDecl *Instance) {
56390b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
56400b57cec5SDimitry Andric 
56410b57cec5SDimitry Andric   do {
56420b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
56430b57cec5SDimitry Andric     if (Pattern == Instance) return true;
56440b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromMemberEnum();
56450b57cec5SDimitry Andric   } while (Instance);
56460b57cec5SDimitry Andric 
56470b57cec5SDimitry Andric   return false;
56480b57cec5SDimitry Andric }
56490b57cec5SDimitry Andric 
56500b57cec5SDimitry Andric static bool isInstantiationOf(UsingShadowDecl *Pattern,
56510b57cec5SDimitry Andric                               UsingShadowDecl *Instance,
56520b57cec5SDimitry Andric                               ASTContext &C) {
56530b57cec5SDimitry Andric   return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
56540b57cec5SDimitry Andric                             Pattern);
56550b57cec5SDimitry Andric }
56560b57cec5SDimitry Andric 
56570b57cec5SDimitry Andric static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
56580b57cec5SDimitry Andric                               ASTContext &C) {
56590b57cec5SDimitry Andric   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
56600b57cec5SDimitry Andric }
56610b57cec5SDimitry Andric 
56620b57cec5SDimitry Andric template<typename T>
56630b57cec5SDimitry Andric static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
56640b57cec5SDimitry Andric                                                  ASTContext &Ctx) {
56650b57cec5SDimitry Andric   // An unresolved using declaration can instantiate to an unresolved using
56660b57cec5SDimitry Andric   // declaration, or to a using declaration or a using declaration pack.
56670b57cec5SDimitry Andric   //
56680b57cec5SDimitry Andric   // Multiple declarations can claim to be instantiated from an unresolved
56690b57cec5SDimitry Andric   // using declaration if it's a pack expansion. We want the UsingPackDecl
56700b57cec5SDimitry Andric   // in that case, not the individual UsingDecls within the pack.
56710b57cec5SDimitry Andric   bool OtherIsPackExpansion;
56720b57cec5SDimitry Andric   NamedDecl *OtherFrom;
56730b57cec5SDimitry Andric   if (auto *OtherUUD = dyn_cast<T>(Other)) {
56740b57cec5SDimitry Andric     OtherIsPackExpansion = OtherUUD->isPackExpansion();
56750b57cec5SDimitry Andric     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
56760b57cec5SDimitry Andric   } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
56770b57cec5SDimitry Andric     OtherIsPackExpansion = true;
56780b57cec5SDimitry Andric     OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
56790b57cec5SDimitry Andric   } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
56800b57cec5SDimitry Andric     OtherIsPackExpansion = false;
56810b57cec5SDimitry Andric     OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
56820b57cec5SDimitry Andric   } else {
56830b57cec5SDimitry Andric     return false;
56840b57cec5SDimitry Andric   }
56850b57cec5SDimitry Andric   return Pattern->isPackExpansion() == OtherIsPackExpansion &&
56860b57cec5SDimitry Andric          declaresSameEntity(OtherFrom, Pattern);
56870b57cec5SDimitry Andric }
56880b57cec5SDimitry Andric 
56890b57cec5SDimitry Andric static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
56900b57cec5SDimitry Andric                                               VarDecl *Instance) {
56910b57cec5SDimitry Andric   assert(Instance->isStaticDataMember());
56920b57cec5SDimitry Andric 
56930b57cec5SDimitry Andric   Pattern = Pattern->getCanonicalDecl();
56940b57cec5SDimitry Andric 
56950b57cec5SDimitry Andric   do {
56960b57cec5SDimitry Andric     Instance = Instance->getCanonicalDecl();
56970b57cec5SDimitry Andric     if (Pattern == Instance) return true;
56980b57cec5SDimitry Andric     Instance = Instance->getInstantiatedFromStaticDataMember();
56990b57cec5SDimitry Andric   } while (Instance);
57000b57cec5SDimitry Andric 
57010b57cec5SDimitry Andric   return false;
57020b57cec5SDimitry Andric }
57030b57cec5SDimitry Andric 
57040b57cec5SDimitry Andric // Other is the prospective instantiation
57050b57cec5SDimitry Andric // D is the prospective pattern
57060b57cec5SDimitry Andric static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
57070b57cec5SDimitry Andric   if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
57080b57cec5SDimitry Andric     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
57090b57cec5SDimitry Andric 
57100b57cec5SDimitry Andric   if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
57110b57cec5SDimitry Andric     return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
57120b57cec5SDimitry Andric 
57130b57cec5SDimitry Andric   if (D->getKind() != Other->getKind())
57140b57cec5SDimitry Andric     return false;
57150b57cec5SDimitry Andric 
57160b57cec5SDimitry Andric   if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
57170b57cec5SDimitry Andric     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
57180b57cec5SDimitry Andric 
57190b57cec5SDimitry Andric   if (auto *Function = dyn_cast<FunctionDecl>(Other))
57200b57cec5SDimitry Andric     return isInstantiationOf(cast<FunctionDecl>(D), Function);
57210b57cec5SDimitry Andric 
57220b57cec5SDimitry Andric   if (auto *Enum = dyn_cast<EnumDecl>(Other))
57230b57cec5SDimitry Andric     return isInstantiationOf(cast<EnumDecl>(D), Enum);
57240b57cec5SDimitry Andric 
57250b57cec5SDimitry Andric   if (auto *Var = dyn_cast<VarDecl>(Other))
57260b57cec5SDimitry Andric     if (Var->isStaticDataMember())
57270b57cec5SDimitry Andric       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
57280b57cec5SDimitry Andric 
57290b57cec5SDimitry Andric   if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
57300b57cec5SDimitry Andric     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
57310b57cec5SDimitry Andric 
57320b57cec5SDimitry Andric   if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
57330b57cec5SDimitry Andric     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
57340b57cec5SDimitry Andric 
57350b57cec5SDimitry Andric   if (auto *PartialSpec =
57360b57cec5SDimitry Andric           dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
57370b57cec5SDimitry Andric     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
57380b57cec5SDimitry Andric                              PartialSpec);
57390b57cec5SDimitry Andric 
57400b57cec5SDimitry Andric   if (auto *Field = dyn_cast<FieldDecl>(Other)) {
57410b57cec5SDimitry Andric     if (!Field->getDeclName()) {
57420b57cec5SDimitry Andric       // This is an unnamed field.
57430b57cec5SDimitry Andric       return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
57440b57cec5SDimitry Andric                                 cast<FieldDecl>(D));
57450b57cec5SDimitry Andric     }
57460b57cec5SDimitry Andric   }
57470b57cec5SDimitry Andric 
57480b57cec5SDimitry Andric   if (auto *Using = dyn_cast<UsingDecl>(Other))
57490b57cec5SDimitry Andric     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
57500b57cec5SDimitry Andric 
57510b57cec5SDimitry Andric   if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
57520b57cec5SDimitry Andric     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
57530b57cec5SDimitry Andric 
57540b57cec5SDimitry Andric   return D->getDeclName() &&
57550b57cec5SDimitry Andric          D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
57560b57cec5SDimitry Andric }
57570b57cec5SDimitry Andric 
57580b57cec5SDimitry Andric template<typename ForwardIterator>
57590b57cec5SDimitry Andric static NamedDecl *findInstantiationOf(ASTContext &Ctx,
57600b57cec5SDimitry Andric                                       NamedDecl *D,
57610b57cec5SDimitry Andric                                       ForwardIterator first,
57620b57cec5SDimitry Andric                                       ForwardIterator last) {
57630b57cec5SDimitry Andric   for (; first != last; ++first)
57640b57cec5SDimitry Andric     if (isInstantiationOf(Ctx, D, *first))
57650b57cec5SDimitry Andric       return cast<NamedDecl>(*first);
57660b57cec5SDimitry Andric 
57670b57cec5SDimitry Andric   return nullptr;
57680b57cec5SDimitry Andric }
57690b57cec5SDimitry Andric 
57700b57cec5SDimitry Andric /// Finds the instantiation of the given declaration context
57710b57cec5SDimitry Andric /// within the current instantiation.
57720b57cec5SDimitry Andric ///
57730b57cec5SDimitry Andric /// \returns NULL if there was an error
57740b57cec5SDimitry Andric DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
57750b57cec5SDimitry Andric                           const MultiLevelTemplateArgumentList &TemplateArgs) {
57760b57cec5SDimitry Andric   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
57770b57cec5SDimitry Andric     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
57780b57cec5SDimitry Andric     return cast_or_null<DeclContext>(ID);
57790b57cec5SDimitry Andric   } else return DC;
57800b57cec5SDimitry Andric }
57810b57cec5SDimitry Andric 
57825ffd83dbSDimitry Andric /// Determine whether the given context is dependent on template parameters at
57835ffd83dbSDimitry Andric /// level \p Level or below.
57845ffd83dbSDimitry Andric ///
57855ffd83dbSDimitry Andric /// Sometimes we only substitute an inner set of template arguments and leave
57865ffd83dbSDimitry Andric /// the outer templates alone. In such cases, contexts dependent only on the
57875ffd83dbSDimitry Andric /// outer levels are not effectively dependent.
57885ffd83dbSDimitry Andric static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
57895ffd83dbSDimitry Andric   if (!DC->isDependentContext())
57905ffd83dbSDimitry Andric     return false;
57915ffd83dbSDimitry Andric   if (!Level)
57925ffd83dbSDimitry Andric     return true;
57935ffd83dbSDimitry Andric   return cast<Decl>(DC)->getTemplateDepth() > Level;
57945ffd83dbSDimitry Andric }
57955ffd83dbSDimitry Andric 
57960b57cec5SDimitry Andric /// Find the instantiation of the given declaration within the
57970b57cec5SDimitry Andric /// current instantiation.
57980b57cec5SDimitry Andric ///
57990b57cec5SDimitry Andric /// This routine is intended to be used when \p D is a declaration
58000b57cec5SDimitry Andric /// referenced from within a template, that needs to mapped into the
58010b57cec5SDimitry Andric /// corresponding declaration within an instantiation. For example,
58020b57cec5SDimitry Andric /// given:
58030b57cec5SDimitry Andric ///
58040b57cec5SDimitry Andric /// \code
58050b57cec5SDimitry Andric /// template<typename T>
58060b57cec5SDimitry Andric /// struct X {
58070b57cec5SDimitry Andric ///   enum Kind {
58080b57cec5SDimitry Andric ///     KnownValue = sizeof(T)
58090b57cec5SDimitry Andric ///   };
58100b57cec5SDimitry Andric ///
58110b57cec5SDimitry Andric ///   bool getKind() const { return KnownValue; }
58120b57cec5SDimitry Andric /// };
58130b57cec5SDimitry Andric ///
58140b57cec5SDimitry Andric /// template struct X<int>;
58150b57cec5SDimitry Andric /// \endcode
58160b57cec5SDimitry Andric ///
5817a7dea167SDimitry Andric /// In the instantiation of X<int>::getKind(), we need to map the \p
5818a7dea167SDimitry Andric /// EnumConstantDecl for \p KnownValue (which refers to
5819a7dea167SDimitry Andric /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
5820a7dea167SDimitry Andric /// \p FindInstantiatedDecl performs this mapping from within the instantiation
5821a7dea167SDimitry Andric /// of X<int>.
58220b57cec5SDimitry Andric NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
58230b57cec5SDimitry Andric                           const MultiLevelTemplateArgumentList &TemplateArgs,
58240b57cec5SDimitry Andric                           bool FindingInstantiatedContext) {
58250b57cec5SDimitry Andric   DeclContext *ParentDC = D->getDeclContext();
58265ffd83dbSDimitry Andric   // Determine whether our parent context depends on any of the tempalte
58275ffd83dbSDimitry Andric   // arguments we're currently substituting.
58285ffd83dbSDimitry Andric   bool ParentDependsOnArgs = isDependentContextAtLevel(
58295ffd83dbSDimitry Andric       ParentDC, TemplateArgs.getNumRetainedOuterLevels());
58300b57cec5SDimitry Andric   // FIXME: Parmeters of pointer to functions (y below) that are themselves
58310b57cec5SDimitry Andric   // parameters (p below) can have their ParentDC set to the translation-unit
58320b57cec5SDimitry Andric   // - thus we can not consistently check if the ParentDC of such a parameter
58330b57cec5SDimitry Andric   // is Dependent or/and a FunctionOrMethod.
58340b57cec5SDimitry Andric   // For e.g. this code, during Template argument deduction tries to
58350b57cec5SDimitry Andric   // find an instantiated decl for (T y) when the ParentDC for y is
58360b57cec5SDimitry Andric   // the translation unit.
58370b57cec5SDimitry Andric   //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
58380b57cec5SDimitry Andric   //   float baz(float(*)()) { return 0.0; }
58390b57cec5SDimitry Andric   //   Foo(baz);
58400b57cec5SDimitry Andric   // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
58410b57cec5SDimitry Andric   // it gets here, always has a FunctionOrMethod as its ParentDC??
58420b57cec5SDimitry Andric   // For now:
58430b57cec5SDimitry Andric   //  - as long as we have a ParmVarDecl whose parent is non-dependent and
58440b57cec5SDimitry Andric   //    whose type is not instantiation dependent, do nothing to the decl
58450b57cec5SDimitry Andric   //  - otherwise find its instantiated decl.
58465ffd83dbSDimitry Andric   if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
58470b57cec5SDimitry Andric       !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
58480b57cec5SDimitry Andric     return D;
58490b57cec5SDimitry Andric   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
58500b57cec5SDimitry Andric       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
58515ffd83dbSDimitry Andric       (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
58520b57cec5SDimitry Andric                                isa<OMPDeclareReductionDecl>(ParentDC) ||
58535ffd83dbSDimitry Andric                                isa<OMPDeclareMapperDecl>(ParentDC))) ||
58540b57cec5SDimitry Andric       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
58550b57cec5SDimitry Andric     // D is a local of some kind. Look into the map of local
58560b57cec5SDimitry Andric     // declarations to their instantiations.
58570b57cec5SDimitry Andric     if (CurrentInstantiationScope) {
58580b57cec5SDimitry Andric       if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
58590b57cec5SDimitry Andric         if (Decl *FD = Found->dyn_cast<Decl *>())
58600b57cec5SDimitry Andric           return cast<NamedDecl>(FD);
58610b57cec5SDimitry Andric 
58620b57cec5SDimitry Andric         int PackIdx = ArgumentPackSubstitutionIndex;
58630b57cec5SDimitry Andric         assert(PackIdx != -1 &&
58640b57cec5SDimitry Andric                "found declaration pack but not pack expanding");
58650b57cec5SDimitry Andric         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
58660b57cec5SDimitry Andric         return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
58670b57cec5SDimitry Andric       }
58680b57cec5SDimitry Andric     }
58690b57cec5SDimitry Andric 
58700b57cec5SDimitry Andric     // If we're performing a partial substitution during template argument
58710b57cec5SDimitry Andric     // deduction, we may not have values for template parameters yet. They
58720b57cec5SDimitry Andric     // just map to themselves.
58730b57cec5SDimitry Andric     if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
58740b57cec5SDimitry Andric         isa<TemplateTemplateParmDecl>(D))
58750b57cec5SDimitry Andric       return D;
58760b57cec5SDimitry Andric 
58770b57cec5SDimitry Andric     if (D->isInvalidDecl())
58780b57cec5SDimitry Andric       return nullptr;
58790b57cec5SDimitry Andric 
58800b57cec5SDimitry Andric     // Normally this function only searches for already instantiated declaration
58810b57cec5SDimitry Andric     // however we have to make an exclusion for local types used before
58820b57cec5SDimitry Andric     // definition as in the code:
58830b57cec5SDimitry Andric     //
58840b57cec5SDimitry Andric     //   template<typename T> void f1() {
58850b57cec5SDimitry Andric     //     void g1(struct x1);
58860b57cec5SDimitry Andric     //     struct x1 {};
58870b57cec5SDimitry Andric     //   }
58880b57cec5SDimitry Andric     //
58890b57cec5SDimitry Andric     // In this case instantiation of the type of 'g1' requires definition of
58900b57cec5SDimitry Andric     // 'x1', which is defined later. Error recovery may produce an enum used
58910b57cec5SDimitry Andric     // before definition. In these cases we need to instantiate relevant
58920b57cec5SDimitry Andric     // declarations here.
58930b57cec5SDimitry Andric     bool NeedInstantiate = false;
58940b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
58950b57cec5SDimitry Andric       NeedInstantiate = RD->isLocalClass();
58965ffd83dbSDimitry Andric     else if (isa<TypedefNameDecl>(D) &&
58975ffd83dbSDimitry Andric              isa<CXXDeductionGuideDecl>(D->getDeclContext()))
58985ffd83dbSDimitry Andric       NeedInstantiate = true;
58990b57cec5SDimitry Andric     else
59000b57cec5SDimitry Andric       NeedInstantiate = isa<EnumDecl>(D);
59010b57cec5SDimitry Andric     if (NeedInstantiate) {
59020b57cec5SDimitry Andric       Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
59030b57cec5SDimitry Andric       CurrentInstantiationScope->InstantiatedLocal(D, Inst);
59040b57cec5SDimitry Andric       return cast<TypeDecl>(Inst);
59050b57cec5SDimitry Andric     }
59060b57cec5SDimitry Andric 
59070b57cec5SDimitry Andric     // If we didn't find the decl, then we must have a label decl that hasn't
59080b57cec5SDimitry Andric     // been found yet.  Lazily instantiate it and return it now.
59090b57cec5SDimitry Andric     assert(isa<LabelDecl>(D));
59100b57cec5SDimitry Andric 
59110b57cec5SDimitry Andric     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
59120b57cec5SDimitry Andric     assert(Inst && "Failed to instantiate label??");
59130b57cec5SDimitry Andric 
59140b57cec5SDimitry Andric     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
59150b57cec5SDimitry Andric     return cast<LabelDecl>(Inst);
59160b57cec5SDimitry Andric   }
59170b57cec5SDimitry Andric 
59180b57cec5SDimitry Andric   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
59190b57cec5SDimitry Andric     if (!Record->isDependentContext())
59200b57cec5SDimitry Andric       return D;
59210b57cec5SDimitry Andric 
59220b57cec5SDimitry Andric     // Determine whether this record is the "templated" declaration describing
59230b57cec5SDimitry Andric     // a class template or class template partial specialization.
59240b57cec5SDimitry Andric     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
59250b57cec5SDimitry Andric     if (ClassTemplate)
59260b57cec5SDimitry Andric       ClassTemplate = ClassTemplate->getCanonicalDecl();
59270b57cec5SDimitry Andric     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
59280b57cec5SDimitry Andric                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
59290b57cec5SDimitry Andric       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
59300b57cec5SDimitry Andric 
59310b57cec5SDimitry Andric     // Walk the current context to find either the record or an instantiation of
59320b57cec5SDimitry Andric     // it.
59330b57cec5SDimitry Andric     DeclContext *DC = CurContext;
59340b57cec5SDimitry Andric     while (!DC->isFileContext()) {
59350b57cec5SDimitry Andric       // If we're performing substitution while we're inside the template
59360b57cec5SDimitry Andric       // definition, we'll find our own context. We're done.
59370b57cec5SDimitry Andric       if (DC->Equals(Record))
59380b57cec5SDimitry Andric         return Record;
59390b57cec5SDimitry Andric 
59400b57cec5SDimitry Andric       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
59410b57cec5SDimitry Andric         // Check whether we're in the process of instantiating a class template
59420b57cec5SDimitry Andric         // specialization of the template we're mapping.
59430b57cec5SDimitry Andric         if (ClassTemplateSpecializationDecl *InstSpec
59440b57cec5SDimitry Andric                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
59450b57cec5SDimitry Andric           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
59460b57cec5SDimitry Andric           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
59470b57cec5SDimitry Andric             return InstRecord;
59480b57cec5SDimitry Andric         }
59490b57cec5SDimitry Andric 
59500b57cec5SDimitry Andric         // Check whether we're in the process of instantiating a member class.
59510b57cec5SDimitry Andric         if (isInstantiationOf(Record, InstRecord))
59520b57cec5SDimitry Andric           return InstRecord;
59530b57cec5SDimitry Andric       }
59540b57cec5SDimitry Andric 
59550b57cec5SDimitry Andric       // Move to the outer template scope.
59560b57cec5SDimitry Andric       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
59570b57cec5SDimitry Andric         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
59580b57cec5SDimitry Andric           DC = FD->getLexicalDeclContext();
59590b57cec5SDimitry Andric           continue;
59600b57cec5SDimitry Andric         }
59610b57cec5SDimitry Andric         // An implicit deduction guide acts as if it's within the class template
59620b57cec5SDimitry Andric         // specialization described by its name and first N template params.
59630b57cec5SDimitry Andric         auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
59640b57cec5SDimitry Andric         if (Guide && Guide->isImplicit()) {
59650b57cec5SDimitry Andric           TemplateDecl *TD = Guide->getDeducedTemplate();
59660b57cec5SDimitry Andric           // Convert the arguments to an "as-written" list.
59670b57cec5SDimitry Andric           TemplateArgumentListInfo Args(Loc, Loc);
59680b57cec5SDimitry Andric           for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
59690b57cec5SDimitry Andric                                         TD->getTemplateParameters()->size())) {
59700b57cec5SDimitry Andric             ArrayRef<TemplateArgument> Unpacked(Arg);
59710b57cec5SDimitry Andric             if (Arg.getKind() == TemplateArgument::Pack)
59720b57cec5SDimitry Andric               Unpacked = Arg.pack_elements();
59730b57cec5SDimitry Andric             for (TemplateArgument UnpackedArg : Unpacked)
59740b57cec5SDimitry Andric               Args.addArgument(
59750b57cec5SDimitry Andric                   getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
59760b57cec5SDimitry Andric           }
59770b57cec5SDimitry Andric           QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
59780b57cec5SDimitry Andric           if (T.isNull())
59790b57cec5SDimitry Andric             return nullptr;
59800b57cec5SDimitry Andric           auto *SubstRecord = T->getAsCXXRecordDecl();
59810b57cec5SDimitry Andric           assert(SubstRecord && "class template id not a class type?");
59820b57cec5SDimitry Andric           // Check that this template-id names the primary template and not a
59830b57cec5SDimitry Andric           // partial or explicit specialization. (In the latter cases, it's
59840b57cec5SDimitry Andric           // meaningless to attempt to find an instantiation of D within the
59850b57cec5SDimitry Andric           // specialization.)
59860b57cec5SDimitry Andric           // FIXME: The standard doesn't say what should happen here.
59870b57cec5SDimitry Andric           if (FindingInstantiatedContext &&
59880b57cec5SDimitry Andric               usesPartialOrExplicitSpecialization(
59890b57cec5SDimitry Andric                   Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
59900b57cec5SDimitry Andric             Diag(Loc, diag::err_specialization_not_primary_template)
59910b57cec5SDimitry Andric               << T << (SubstRecord->getTemplateSpecializationKind() ==
59920b57cec5SDimitry Andric                            TSK_ExplicitSpecialization);
59930b57cec5SDimitry Andric             return nullptr;
59940b57cec5SDimitry Andric           }
59950b57cec5SDimitry Andric           DC = SubstRecord;
59960b57cec5SDimitry Andric           continue;
59970b57cec5SDimitry Andric         }
59980b57cec5SDimitry Andric       }
59990b57cec5SDimitry Andric 
60000b57cec5SDimitry Andric       DC = DC->getParent();
60010b57cec5SDimitry Andric     }
60020b57cec5SDimitry Andric 
60030b57cec5SDimitry Andric     // Fall through to deal with other dependent record types (e.g.,
60040b57cec5SDimitry Andric     // anonymous unions in class templates).
60050b57cec5SDimitry Andric   }
60060b57cec5SDimitry Andric 
60075ffd83dbSDimitry Andric   if (!ParentDependsOnArgs)
60080b57cec5SDimitry Andric     return D;
60090b57cec5SDimitry Andric 
60100b57cec5SDimitry Andric   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
60110b57cec5SDimitry Andric   if (!ParentDC)
60120b57cec5SDimitry Andric     return nullptr;
60130b57cec5SDimitry Andric 
60140b57cec5SDimitry Andric   if (ParentDC != D->getDeclContext()) {
60150b57cec5SDimitry Andric     // We performed some kind of instantiation in the parent context,
60160b57cec5SDimitry Andric     // so now we need to look into the instantiated parent context to
60170b57cec5SDimitry Andric     // find the instantiation of the declaration D.
60180b57cec5SDimitry Andric 
60190b57cec5SDimitry Andric     // If our context used to be dependent, we may need to instantiate
60200b57cec5SDimitry Andric     // it before performing lookup into that context.
60210b57cec5SDimitry Andric     bool IsBeingInstantiated = false;
60220b57cec5SDimitry Andric     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
60230b57cec5SDimitry Andric       if (!Spec->isDependentContext()) {
60240b57cec5SDimitry Andric         QualType T = Context.getTypeDeclType(Spec);
60250b57cec5SDimitry Andric         const RecordType *Tag = T->getAs<RecordType>();
60260b57cec5SDimitry Andric         assert(Tag && "type of non-dependent record is not a RecordType");
60270b57cec5SDimitry Andric         if (Tag->isBeingDefined())
60280b57cec5SDimitry Andric           IsBeingInstantiated = true;
60290b57cec5SDimitry Andric         if (!Tag->isBeingDefined() &&
60300b57cec5SDimitry Andric             RequireCompleteType(Loc, T, diag::err_incomplete_type))
60310b57cec5SDimitry Andric           return nullptr;
60320b57cec5SDimitry Andric 
60330b57cec5SDimitry Andric         ParentDC = Tag->getDecl();
60340b57cec5SDimitry Andric       }
60350b57cec5SDimitry Andric     }
60360b57cec5SDimitry Andric 
60370b57cec5SDimitry Andric     NamedDecl *Result = nullptr;
60380b57cec5SDimitry Andric     // FIXME: If the name is a dependent name, this lookup won't necessarily
60390b57cec5SDimitry Andric     // find it. Does that ever matter?
60400b57cec5SDimitry Andric     if (auto Name = D->getDeclName()) {
60410b57cec5SDimitry Andric       DeclarationNameInfo NameInfo(Name, D->getLocation());
6042a7dea167SDimitry Andric       DeclarationNameInfo NewNameInfo =
6043a7dea167SDimitry Andric           SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6044a7dea167SDimitry Andric       Name = NewNameInfo.getName();
60450b57cec5SDimitry Andric       if (!Name)
60460b57cec5SDimitry Andric         return nullptr;
60470b57cec5SDimitry Andric       DeclContext::lookup_result Found = ParentDC->lookup(Name);
6048a7dea167SDimitry Andric 
60490b57cec5SDimitry Andric       Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
60500b57cec5SDimitry Andric     } else {
60510b57cec5SDimitry Andric       // Since we don't have a name for the entity we're looking for,
60520b57cec5SDimitry Andric       // our only option is to walk through all of the declarations to
60530b57cec5SDimitry Andric       // find that name. This will occur in a few cases:
60540b57cec5SDimitry Andric       //
60550b57cec5SDimitry Andric       //   - anonymous struct/union within a template
60560b57cec5SDimitry Andric       //   - unnamed class/struct/union/enum within a template
60570b57cec5SDimitry Andric       //
60580b57cec5SDimitry Andric       // FIXME: Find a better way to find these instantiations!
60590b57cec5SDimitry Andric       Result = findInstantiationOf(Context, D,
60600b57cec5SDimitry Andric                                    ParentDC->decls_begin(),
60610b57cec5SDimitry Andric                                    ParentDC->decls_end());
60620b57cec5SDimitry Andric     }
60630b57cec5SDimitry Andric 
60640b57cec5SDimitry Andric     if (!Result) {
60650b57cec5SDimitry Andric       if (isa<UsingShadowDecl>(D)) {
60660b57cec5SDimitry Andric         // UsingShadowDecls can instantiate to nothing because of using hiding.
6067*e8d8bef9SDimitry Andric       } else if (hasUncompilableErrorOccurred()) {
60685ffd83dbSDimitry Andric         // We've already complained about some ill-formed code, so most likely
60695ffd83dbSDimitry Andric         // this declaration failed to instantiate. There's no point in
60705ffd83dbSDimitry Andric         // complaining further, since this is normal in invalid code.
60715ffd83dbSDimitry Andric         // FIXME: Use more fine-grained 'invalid' tracking for this.
60720b57cec5SDimitry Andric       } else if (IsBeingInstantiated) {
60730b57cec5SDimitry Andric         // The class in which this member exists is currently being
60740b57cec5SDimitry Andric         // instantiated, and we haven't gotten around to instantiating this
60750b57cec5SDimitry Andric         // member yet. This can happen when the code uses forward declarations
60760b57cec5SDimitry Andric         // of member classes, and introduces ordering dependencies via
60770b57cec5SDimitry Andric         // template instantiation.
60780b57cec5SDimitry Andric         Diag(Loc, diag::err_member_not_yet_instantiated)
60790b57cec5SDimitry Andric           << D->getDeclName()
60800b57cec5SDimitry Andric           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
60810b57cec5SDimitry Andric         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
60820b57cec5SDimitry Andric       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
60830b57cec5SDimitry Andric         // This enumeration constant was found when the template was defined,
60840b57cec5SDimitry Andric         // but can't be found in the instantiation. This can happen if an
60850b57cec5SDimitry Andric         // unscoped enumeration member is explicitly specialized.
60860b57cec5SDimitry Andric         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
60870b57cec5SDimitry Andric         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
60880b57cec5SDimitry Andric                                                              TemplateArgs));
60890b57cec5SDimitry Andric         assert(Spec->getTemplateSpecializationKind() ==
60900b57cec5SDimitry Andric                  TSK_ExplicitSpecialization);
60910b57cec5SDimitry Andric         Diag(Loc, diag::err_enumerator_does_not_exist)
60920b57cec5SDimitry Andric           << D->getDeclName()
60930b57cec5SDimitry Andric           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
60940b57cec5SDimitry Andric         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
60950b57cec5SDimitry Andric           << Context.getTypeDeclType(Spec);
60960b57cec5SDimitry Andric       } else {
60970b57cec5SDimitry Andric         // We should have found something, but didn't.
60980b57cec5SDimitry Andric         llvm_unreachable("Unable to find instantiation of declaration!");
60990b57cec5SDimitry Andric       }
61000b57cec5SDimitry Andric     }
61010b57cec5SDimitry Andric 
61020b57cec5SDimitry Andric     D = Result;
61030b57cec5SDimitry Andric   }
61040b57cec5SDimitry Andric 
61050b57cec5SDimitry Andric   return D;
61060b57cec5SDimitry Andric }
61070b57cec5SDimitry Andric 
61080b57cec5SDimitry Andric /// Performs template instantiation for all implicit template
61090b57cec5SDimitry Andric /// instantiations we have seen until this point.
61100b57cec5SDimitry Andric void Sema::PerformPendingInstantiations(bool LocalOnly) {
61115ffd83dbSDimitry Andric   std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
61120b57cec5SDimitry Andric   while (!PendingLocalImplicitInstantiations.empty() ||
61130b57cec5SDimitry Andric          (!LocalOnly && !PendingInstantiations.empty())) {
61140b57cec5SDimitry Andric     PendingImplicitInstantiation Inst;
61150b57cec5SDimitry Andric 
61160b57cec5SDimitry Andric     if (PendingLocalImplicitInstantiations.empty()) {
61170b57cec5SDimitry Andric       Inst = PendingInstantiations.front();
61180b57cec5SDimitry Andric       PendingInstantiations.pop_front();
61190b57cec5SDimitry Andric     } else {
61200b57cec5SDimitry Andric       Inst = PendingLocalImplicitInstantiations.front();
61210b57cec5SDimitry Andric       PendingLocalImplicitInstantiations.pop_front();
61220b57cec5SDimitry Andric     }
61230b57cec5SDimitry Andric 
61240b57cec5SDimitry Andric     // Instantiate function definitions
61250b57cec5SDimitry Andric     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
61260b57cec5SDimitry Andric       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
61270b57cec5SDimitry Andric                                 TSK_ExplicitInstantiationDefinition;
61280b57cec5SDimitry Andric       if (Function->isMultiVersion()) {
61290b57cec5SDimitry Andric         getASTContext().forEachMultiversionedFunctionVersion(
61300b57cec5SDimitry Andric             Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
61310b57cec5SDimitry Andric               InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
61320b57cec5SDimitry Andric                                             DefinitionRequired, true);
61330b57cec5SDimitry Andric               if (CurFD->isDefined())
61340b57cec5SDimitry Andric                 CurFD->setInstantiationIsPending(false);
61350b57cec5SDimitry Andric             });
61360b57cec5SDimitry Andric       } else {
61370b57cec5SDimitry Andric         InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
61380b57cec5SDimitry Andric                                       DefinitionRequired, true);
61390b57cec5SDimitry Andric         if (Function->isDefined())
61400b57cec5SDimitry Andric           Function->setInstantiationIsPending(false);
61410b57cec5SDimitry Andric       }
61425ffd83dbSDimitry Andric       // Definition of a PCH-ed template declaration may be available only in the TU.
61435ffd83dbSDimitry Andric       if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
61445ffd83dbSDimitry Andric           TUKind == TU_Prefix && Function->instantiationIsPending())
61455ffd83dbSDimitry Andric         delayedPCHInstantiations.push_back(Inst);
61460b57cec5SDimitry Andric       continue;
61470b57cec5SDimitry Andric     }
61480b57cec5SDimitry Andric 
61490b57cec5SDimitry Andric     // Instantiate variable definitions
61500b57cec5SDimitry Andric     VarDecl *Var = cast<VarDecl>(Inst.first);
61510b57cec5SDimitry Andric 
61520b57cec5SDimitry Andric     assert((Var->isStaticDataMember() ||
61530b57cec5SDimitry Andric             isa<VarTemplateSpecializationDecl>(Var)) &&
61540b57cec5SDimitry Andric            "Not a static data member, nor a variable template"
61550b57cec5SDimitry Andric            " specialization?");
61560b57cec5SDimitry Andric 
61570b57cec5SDimitry Andric     // Don't try to instantiate declarations if the most recent redeclaration
61580b57cec5SDimitry Andric     // is invalid.
61590b57cec5SDimitry Andric     if (Var->getMostRecentDecl()->isInvalidDecl())
61600b57cec5SDimitry Andric       continue;
61610b57cec5SDimitry Andric 
61620b57cec5SDimitry Andric     // Check if the most recent declaration has changed the specialization kind
61630b57cec5SDimitry Andric     // and removed the need for implicit instantiation.
61640b57cec5SDimitry Andric     switch (Var->getMostRecentDecl()
61650b57cec5SDimitry Andric                 ->getTemplateSpecializationKindForInstantiation()) {
61660b57cec5SDimitry Andric     case TSK_Undeclared:
61670b57cec5SDimitry Andric       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
61680b57cec5SDimitry Andric     case TSK_ExplicitInstantiationDeclaration:
61690b57cec5SDimitry Andric     case TSK_ExplicitSpecialization:
61700b57cec5SDimitry Andric       continue;  // No longer need to instantiate this type.
61710b57cec5SDimitry Andric     case TSK_ExplicitInstantiationDefinition:
61720b57cec5SDimitry Andric       // We only need an instantiation if the pending instantiation *is* the
61730b57cec5SDimitry Andric       // explicit instantiation.
61740b57cec5SDimitry Andric       if (Var != Var->getMostRecentDecl())
61750b57cec5SDimitry Andric         continue;
61760b57cec5SDimitry Andric       break;
61770b57cec5SDimitry Andric     case TSK_ImplicitInstantiation:
61780b57cec5SDimitry Andric       break;
61790b57cec5SDimitry Andric     }
61800b57cec5SDimitry Andric 
61810b57cec5SDimitry Andric     PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
61820b57cec5SDimitry Andric                                         "instantiating variable definition");
61830b57cec5SDimitry Andric     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
61840b57cec5SDimitry Andric                               TSK_ExplicitInstantiationDefinition;
61850b57cec5SDimitry Andric 
61860b57cec5SDimitry Andric     // Instantiate static data member definitions or variable template
61870b57cec5SDimitry Andric     // specializations.
61880b57cec5SDimitry Andric     InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
61890b57cec5SDimitry Andric                                   DefinitionRequired, true);
61900b57cec5SDimitry Andric   }
61915ffd83dbSDimitry Andric 
61925ffd83dbSDimitry Andric   if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
61935ffd83dbSDimitry Andric     PendingInstantiations.swap(delayedPCHInstantiations);
61940b57cec5SDimitry Andric }
61950b57cec5SDimitry Andric 
61960b57cec5SDimitry Andric void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
61970b57cec5SDimitry Andric                        const MultiLevelTemplateArgumentList &TemplateArgs) {
61980b57cec5SDimitry Andric   for (auto DD : Pattern->ddiags()) {
61990b57cec5SDimitry Andric     switch (DD->getKind()) {
62000b57cec5SDimitry Andric     case DependentDiagnostic::Access:
62010b57cec5SDimitry Andric       HandleDependentAccessCheck(*DD, TemplateArgs);
62020b57cec5SDimitry Andric       break;
62030b57cec5SDimitry Andric     }
62040b57cec5SDimitry Andric   }
62050b57cec5SDimitry Andric }
6206