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