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