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