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