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