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