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