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