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