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