1//===------- SemaTemplateInstantiate.cpp - C++ Template 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.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
13#include "clang/AST/ASTConcept.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/DynamicRecursiveASTVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprConcepts.h"
23#include "clang/AST/PrettyDeclStackTrace.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeVisitor.h"
27#include "clang/Basic/LangOptions.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/EnterExpressionEvaluationContext.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Sema.h"
33#include "clang/Sema/SemaConcept.h"
34#include "clang/Sema/SemaInternal.h"
35#include "clang/Sema/Template.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "clang/Sema/TemplateInstCallback.h"
38#include "llvm/ADT/SmallVectorExtras.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/SaveAndRestore.h"
42#include "llvm/Support/TimeProfiler.h"
43#include <optional>
44
45using namespace clang;
46using namespace sema;
47
48//===----------------------------------------------------------------------===/
49// Template Instantiation Support
50//===----------------------------------------------------------------------===/
51
52namespace {
53namespace TemplateInstArgsHelpers {
54struct Response {
55 const Decl *NextDecl = nullptr;
56 bool IsDone = false;
57 bool ClearRelativeToPrimary = true;
58 static Response Done() {
59 Response R;
60 R.IsDone = true;
61 return R;
62 }
63 static Response ChangeDecl(const Decl *ND) {
64 Response R;
65 R.NextDecl = ND;
66 return R;
67 }
68 static Response ChangeDecl(const DeclContext *Ctx) {
69 Response R;
70 R.NextDecl = Decl::castFromDeclContext(Ctx);
71 return R;
72 }
73
74 static Response UseNextDecl(const Decl *CurDecl) {
75 return ChangeDecl(Ctx: CurDecl->getDeclContext());
76 }
77
78 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
79 Response R = Response::UseNextDecl(CurDecl);
80 R.ClearRelativeToPrimary = false;
81 return R;
82 }
83};
84
85// Retrieve the primary template for a lambda call operator. It's
86// unfortunate that we only have the mappings of call operators rather
87// than lambda classes.
88const FunctionDecl *
89getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
90 if (!isLambdaCallOperator(DC: LambdaCallOperator))
91 return LambdaCallOperator;
92 while (true) {
93 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
94 Val: LambdaCallOperator->getDescribedTemplate());
95 FTD && FTD->getInstantiatedFromMemberTemplate()) {
96 LambdaCallOperator =
97 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
98 } else if (LambdaCallOperator->getPrimaryTemplate()) {
99 // Cases where the lambda operator is instantiated in
100 // TemplateDeclInstantiator::VisitCXXMethodDecl.
101 LambdaCallOperator =
102 LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
103 } else if (auto *Prev = cast<CXXMethodDecl>(Val: LambdaCallOperator)
104 ->getInstantiatedFromMemberFunction())
105 LambdaCallOperator = Prev;
106 else
107 break;
108 }
109 return LambdaCallOperator;
110}
111
112struct EnclosingTypeAliasTemplateDetails {
113 TypeAliasTemplateDecl *Template = nullptr;
114 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
115 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
116
117 explicit operator bool() noexcept { return Template; }
118};
119
120// Find the enclosing type alias template Decl from CodeSynthesisContexts, as
121// well as its primary template and instantiating template arguments.
122EnclosingTypeAliasTemplateDetails
123getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
124 for (auto &CSC : llvm::reverse(C&: SemaRef.CodeSynthesisContexts)) {
125 if (CSC.Kind != Sema::CodeSynthesisContext::SynthesisKind::
126 TypeAliasTemplateInstantiation)
127 continue;
128 EnclosingTypeAliasTemplateDetails Result;
129 auto *TATD = cast<TypeAliasTemplateDecl>(Val: CSC.Entity),
130 *Next = TATD->getInstantiatedFromMemberTemplate();
131 Result = {
132 /*Template=*/TATD,
133 /*PrimaryTypeAliasDecl=*/TATD,
134 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
135 };
136 while (Next) {
137 Result.PrimaryTypeAliasDecl = Next;
138 Next = Next->getInstantiatedFromMemberTemplate();
139 }
140 return Result;
141 }
142 return {};
143}
144
145// Check if we are currently inside of a lambda expression that is
146// surrounded by a using alias declaration. e.g.
147// template <class> using type = decltype([](auto) { ^ }());
148// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
149// a DeclContext, nor does it have an associated specialization Decl from which
150// we could collect these template arguments.
151bool isLambdaEnclosedByTypeAliasDecl(
152 const FunctionDecl *LambdaCallOperator,
153 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
154 struct Visitor : DynamicRecursiveASTVisitor {
155 Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
156 bool VisitLambdaExpr(LambdaExpr *LE) override {
157 // Return true to bail out of the traversal, implying the Decl contains
158 // the lambda.
159 return getPrimaryTemplateOfGenericLambda(LambdaCallOperator: LE->getCallOperator()) !=
160 CallOperator;
161 }
162 const FunctionDecl *CallOperator;
163 };
164
165 QualType Underlying =
166 PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
167
168 return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
169 .TraverseType(T: Underlying);
170}
171
172// Add template arguments from a variable template instantiation.
173Response
174HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
175 MultiLevelTemplateArgumentList &Result,
176 bool SkipForSpecialization) {
177 // For a class-scope explicit specialization, there are no template arguments
178 // at this level, but there may be enclosing template arguments.
179 if (VarTemplSpec->isClassScopeExplicitSpecialization())
180 return Response::DontClearRelativeToPrimaryNextDecl(CurDecl: VarTemplSpec);
181
182 // We're done when we hit an explicit specialization.
183 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
184 !isa<VarTemplatePartialSpecializationDecl>(Val: VarTemplSpec))
185 return Response::Done();
186
187 // If this variable template specialization was instantiated from a
188 // specialized member that is a variable template, we're done.
189 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
190 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
191 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
192 if (VarTemplatePartialSpecializationDecl *Partial =
193 dyn_cast<VarTemplatePartialSpecializationDecl *>(Val&: Specialized)) {
194 if (!SkipForSpecialization)
195 Result.addOuterTemplateArguments(
196 AssociatedDecl: Partial, Args: VarTemplSpec->getTemplateInstantiationArgs().asArray(),
197 /*Final=*/false);
198 if (Partial->isMemberSpecialization())
199 return Response::Done();
200 } else {
201 VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Val&: Specialized);
202 if (!SkipForSpecialization)
203 Result.addOuterTemplateArguments(
204 AssociatedDecl: Tmpl, Args: VarTemplSpec->getTemplateInstantiationArgs().asArray(),
205 /*Final=*/false);
206 if (Tmpl->isMemberSpecialization())
207 return Response::Done();
208 }
209 return Response::DontClearRelativeToPrimaryNextDecl(CurDecl: VarTemplSpec);
210}
211
212// If we have a template template parameter with translation unit context,
213// then we're performing substitution into a default template argument of
214// this template template parameter before we've constructed the template
215// that will own this template template parameter. In this case, we
216// use empty template parameter lists for all of the outer templates
217// to avoid performing any substitutions.
218Response
219HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
220 MultiLevelTemplateArgumentList &Result) {
221 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
222 Result.addOuterTemplateArguments(std::nullopt);
223 return Response::Done();
224}
225
226Response HandlePartialClassTemplateSpec(
227 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
228 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
229 if (!SkipForSpecialization)
230 Result.addOuterRetainedLevels(Num: PartialClassTemplSpec->getTemplateDepth());
231 return Response::Done();
232}
233
234// Add template arguments from a class template instantiation.
235Response
236HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
237 MultiLevelTemplateArgumentList &Result,
238 bool SkipForSpecialization) {
239 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
240 // We're done when we hit an explicit specialization.
241 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
242 !isa<ClassTemplatePartialSpecializationDecl>(Val: ClassTemplSpec))
243 return Response::Done();
244
245 if (!SkipForSpecialization)
246 Result.addOuterTemplateArguments(
247 AssociatedDecl: const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
248 Args: ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
249 /*Final=*/false);
250
251 // If this class template specialization was instantiated from a
252 // specialized member that is a class template, we're done.
253 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
254 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
255 return Response::Done();
256
257 // If this was instantiated from a partial template specialization, we need
258 // to get the next level of declaration context from the partial
259 // specialization, as the ClassTemplateSpecializationDecl's
260 // DeclContext/LexicalDeclContext will be for the primary template.
261 if (auto *InstFromPartialTempl =
262 ClassTemplSpec->getSpecializedTemplateOrPartial()
263 .dyn_cast<ClassTemplatePartialSpecializationDecl *>())
264 return Response::ChangeDecl(
265 Ctx: InstFromPartialTempl->getLexicalDeclContext());
266 }
267 return Response::UseNextDecl(CurDecl: ClassTemplSpec);
268}
269
270Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
271 MultiLevelTemplateArgumentList &Result,
272 const FunctionDecl *Pattern, bool RelativeToPrimary,
273 bool ForConstraintInstantiation,
274 bool ForDefaultArgumentSubstitution) {
275 // Add template arguments from a function template specialization.
276 if (!RelativeToPrimary &&
277 Function->getTemplateSpecializationKindForInstantiation() ==
278 TSK_ExplicitSpecialization)
279 return Response::Done();
280
281 if (!RelativeToPrimary &&
282 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
283 // This is an implicit instantiation of an explicit specialization. We
284 // don't get any template arguments from this function but might get
285 // some from an enclosing template.
286 return Response::UseNextDecl(CurDecl: Function);
287 } else if (const TemplateArgumentList *TemplateArgs =
288 Function->getTemplateSpecializationArgs()) {
289 // Add the template arguments for this specialization.
290 Result.addOuterTemplateArguments(AssociatedDecl: const_cast<FunctionDecl *>(Function),
291 Args: TemplateArgs->asArray(),
292 /*Final=*/false);
293
294 if (RelativeToPrimary &&
295 (Function->getTemplateSpecializationKind() ==
296 TSK_ExplicitSpecialization ||
297 (Function->getFriendObjectKind() &&
298 !Function->getPrimaryTemplate()->getFriendObjectKind())))
299 return Response::UseNextDecl(CurDecl: Function);
300
301 // If this function was instantiated from a specialized member that is
302 // a function template, we're done.
303 assert(Function->getPrimaryTemplate() && "No function template?");
304 if (!ForDefaultArgumentSubstitution &&
305 Function->getPrimaryTemplate()->isMemberSpecialization())
306 return Response::Done();
307
308 // If this function is a generic lambda specialization, we are done.
309 if (!ForConstraintInstantiation &&
310 isGenericLambdaCallOperatorOrStaticInvokerSpecialization(DC: Function))
311 return Response::Done();
312
313 } else if (auto *Template = Function->getDescribedFunctionTemplate()) {
314 assert(
315 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
316 "Outer template not instantiated?");
317 if (ForConstraintInstantiation) {
318 for (auto &Inst : llvm::reverse(C&: SemaRef.CodeSynthesisContexts)) {
319 if (Inst.Kind == Sema::CodeSynthesisContext::ConstraintsCheck &&
320 Inst.Entity == Template) {
321 // After CWG2369, the outer templates are not instantiated when
322 // checking its associated constraints. So add them back through the
323 // synthesis context; this is useful for e.g. nested constraints
324 // involving lambdas.
325 Result.addOuterTemplateArguments(AssociatedDecl: Template, Args: Inst.template_arguments(),
326 /*Final=*/false);
327 break;
328 }
329 }
330 }
331 }
332 // If this is a friend or local declaration and it declares an entity at
333 // namespace scope, take arguments from its lexical parent
334 // instead of its semantic parent, unless of course the pattern we're
335 // instantiating actually comes from the file's context!
336 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
337 Function->getNonTransparentDeclContext()->isFileContext() &&
338 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
339 return Response::ChangeDecl(Ctx: Function->getLexicalDeclContext());
340 }
341
342 if (ForConstraintInstantiation && Function->getFriendObjectKind())
343 return Response::ChangeDecl(Ctx: Function->getLexicalDeclContext());
344 return Response::UseNextDecl(CurDecl: Function);
345}
346
347Response HandleFunctionTemplateDecl(Sema &SemaRef,
348 const FunctionTemplateDecl *FTD,
349 MultiLevelTemplateArgumentList &Result) {
350 if (!isa<ClassTemplateSpecializationDecl>(Val: FTD->getDeclContext())) {
351 Result.addOuterTemplateArguments(
352 AssociatedDecl: const_cast<FunctionTemplateDecl *>(FTD),
353 Args: const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(
354 Context: SemaRef.Context),
355 /*Final=*/false);
356
357 NestedNameSpecifier NNS = FTD->getTemplatedDecl()->getQualifier();
358
359 for (const Type *Ty = NNS.getKind() == NestedNameSpecifier::Kind::Type
360 ? NNS.getAsType()
361 : nullptr,
362 *NextTy = nullptr;
363 Ty && Ty->isInstantiationDependentType();
364 Ty = std::exchange(obj&: NextTy, new_val: nullptr)) {
365 if (NestedNameSpecifier P = Ty->getPrefix();
366 P.getKind() == NestedNameSpecifier::Kind::Type)
367 NextTy = P.getAsType();
368 const auto *TSTy = dyn_cast<TemplateSpecializationType>(Val: Ty);
369 if (!TSTy)
370 continue;
371
372 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
373 // Prefer template arguments from the injected-class-type if possible.
374 // For example,
375 // ```cpp
376 // template <class... Pack> struct S {
377 // template <class T> void foo();
378 // };
379 // template <class... Pack> template <class T>
380 // ^^^^^^^^^^^^^ InjectedTemplateArgs
381 // They're of kind TemplateArgument::Pack, not of
382 // TemplateArgument::Type.
383 // void S<Pack...>::foo() {}
384 // ^^^^^^^
385 // TSTy->template_arguments() (which are of PackExpansionType)
386 // ```
387 // This meets the contract in
388 // TreeTransform::TryExpandParameterPacks that the template arguments
389 // for unexpanded parameters should be of a Pack kind.
390 if (TSTy->isCurrentInstantiation()) {
391 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
392 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
393 Arguments = CTD->getInjectedTemplateArgs(Context: SemaRef.Context);
394 else if (auto *Specialization =
395 dyn_cast<ClassTemplateSpecializationDecl>(Val: RD))
396 Arguments = Specialization->getTemplateInstantiationArgs().asArray();
397 }
398 Result.addOuterTemplateArguments(
399 AssociatedDecl: TSTy->getTemplateName().getAsTemplateDecl(), Args: Arguments,
400 /*Final=*/false);
401 }
402 }
403
404 return Response::ChangeDecl(Ctx: FTD->getLexicalDeclContext());
405}
406
407Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
408 MultiLevelTemplateArgumentList &Result,
409 ASTContext &Context,
410 bool ForConstraintInstantiation) {
411 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
412 assert(
413 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
414 "Outer template not instantiated?");
415 if (ClassTemplate->isMemberSpecialization())
416 return Response::Done();
417 if (ForConstraintInstantiation)
418 Result.addOuterTemplateArguments(
419 AssociatedDecl: const_cast<CXXRecordDecl *>(Rec),
420 Args: ClassTemplate->getInjectedTemplateArgs(Context: SemaRef.Context),
421 /*Final=*/false);
422 }
423
424 if (const MemberSpecializationInfo *MSInfo =
425 Rec->getMemberSpecializationInfo())
426 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
427 return Response::Done();
428
429 bool IsFriend = Rec->getFriendObjectKind() ||
430 (Rec->getDescribedClassTemplate() &&
431 Rec->getDescribedClassTemplate()->getFriendObjectKind());
432 if (ForConstraintInstantiation && IsFriend &&
433 Rec->getNonTransparentDeclContext()->isFileContext()) {
434 return Response::ChangeDecl(Ctx: Rec->getLexicalDeclContext());
435 }
436
437 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
438 // TypeAliasTemplateDecl that this lambda is defined inside of.
439 if (Rec->isLambda()) {
440 if (const Decl *LCD = Rec->getLambdaContextDecl())
441 return Response::ChangeDecl(ND: LCD);
442 // Retrieve the template arguments for a using alias declaration.
443 // This is necessary for constraint checking, since we always keep
444 // constraints relative to the primary template.
445 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);
446 ForConstraintInstantiation && TypeAlias) {
447 if (isLambdaEnclosedByTypeAliasDecl(LambdaCallOperator: Rec->getLambdaCallOperator(),
448 PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) {
449 Result.addOuterTemplateArguments(AssociatedDecl: TypeAlias.Template,
450 Args: TypeAlias.AssociatedTemplateArguments,
451 /*Final=*/false);
452 // Visit the parent of the current type alias declaration rather than
453 // the lambda thereof.
454 // E.g., in the following example:
455 // struct S {
456 // template <class> using T = decltype([]<Concept> {} ());
457 // };
458 // void foo() {
459 // S::T var;
460 // }
461 // The instantiated lambda expression (which we're visiting at 'var')
462 // has a function DeclContext 'foo' rather than the Record DeclContext
463 // S. This seems to be an oversight to me that we may want to set a
464 // Sema Context from the CXXScopeSpec before substituting into T.
465 return Response::ChangeDecl(Ctx: TypeAlias.Template->getDeclContext());
466 }
467 }
468 }
469
470 return Response::UseNextDecl(CurDecl: Rec);
471}
472
473Response HandleImplicitConceptSpecializationDecl(
474 const ImplicitConceptSpecializationDecl *CSD,
475 MultiLevelTemplateArgumentList &Result) {
476 Result.addOuterTemplateArguments(
477 AssociatedDecl: const_cast<ImplicitConceptSpecializationDecl *>(CSD),
478 Args: CSD->getTemplateArguments(),
479 /*Final=*/false);
480 return Response::UseNextDecl(CurDecl: CSD);
481}
482
483Response HandleGenericDeclContext(const Decl *CurDecl) {
484 return Response::UseNextDecl(CurDecl);
485}
486} // namespace TemplateInstArgsHelpers
487} // namespace
488
489MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs(
490 const NamedDecl *ND, const DeclContext *DC, bool Final,
491 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
492 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
493 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
494 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
495 // Accumulate the set of template argument lists in this structure.
496 MultiLevelTemplateArgumentList Result;
497
498 using namespace TemplateInstArgsHelpers;
499 const Decl *CurDecl = ND;
500
501 if (Innermost) {
502 Result.addOuterTemplateArguments(AssociatedDecl: const_cast<NamedDecl *>(ND), Args: *Innermost,
503 Final);
504 // Populate placeholder template arguments for TemplateTemplateParmDecls.
505 // This is essential for the case e.g.
506 //
507 // template <class> concept Concept = false;
508 // template <template <Concept C> class T> void foo(T<int>)
509 //
510 // where parameter C has a depth of 1 but the substituting argument `int`
511 // has a depth of 0.
512 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: CurDecl))
513 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
514 CurDecl = DC ? Decl::castFromDeclContext(DC)
515 : Response::UseNextDecl(CurDecl).NextDecl;
516 } else if (!CurDecl)
517 CurDecl = Decl::castFromDeclContext(DC);
518
519 while (!CurDecl->isFileContextDecl()) {
520 Response R;
521 if (const auto *VarTemplSpec =
522 dyn_cast<VarTemplateSpecializationDecl>(Val: CurDecl)) {
523 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
524 } else if (const auto *PartialClassTemplSpec =
525 dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: CurDecl)) {
526 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
527 SkipForSpecialization);
528 } else if (const auto *ClassTemplSpec =
529 dyn_cast<ClassTemplateSpecializationDecl>(Val: CurDecl)) {
530 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
531 SkipForSpecialization);
532 } else if (const auto *Function = dyn_cast<FunctionDecl>(Val: CurDecl)) {
533 R = HandleFunction(SemaRef&: *this, Function, Result, Pattern, RelativeToPrimary,
534 ForConstraintInstantiation,
535 ForDefaultArgumentSubstitution);
536 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: CurDecl)) {
537 R = HandleRecordDecl(SemaRef&: *this, Rec, Result, Context,
538 ForConstraintInstantiation);
539 } else if (const auto *CSD =
540 dyn_cast<ImplicitConceptSpecializationDecl>(Val: CurDecl)) {
541 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
542 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: CurDecl)) {
543 R = HandleFunctionTemplateDecl(SemaRef&: *this, FTD, Result);
544 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(Val: CurDecl)) {
545 R = Response::ChangeDecl(Ctx: CTD->getLexicalDeclContext());
546 } else if (!isa<DeclContext>(Val: CurDecl)) {
547 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
548 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: CurDecl)) {
549 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
550 }
551 } else {
552 R = HandleGenericDeclContext(CurDecl);
553 }
554
555 if (R.IsDone)
556 return Result;
557 if (R.ClearRelativeToPrimary)
558 RelativeToPrimary = false;
559 assert(R.NextDecl);
560 CurDecl = R.NextDecl;
561 }
562 return Result;
563}
564
565bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
566 switch (Kind) {
567 case TemplateInstantiation:
568 case ExceptionSpecInstantiation:
569 case DefaultTemplateArgumentInstantiation:
570 case DefaultFunctionArgumentInstantiation:
571 case ExplicitTemplateArgumentSubstitution:
572 case DeducedTemplateArgumentSubstitution:
573 case PriorTemplateArgumentSubstitution:
574 case ConstraintsCheck:
575 case NestedRequirementConstraintsCheck:
576 return true;
577
578 case RequirementInstantiation:
579 case RequirementParameterInstantiation:
580 case DefaultTemplateArgumentChecking:
581 case DeclaringSpecialMember:
582 case DeclaringImplicitEqualityComparison:
583 case DefiningSynthesizedFunction:
584 case ExceptionSpecEvaluation:
585 case ConstraintSubstitution:
586 case ParameterMappingSubstitution:
587 case ConstraintNormalization:
588 case RewritingOperatorAsSpaceship:
589 case InitializingStructuredBinding:
590 case MarkingClassDllexported:
591 case BuildingBuiltinDumpStructCall:
592 case LambdaExpressionSubstitution:
593 case BuildingDeductionGuides:
594 case TypeAliasTemplateInstantiation:
595 case PartialOrderingTTP:
596 return false;
597
598 // This function should never be called when Kind's value is Memoization.
599 case Memoization:
600 break;
601 }
602
603 llvm_unreachable("Invalid SynthesisKind!");
604}
605
606Sema::InstantiatingTemplate::InstantiatingTemplate(
607 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
608 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
609 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs)
610 : SemaRef(SemaRef) {
611 // Don't allow further instantiation if a fatal error and an uncompilable
612 // error have occurred. Any diagnostics we might have raised will not be
613 // visible, and we do not need to construct a correct AST.
614 if (SemaRef.Diags.hasFatalErrorOccurred() &&
615 SemaRef.hasUncompilableErrorOccurred()) {
616 Invalid = true;
617 return;
618 }
619
620 CodeSynthesisContext Inst;
621 Inst.Kind = Kind;
622 Inst.PointOfInstantiation = PointOfInstantiation;
623 Inst.Entity = Entity;
624 Inst.Template = Template;
625 Inst.TemplateArgs = TemplateArgs.data();
626 Inst.NumTemplateArgs = TemplateArgs.size();
627 Inst.InstantiationRange = InstantiationRange;
628 Inst.InConstraintSubstitution =
629 Inst.Kind == CodeSynthesisContext::ConstraintSubstitution;
630 Inst.InParameterMappingSubstitution =
631 Inst.Kind == CodeSynthesisContext::ParameterMappingSubstitution;
632 if (!SemaRef.CodeSynthesisContexts.empty()) {
633 Inst.InConstraintSubstitution |=
634 SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution;
635 Inst.InParameterMappingSubstitution |=
636 SemaRef.CodeSynthesisContexts.back().InParameterMappingSubstitution;
637 }
638
639 Invalid = SemaRef.pushCodeSynthesisContext(Ctx: Inst);
640 if (!Invalid)
641 atTemplateBegin(Callbacks&: SemaRef.TemplateInstCallbacks, TheSema: SemaRef, Inst);
642}
643
644Sema::InstantiatingTemplate::InstantiatingTemplate(
645 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
646 SourceRange InstantiationRange)
647 : InstantiatingTemplate(SemaRef,
648 CodeSynthesisContext::TemplateInstantiation,
649 PointOfInstantiation, InstantiationRange, Entity) {}
650
651Sema::InstantiatingTemplate::InstantiatingTemplate(
652 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
653 ExceptionSpecification, SourceRange InstantiationRange)
654 : InstantiatingTemplate(
655 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
656 PointOfInstantiation, InstantiationRange, Entity) {}
657
658Sema::InstantiatingTemplate::InstantiatingTemplate(
659 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
660 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
661 SourceRange InstantiationRange)
662 : InstantiatingTemplate(
663 SemaRef,
664 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
665 PointOfInstantiation, InstantiationRange, getAsNamedDecl(P: Param),
666 Template, TemplateArgs) {}
667
668Sema::InstantiatingTemplate::InstantiatingTemplate(
669 Sema &SemaRef, SourceLocation PointOfInstantiation,
670 FunctionTemplateDecl *FunctionTemplate,
671 ArrayRef<TemplateArgument> TemplateArgs,
672 CodeSynthesisContext::SynthesisKind Kind, SourceRange InstantiationRange)
673 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
674 InstantiationRange, FunctionTemplate, nullptr,
675 TemplateArgs) {
676 assert(Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
677 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution ||
678 Kind == CodeSynthesisContext::BuildingDeductionGuides);
679}
680
681Sema::InstantiatingTemplate::InstantiatingTemplate(
682 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
683 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
684 : InstantiatingTemplate(
685 SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
686 PointOfInstantiation, InstantiationRange, Template, nullptr,
687 TemplateArgs) {}
688
689Sema::InstantiatingTemplate::InstantiatingTemplate(
690 Sema &SemaRef, SourceLocation PointOfInstantiation,
691 ClassTemplatePartialSpecializationDecl *PartialSpec,
692 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
693 : InstantiatingTemplate(
694 SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
695 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
696 TemplateArgs) {}
697
698Sema::InstantiatingTemplate::InstantiatingTemplate(
699 Sema &SemaRef, SourceLocation PointOfInstantiation,
700 VarTemplatePartialSpecializationDecl *PartialSpec,
701 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
702 : InstantiatingTemplate(
703 SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
704 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
705 TemplateArgs) {}
706
707Sema::InstantiatingTemplate::InstantiatingTemplate(
708 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
709 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
710 : InstantiatingTemplate(
711 SemaRef,
712 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
713 PointOfInstantiation, InstantiationRange, Param, nullptr,
714 TemplateArgs) {}
715
716Sema::InstantiatingTemplate::InstantiatingTemplate(
717 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
718 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
719 SourceRange InstantiationRange)
720 : InstantiatingTemplate(
721 SemaRef,
722 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
723 PointOfInstantiation, InstantiationRange, Param, Template,
724 TemplateArgs) {}
725
726Sema::InstantiatingTemplate::InstantiatingTemplate(
727 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
728 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
729 SourceRange InstantiationRange)
730 : InstantiatingTemplate(
731 SemaRef,
732 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
733 PointOfInstantiation, InstantiationRange, Param, Template,
734 TemplateArgs) {}
735
736Sema::InstantiatingTemplate::InstantiatingTemplate(
737 Sema &SemaRef, SourceLocation PointOfInstantiation,
738 TypeAliasTemplateDecl *Entity, ArrayRef<TemplateArgument> TemplateArgs,
739 SourceRange InstantiationRange)
740 : InstantiatingTemplate(
741 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
742 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
743 /*Template=*/nullptr, TemplateArgs) {}
744
745Sema::InstantiatingTemplate::InstantiatingTemplate(
746 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
747 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
748 SourceRange InstantiationRange)
749 : InstantiatingTemplate(
750 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
751 PointOfInstantiation, InstantiationRange, Param, Template,
752 TemplateArgs) {}
753
754Sema::InstantiatingTemplate::InstantiatingTemplate(
755 Sema &SemaRef, SourceLocation PointOfInstantiation,
756 concepts::Requirement *Req, SourceRange InstantiationRange)
757 : InstantiatingTemplate(
758 SemaRef, CodeSynthesisContext::RequirementInstantiation,
759 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
760 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
761
762Sema::InstantiatingTemplate::InstantiatingTemplate(
763 Sema &SemaRef, SourceLocation PointOfInstantiation,
764 concepts::NestedRequirement *Req, ConstraintsCheck,
765 SourceRange InstantiationRange)
766 : InstantiatingTemplate(
767 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
768 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
769 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
770
771Sema::InstantiatingTemplate::InstantiatingTemplate(
772 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
773 SourceRange InstantiationRange)
774 : InstantiatingTemplate(
775 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
776 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
777 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
778
779Sema::InstantiatingTemplate::InstantiatingTemplate(
780 Sema &SemaRef, SourceLocation PointOfInstantiation,
781 ConstraintsCheck, NamedDecl *Template,
782 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
783 : InstantiatingTemplate(
784 SemaRef, CodeSynthesisContext::ConstraintsCheck,
785 PointOfInstantiation, InstantiationRange, Template, nullptr,
786 TemplateArgs) {}
787
788Sema::InstantiatingTemplate::InstantiatingTemplate(
789 Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution,
790 NamedDecl *Template, SourceRange InstantiationRange)
791 : InstantiatingTemplate(
792 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
793 PointOfInstantiation, InstantiationRange, Template, nullptr, {}) {}
794
795Sema::InstantiatingTemplate::InstantiatingTemplate(
796 Sema &SemaRef, SourceLocation PointOfInstantiation,
797 ConstraintNormalization, NamedDecl *Template,
798 SourceRange InstantiationRange)
799 : InstantiatingTemplate(
800 SemaRef, CodeSynthesisContext::ConstraintNormalization,
801 PointOfInstantiation, InstantiationRange, Template) {}
802
803Sema::InstantiatingTemplate::InstantiatingTemplate(
804 Sema &SemaRef, SourceLocation PointOfInstantiation,
805 ParameterMappingSubstitution, NamedDecl *Template,
806 SourceRange InstantiationRange)
807 : InstantiatingTemplate(
808 SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
809 PointOfInstantiation, InstantiationRange, Template) {}
810
811Sema::InstantiatingTemplate::InstantiatingTemplate(
812 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
813 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
814 : InstantiatingTemplate(
815 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
816 PointOfInstantiation, InstantiationRange, Entity) {}
817
818Sema::InstantiatingTemplate::InstantiatingTemplate(
819 Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP,
820 TemplateDecl *PArg, SourceRange InstantiationRange)
821 : InstantiatingTemplate(SemaRef, CodeSynthesisContext::PartialOrderingTTP,
822 ArgLoc, InstantiationRange, PArg) {}
823
824bool Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
825 if (!Ctx.isInstantiationRecord()) {
826 ++NonInstantiationEntries;
827 } else {
828 assert(SemaRef.NonInstantiationEntries <=
829 SemaRef.CodeSynthesisContexts.size());
830 if ((SemaRef.CodeSynthesisContexts.size() -
831 SemaRef.NonInstantiationEntries) >
832 SemaRef.getLangOpts().InstantiationDepth) {
833 SemaRef.Diag(Loc: Ctx.PointOfInstantiation,
834 DiagID: diag::err_template_recursion_depth_exceeded)
835 << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange;
836 SemaRef.Diag(Loc: Ctx.PointOfInstantiation,
837 DiagID: diag::note_template_recursion_depth)
838 << SemaRef.getLangOpts().InstantiationDepth;
839 return true;
840 }
841 }
842
843 CodeSynthesisContexts.push_back(Elt: Ctx);
844
845 // Check to see if we're low on stack space. We can't do anything about this
846 // from here, but we can at least warn the user.
847 StackHandler.warnOnStackNearlyExhausted(Loc: Ctx.PointOfInstantiation);
848 return false;
849}
850
851void Sema::popCodeSynthesisContext() {
852 auto &Active = CodeSynthesisContexts.back();
853 if (!Active.isInstantiationRecord()) {
854 assert(NonInstantiationEntries > 0);
855 --NonInstantiationEntries;
856 }
857
858 // Name lookup no longer looks in this template's defining module.
859 assert(CodeSynthesisContexts.size() >=
860 CodeSynthesisContextLookupModules.size() &&
861 "forgot to remove a lookup module for a template instantiation");
862 if (CodeSynthesisContexts.size() ==
863 CodeSynthesisContextLookupModules.size()) {
864 if (Module *M = CodeSynthesisContextLookupModules.back())
865 LookupModulesCache.erase(V: M);
866 CodeSynthesisContextLookupModules.pop_back();
867 }
868
869 // If we've left the code synthesis context for the current context stack,
870 // stop remembering that we've emitted that stack.
871 if (CodeSynthesisContexts.size() ==
872 LastEmittedCodeSynthesisContextDepth)
873 LastEmittedCodeSynthesisContextDepth = 0;
874
875 CodeSynthesisContexts.pop_back();
876}
877
878void Sema::InstantiatingTemplate::Clear() {
879 if (!Invalid) {
880 atTemplateEnd(Callbacks&: SemaRef.TemplateInstCallbacks, TheSema: SemaRef,
881 Inst: SemaRef.CodeSynthesisContexts.back());
882
883 SemaRef.popCodeSynthesisContext();
884 Invalid = true;
885 }
886}
887
888static std::string convertCallArgsToString(Sema &S,
889 llvm::ArrayRef<const Expr *> Args) {
890 std::string Result;
891 llvm::raw_string_ostream OS(Result);
892 llvm::ListSeparator Comma;
893 for (const Expr *Arg : Args) {
894 OS << Comma;
895 Arg->IgnoreParens()->printPretty(OS, Helper: nullptr,
896 Policy: S.Context.getPrintingPolicy());
897 }
898 return Result;
899}
900
901void Sema::PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc) {
902 // Determine which template instantiations to skip, if any.
903 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
904 unsigned Limit = Diags.getTemplateBacktraceLimit();
905 if (Limit && Limit < CodeSynthesisContexts.size()) {
906 SkipStart = Limit / 2 + Limit % 2;
907 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
908 }
909
910 // FIXME: In all of these cases, we need to show the template arguments
911 unsigned InstantiationIdx = 0;
912 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
913 Active = CodeSynthesisContexts.rbegin(),
914 ActiveEnd = CodeSynthesisContexts.rend();
915 Active != ActiveEnd;
916 ++Active, ++InstantiationIdx) {
917 // Skip this instantiation?
918 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
919 if (InstantiationIdx == SkipStart) {
920 // Note that we're skipping instantiations.
921 DiagFunc(Active->PointOfInstantiation,
922 PDiag(DiagID: diag::note_instantiation_contexts_suppressed)
923 << unsigned(CodeSynthesisContexts.size() - Limit));
924 }
925 continue;
926 }
927
928 switch (Active->Kind) {
929 case CodeSynthesisContext::TemplateInstantiation: {
930 Decl *D = Active->Entity;
931 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
932 unsigned DiagID = diag::note_template_member_class_here;
933 if (isa<ClassTemplateSpecializationDecl>(Val: Record))
934 DiagID = diag::note_template_class_instantiation_here;
935 DiagFunc(Active->PointOfInstantiation,
936 PDiag(DiagID) << Record << Active->InstantiationRange);
937 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D)) {
938 unsigned DiagID;
939 if (Function->getPrimaryTemplate())
940 DiagID = diag::note_function_template_spec_here;
941 else
942 DiagID = diag::note_template_member_function_here;
943 DiagFunc(Active->PointOfInstantiation,
944 PDiag(DiagID) << Function << Active->InstantiationRange);
945 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
946 DiagFunc(Active->PointOfInstantiation,
947 PDiag(DiagID: VD->isStaticDataMember()
948 ? diag::note_template_static_data_member_def_here
949 : diag::note_template_variable_def_here)
950 << VD << Active->InstantiationRange);
951 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: D)) {
952 DiagFunc(Active->PointOfInstantiation,
953 PDiag(DiagID: diag::note_template_enum_def_here)
954 << ED << Active->InstantiationRange);
955 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: D)) {
956 DiagFunc(Active->PointOfInstantiation,
957 PDiag(DiagID: diag::note_template_nsdmi_here)
958 << FD << Active->InstantiationRange);
959 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
960 DiagFunc(Active->PointOfInstantiation,
961 PDiag(DiagID: diag::note_template_class_instantiation_here)
962 << CTD << Active->InstantiationRange);
963 }
964 break;
965 }
966
967 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
968 TemplateDecl *Template = cast<TemplateDecl>(Val: Active->Template);
969 SmallString<128> TemplateArgsStr;
970 llvm::raw_svector_ostream OS(TemplateArgsStr);
971 Template->printName(OS, Policy: getPrintingPolicy());
972 printTemplateArgumentList(OS, Args: Active->template_arguments(),
973 Policy: getPrintingPolicy());
974 DiagFunc(Active->PointOfInstantiation,
975 PDiag(DiagID: diag::note_default_arg_instantiation_here)
976 << OS.str() << Active->InstantiationRange);
977 break;
978 }
979
980 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
981 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Val: Active->Entity);
982 DiagFunc(Active->PointOfInstantiation,
983 PDiag(DiagID: diag::note_explicit_template_arg_substitution_here)
984 << FnTmpl
985 << getTemplateArgumentBindingsText(
986 Params: FnTmpl->getTemplateParameters(), Args: Active->TemplateArgs,
987 NumArgs: Active->NumTemplateArgs)
988 << Active->InstantiationRange);
989 break;
990 }
991
992 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
993 if (FunctionTemplateDecl *FnTmpl =
994 dyn_cast<FunctionTemplateDecl>(Val: Active->Entity)) {
995 DiagFunc(
996 Active->PointOfInstantiation,
997 PDiag(DiagID: diag::note_function_template_deduction_instantiation_here)
998 << FnTmpl
999 << getTemplateArgumentBindingsText(
1000 Params: FnTmpl->getTemplateParameters(), Args: Active->TemplateArgs,
1001 NumArgs: Active->NumTemplateArgs)
1002 << Active->InstantiationRange);
1003 } else {
1004 bool IsVar = isa<VarTemplateDecl>(Val: Active->Entity) ||
1005 isa<VarTemplateSpecializationDecl>(Val: Active->Entity);
1006 bool IsTemplate = false;
1007 TemplateParameterList *Params;
1008 if (auto *D = dyn_cast<TemplateDecl>(Val: Active->Entity)) {
1009 IsTemplate = true;
1010 Params = D->getTemplateParameters();
1011 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1012 Val: Active->Entity)) {
1013 Params = D->getTemplateParameters();
1014 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1015 Val: Active->Entity)) {
1016 Params = D->getTemplateParameters();
1017 } else {
1018 llvm_unreachable("unexpected template kind");
1019 }
1020
1021 DiagFunc(Active->PointOfInstantiation,
1022 PDiag(DiagID: diag::note_deduced_template_arg_substitution_here)
1023 << IsVar << IsTemplate << cast<NamedDecl>(Val: Active->Entity)
1024 << getTemplateArgumentBindingsText(Params,
1025 Args: Active->TemplateArgs,
1026 NumArgs: Active->NumTemplateArgs)
1027 << Active->InstantiationRange);
1028 }
1029 break;
1030 }
1031
1032 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
1033 ParmVarDecl *Param = cast<ParmVarDecl>(Val: Active->Entity);
1034 FunctionDecl *FD = cast<FunctionDecl>(Val: Param->getDeclContext());
1035
1036 SmallString<128> TemplateArgsStr;
1037 llvm::raw_svector_ostream OS(TemplateArgsStr);
1038 FD->printName(OS, Policy: getPrintingPolicy());
1039 printTemplateArgumentList(OS, Args: Active->template_arguments(),
1040 Policy: getPrintingPolicy());
1041 DiagFunc(Active->PointOfInstantiation,
1042 PDiag(DiagID: diag::note_default_function_arg_instantiation_here)
1043 << OS.str() << Active->InstantiationRange);
1044 break;
1045 }
1046
1047 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
1048 NamedDecl *Parm = cast<NamedDecl>(Val: Active->Entity);
1049 std::string Name;
1050 if (!Parm->getName().empty())
1051 Name = std::string(" '") + Parm->getName().str() + "'";
1052
1053 TemplateParameterList *TemplateParams = nullptr;
1054 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template))
1055 TemplateParams = Template->getTemplateParameters();
1056 else
1057 TemplateParams =
1058 cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template)
1059 ->getTemplateParameters();
1060 DiagFunc(Active->PointOfInstantiation,
1061 PDiag(DiagID: diag::note_prior_template_arg_substitution)
1062 << isa<TemplateTemplateParmDecl>(Val: Parm) << Name
1063 << getTemplateArgumentBindingsText(Params: TemplateParams,
1064 Args: Active->TemplateArgs,
1065 NumArgs: Active->NumTemplateArgs)
1066 << Active->InstantiationRange);
1067 break;
1068 }
1069
1070 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
1071 TemplateParameterList *TemplateParams = nullptr;
1072 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template))
1073 TemplateParams = Template->getTemplateParameters();
1074 else
1075 TemplateParams =
1076 cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template)
1077 ->getTemplateParameters();
1078
1079 DiagFunc(Active->PointOfInstantiation,
1080 PDiag(DiagID: diag::note_template_default_arg_checking)
1081 << getTemplateArgumentBindingsText(Params: TemplateParams,
1082 Args: Active->TemplateArgs,
1083 NumArgs: Active->NumTemplateArgs)
1084 << Active->InstantiationRange);
1085 break;
1086 }
1087
1088 case CodeSynthesisContext::ExceptionSpecEvaluation:
1089 DiagFunc(Active->PointOfInstantiation,
1090 PDiag(DiagID: diag::note_evaluating_exception_spec_here)
1091 << cast<FunctionDecl>(Val: Active->Entity));
1092 break;
1093
1094 case CodeSynthesisContext::ExceptionSpecInstantiation:
1095 DiagFunc(Active->PointOfInstantiation,
1096 PDiag(DiagID: diag::note_template_exception_spec_instantiation_here)
1097 << cast<FunctionDecl>(Val: Active->Entity)
1098 << Active->InstantiationRange);
1099 break;
1100
1101 case CodeSynthesisContext::RequirementInstantiation:
1102 DiagFunc(Active->PointOfInstantiation,
1103 PDiag(DiagID: diag::note_template_requirement_instantiation_here)
1104 << Active->InstantiationRange);
1105 break;
1106 case CodeSynthesisContext::RequirementParameterInstantiation:
1107 DiagFunc(Active->PointOfInstantiation,
1108 PDiag(DiagID: diag::note_template_requirement_params_instantiation_here)
1109 << Active->InstantiationRange);
1110 break;
1111
1112 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
1113 DiagFunc(Active->PointOfInstantiation,
1114 PDiag(DiagID: diag::note_nested_requirement_here)
1115 << Active->InstantiationRange);
1116 break;
1117
1118 case CodeSynthesisContext::DeclaringSpecialMember:
1119 DiagFunc(Active->PointOfInstantiation,
1120 PDiag(DiagID: diag::note_in_declaration_of_implicit_special_member)
1121 << cast<CXXRecordDecl>(Val: Active->Entity)
1122 << Active->SpecialMember);
1123 break;
1124
1125 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
1126 DiagFunc(
1127 Active->Entity->getLocation(),
1128 PDiag(DiagID: diag::note_in_declaration_of_implicit_equality_comparison));
1129 break;
1130
1131 case CodeSynthesisContext::DefiningSynthesizedFunction: {
1132 // FIXME: For synthesized functions that are not defaulted,
1133 // produce a note.
1134 auto *FD = dyn_cast<FunctionDecl>(Val: Active->Entity);
1135 // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind()
1136 // will ensure that DFK.isComparison() is false. This is important because
1137 // we will uncondtionally dereference FD in the else if.
1138 DefaultedFunctionKind DFK =
1139 FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
1140 if (DFK.isSpecialMember()) {
1141 auto *MD = cast<CXXMethodDecl>(Val: FD);
1142 DiagFunc(Active->PointOfInstantiation,
1143 PDiag(DiagID: diag::note_member_synthesized_at)
1144 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
1145 << Context.getCanonicalTagType(TD: MD->getParent()));
1146 } else if (DFK.isComparison()) {
1147 QualType RecordType = FD->getParamDecl(i: 0)
1148 ->getType()
1149 .getNonReferenceType()
1150 .getUnqualifiedType();
1151 DiagFunc(Active->PointOfInstantiation,
1152 PDiag(DiagID: diag::note_comparison_synthesized_at)
1153 << (int)DFK.asComparison() << RecordType);
1154 }
1155 break;
1156 }
1157
1158 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
1159 DiagFunc(Active->Entity->getLocation(),
1160 PDiag(DiagID: diag::note_rewriting_operator_as_spaceship));
1161 break;
1162
1163 case CodeSynthesisContext::InitializingStructuredBinding:
1164 DiagFunc(Active->PointOfInstantiation,
1165 PDiag(DiagID: diag::note_in_binding_decl_init)
1166 << cast<BindingDecl>(Val: Active->Entity));
1167 break;
1168
1169 case CodeSynthesisContext::MarkingClassDllexported:
1170 DiagFunc(Active->PointOfInstantiation,
1171 PDiag(DiagID: diag::note_due_to_dllexported_class)
1172 << cast<CXXRecordDecl>(Val: Active->Entity)
1173 << !getLangOpts().CPlusPlus11);
1174 break;
1175
1176 case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
1177 DiagFunc(Active->PointOfInstantiation,
1178 PDiag(DiagID: diag::note_building_builtin_dump_struct_call)
1179 << convertCallArgsToString(
1180 S&: *this, Args: llvm::ArrayRef(Active->CallArgs,
1181 Active->NumCallArgs)));
1182 break;
1183
1184 case CodeSynthesisContext::Memoization:
1185 break;
1186
1187 case CodeSynthesisContext::LambdaExpressionSubstitution:
1188 DiagFunc(Active->PointOfInstantiation,
1189 PDiag(DiagID: diag::note_lambda_substitution_here));
1190 break;
1191 case CodeSynthesisContext::ConstraintsCheck: {
1192 unsigned DiagID = 0;
1193 if (!Active->Entity) {
1194 DiagFunc(Active->PointOfInstantiation,
1195 PDiag(DiagID: diag::note_nested_requirement_here)
1196 << Active->InstantiationRange);
1197 break;
1198 }
1199 if (isa<ConceptDecl>(Val: Active->Entity))
1200 DiagID = diag::note_concept_specialization_here;
1201 else if (isa<TemplateDecl>(Val: Active->Entity))
1202 DiagID = diag::note_checking_constraints_for_template_id_here;
1203 else if (isa<VarTemplatePartialSpecializationDecl>(Val: Active->Entity))
1204 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1205 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Active->Entity))
1206 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1207 else {
1208 assert(isa<FunctionDecl>(Active->Entity));
1209 DiagID = diag::note_checking_constraints_for_function_here;
1210 }
1211 SmallString<128> TemplateArgsStr;
1212 llvm::raw_svector_ostream OS(TemplateArgsStr);
1213 cast<NamedDecl>(Val: Active->Entity)->printName(OS, Policy: getPrintingPolicy());
1214 if (!isa<FunctionDecl>(Val: Active->Entity)) {
1215 printTemplateArgumentList(OS, Args: Active->template_arguments(),
1216 Policy: getPrintingPolicy());
1217 }
1218 DiagFunc(Active->PointOfInstantiation,
1219 PDiag(DiagID) << OS.str() << Active->InstantiationRange);
1220 break;
1221 }
1222 case CodeSynthesisContext::ConstraintSubstitution:
1223 DiagFunc(Active->PointOfInstantiation,
1224 PDiag(DiagID: diag::note_constraint_substitution_here)
1225 << Active->InstantiationRange);
1226 break;
1227 case CodeSynthesisContext::ConstraintNormalization:
1228 DiagFunc(Active->PointOfInstantiation,
1229 PDiag(DiagID: diag::note_constraint_normalization_here)
1230 << cast<NamedDecl>(Val: Active->Entity)
1231 << Active->InstantiationRange);
1232 break;
1233 case CodeSynthesisContext::ParameterMappingSubstitution:
1234 DiagFunc(Active->PointOfInstantiation,
1235 PDiag(DiagID: diag::note_parameter_mapping_substitution_here)
1236 << Active->InstantiationRange);
1237 break;
1238 case CodeSynthesisContext::BuildingDeductionGuides:
1239 DiagFunc(Active->PointOfInstantiation,
1240 PDiag(DiagID: diag::note_building_deduction_guide_here));
1241 break;
1242 case CodeSynthesisContext::TypeAliasTemplateInstantiation:
1243 // Workaround for a workaround: don't produce a note if we are merely
1244 // instantiating some other template which contains this alias template.
1245 // This would be redundant either with the error itself, or some other
1246 // context note attached to it.
1247 if (Active->NumTemplateArgs == 0)
1248 break;
1249 DiagFunc(Active->PointOfInstantiation,
1250 PDiag(DiagID: diag::note_template_type_alias_instantiation_here)
1251 << cast<TypeAliasTemplateDecl>(Val: Active->Entity)
1252 << Active->InstantiationRange);
1253 break;
1254 case CodeSynthesisContext::PartialOrderingTTP:
1255 DiagFunc(Active->PointOfInstantiation,
1256 PDiag(DiagID: diag::note_template_arg_template_params_mismatch));
1257 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1258 ParamLoc.isValid())
1259 DiagFunc(ParamLoc, PDiag(DiagID: diag::note_template_prev_declaration)
1260 << /*isTemplateTemplateParam=*/true
1261 << Active->InstantiationRange);
1262 break;
1263 }
1264 }
1265}
1266
1267//===----------------------------------------------------------------------===/
1268// Template Instantiation for Types
1269//===----------------------------------------------------------------------===/
1270namespace {
1271
1272 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1273 const MultiLevelTemplateArgumentList &TemplateArgs;
1274 SourceLocation Loc;
1275 DeclarationName Entity;
1276 // Whether to evaluate the C++20 constraints or simply substitute into them.
1277 bool EvaluateConstraints = true;
1278 // Whether Substitution was Incomplete, that is, we tried to substitute in
1279 // any user provided template arguments which were null.
1280 bool IsIncomplete = false;
1281 // Whether an incomplete substituion should be treated as an error.
1282 bool BailOutOnIncomplete;
1283
1284 // CWG2770: Function parameters should be instantiated when they are
1285 // needed by a satisfaction check of an atomic constraint or
1286 // (recursively) by another function parameter.
1287 bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm);
1288
1289 public:
1290 typedef TreeTransform<TemplateInstantiator> inherited;
1291
1292 TemplateInstantiator(Sema &SemaRef,
1293 const MultiLevelTemplateArgumentList &TemplateArgs,
1294 SourceLocation Loc, DeclarationName Entity,
1295 bool BailOutOnIncomplete = false)
1296 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1297 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1298
1299 void setEvaluateConstraints(bool B) {
1300 EvaluateConstraints = B;
1301 }
1302 bool getEvaluateConstraints() {
1303 return EvaluateConstraints;
1304 }
1305
1306 inline static struct ForParameterMappingSubstitution_t {
1307 } ForParameterMappingSubstitution;
1308
1309 TemplateInstantiator(ForParameterMappingSubstitution_t, Sema &SemaRef,
1310 SourceLocation Loc,
1311 const MultiLevelTemplateArgumentList &TemplateArgs)
1312 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1313 BailOutOnIncomplete(false) {}
1314
1315 /// Determine whether the given type \p T has already been
1316 /// transformed.
1317 ///
1318 /// For the purposes of template instantiation, a type has already been
1319 /// transformed if it is NULL or if it is not dependent.
1320 bool AlreadyTransformed(QualType T);
1321
1322 /// Returns the location of the entity being instantiated, if known.
1323 SourceLocation getBaseLocation() { return Loc; }
1324
1325 /// Returns the name of the entity being instantiated, if any.
1326 DeclarationName getBaseEntity() { return Entity; }
1327
1328 /// Returns whether any substitution so far was incomplete.
1329 bool getIsIncomplete() const { return IsIncomplete; }
1330
1331 /// Sets the "base" location and entity when that
1332 /// information is known based on another transformation.
1333 void setBase(SourceLocation Loc, DeclarationName Entity) {
1334 this->Loc = Loc;
1335 this->Entity = Entity;
1336 }
1337
1338 unsigned TransformTemplateDepth(unsigned Depth) {
1339 return TemplateArgs.getNewDepth(OldDepth: Depth);
1340 }
1341
1342 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1343 SourceRange PatternRange,
1344 ArrayRef<UnexpandedParameterPack> Unexpanded,
1345 bool FailOnPackProducingTemplates,
1346 bool &ShouldExpand, bool &RetainExpansion,
1347 UnsignedOrNone &NumExpansions) {
1348 if (SemaRef.CurrentInstantiationScope &&
1349 (SemaRef.inConstraintSubstitution() ||
1350 SemaRef.inParameterMappingSubstitution())) {
1351 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1352 NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>();
1353 if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(Val: VD);
1354 PVD && maybeInstantiateFunctionParameterToScope(OldParm: PVD))
1355 return true;
1356 }
1357 }
1358
1359 return getSema().CheckParameterPacksForExpansion(
1360 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1361 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1362 NumExpansions);
1363 }
1364
1365 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1366 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Pack);
1367 }
1368
1369 TemplateArgument ForgetPartiallySubstitutedPack() {
1370 TemplateArgument Result;
1371 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1372 ->getPartiallySubstitutedPack()) {
1373 MultiLevelTemplateArgumentList &TemplateArgs =
1374 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1375 unsigned Depth, Index;
1376 std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack);
1377 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1378 Result = TemplateArgs(Depth, Index);
1379 TemplateArgs.setArgument(Depth, Index, Arg: TemplateArgument());
1380 } else {
1381 IsIncomplete = true;
1382 if (BailOutOnIncomplete)
1383 return TemplateArgument();
1384 }
1385 }
1386
1387 return Result;
1388 }
1389
1390 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1391 if (Arg.isNull())
1392 return;
1393
1394 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1395 ->getPartiallySubstitutedPack()) {
1396 MultiLevelTemplateArgumentList &TemplateArgs =
1397 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1398 unsigned Depth, Index;
1399 std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack);
1400 TemplateArgs.setArgument(Depth, Index, Arg);
1401 }
1402 }
1403
1404 MultiLevelTemplateArgumentList ForgetSubstitution() {
1405 MultiLevelTemplateArgumentList New;
1406 New.addOuterRetainedLevels(Num: this->TemplateArgs.getNumLevels());
1407
1408 MultiLevelTemplateArgumentList Old =
1409 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1410 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1411 std::move(New);
1412 return Old;
1413 }
1414
1415 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1416 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = Old;
1417 }
1418
1419 TemplateArgument
1420 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1421 if (TA.getKind() != TemplateArgument::Pack)
1422 return TA;
1423 if (SemaRef.ArgPackSubstIndex)
1424 return SemaRef.getPackSubstitutedTemplateArgument(Arg: TA);
1425 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1426 "unexpected pack arguments in template rewrite");
1427 TemplateArgument Arg = *TA.pack_begin();
1428 if (Arg.isPackExpansion())
1429 Arg = Arg.getPackExpansionPattern();
1430 return Arg;
1431 }
1432
1433 /// Transform the given declaration by instantiating a reference to
1434 /// this declaration.
1435 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1436
1437 void transformAttrs(Decl *Old, Decl *New) {
1438 SemaRef.InstantiateAttrs(TemplateArgs, Pattern: Old, Inst: New);
1439 }
1440
1441 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1442 if (Old->isParameterPack() &&
1443 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1444 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Old);
1445 for (auto *New : NewDecls)
1446 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
1447 D: Old, Inst: cast<VarDecl>(Val: New));
1448 return;
1449 }
1450
1451 assert(NewDecls.size() == 1 &&
1452 "should only have multiple expansions for a pack");
1453 Decl *New = NewDecls.front();
1454
1455 // If we've instantiated the call operator of a lambda or the call
1456 // operator template of a generic lambda, update the "instantiation of"
1457 // information.
1458 auto *NewMD = dyn_cast<CXXMethodDecl>(Val: New);
1459 if (NewMD && isLambdaCallOperator(MD: NewMD)) {
1460 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: Old);
1461 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1462 NewTD->setInstantiatedFromMemberTemplate(
1463 OldMD->getDescribedFunctionTemplate());
1464 else
1465 NewMD->setInstantiationOfMemberFunction(FD: OldMD,
1466 TSK: TSK_ImplicitInstantiation);
1467 }
1468
1469 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: Old, Inst: New);
1470
1471 // We recreated a local declaration, but not by instantiating it. There
1472 // may be pending dependent diagnostics to produce.
1473 if (auto *DC = dyn_cast<DeclContext>(Val: Old);
1474 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1475 SemaRef.PerformDependentDiagnostics(Pattern: DC, TemplateArgs);
1476 }
1477
1478 /// Transform the definition of the given declaration by
1479 /// instantiating it.
1480 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1481
1482 /// Transform the first qualifier within a scope by instantiating the
1483 /// declaration.
1484 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1485
1486 bool TransformExceptionSpec(SourceLocation Loc,
1487 FunctionProtoType::ExceptionSpecInfo &ESI,
1488 SmallVectorImpl<QualType> &Exceptions,
1489 bool &Changed);
1490
1491 /// Rebuild the exception declaration and register the declaration
1492 /// as an instantiated local.
1493 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1494 TypeSourceInfo *Declarator,
1495 SourceLocation StartLoc,
1496 SourceLocation NameLoc,
1497 IdentifierInfo *Name);
1498
1499 /// Rebuild the Objective-C exception declaration and register the
1500 /// declaration as an instantiated local.
1501 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1502 TypeSourceInfo *TSInfo, QualType T);
1503
1504 TemplateName
1505 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1506 SourceLocation TemplateKWLoc, TemplateName Name,
1507 SourceLocation NameLoc,
1508 QualType ObjectType = QualType(),
1509 NamedDecl *FirstQualifierInScope = nullptr,
1510 bool AllowInjectedClassName = false);
1511
1512 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1513 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1514 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1515 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1516 const Stmt *InstS,
1517 const NoInlineAttr *A);
1518 const AlwaysInlineAttr *
1519 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1520 const AlwaysInlineAttr *A);
1521 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1522 const OpenACCRoutineDeclAttr *
1523 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1524 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1525 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1526 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1527
1528 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1529 NonTypeTemplateParmDecl *D);
1530
1531 /// Rebuild a DeclRefExpr for a VarDecl reference.
1532 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1533
1534 /// Transform a reference to a function or init-capture parameter pack.
1535 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1536
1537 /// Transform a FunctionParmPackExpr which was built when we couldn't
1538 /// expand a function parameter pack reference which refers to an expanded
1539 /// pack.
1540 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1541
1542 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1543 FunctionProtoTypeLoc TL) {
1544 // Call the base version; it will forward to our overridden version below.
1545 return inherited::TransformFunctionProtoType(TLB, TL);
1546 }
1547
1548 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1549 auto Type = inherited::TransformTagType(TLB, TL);
1550 if (!Type.isNull())
1551 return Type;
1552 // Special case for transforming a deduction guide, we return a
1553 // transformed TemplateSpecializationType.
1554 // FIXME: Why is this hack necessary?
1555 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(Val: TL.getTypePtr());
1556 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1557 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
1558 Type = inherited::TransformType(
1559 T: ICNT->getDecl()->getCanonicalTemplateSpecializationType(
1560 Ctx: SemaRef.Context));
1561 TLB.pushTrivial(Context&: SemaRef.Context, T: Type, Loc: TL.getNameLoc());
1562 }
1563 return Type;
1564 }
1565 // Override the default version to handle a rewrite-template-arg-pack case
1566 // for building a deduction guide.
1567 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1568 TemplateArgumentLoc &Output,
1569 bool Uneval = false) {
1570 const TemplateArgument &Arg = Input.getArgument();
1571 std::vector<TemplateArgument> TArgs;
1572 switch (Arg.getKind()) {
1573 case TemplateArgument::Pack:
1574 assert(SemaRef.CodeSynthesisContexts.empty() ||
1575 SemaRef.CodeSynthesisContexts.back().Kind ==
1576 Sema::CodeSynthesisContext::BuildingDeductionGuides);
1577 // Literally rewrite the template argument pack, instead of unpacking
1578 // it.
1579 for (auto &pack : Arg.getPackAsArray()) {
1580 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1581 Arg: pack, NTTPType: QualType(), Loc: SourceLocation{});
1582 TemplateArgumentLoc Output;
1583 if (TransformTemplateArgument(Input, Output, Uneval))
1584 return true; // fails
1585 TArgs.push_back(x: Output.getArgument());
1586 }
1587 Output = SemaRef.getTrivialTemplateArgumentLoc(
1588 Arg: TemplateArgument(llvm::ArrayRef(TArgs).copy(A&: SemaRef.Context)),
1589 NTTPType: QualType(), Loc: SourceLocation{});
1590 return false;
1591 default:
1592 break;
1593 }
1594 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1595 }
1596
1597 using TreeTransform::TransformTemplateSpecializationType;
1598 QualType
1599 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1600 TemplateSpecializationTypeLoc TL) {
1601 auto *T = TL.getTypePtr();
1602 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1603 !isPackProducingBuiltinTemplateName(N: T->getTemplateName()))
1604 return TreeTransform::TransformTemplateSpecializationType(TLB, TL);
1605 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1606 // need to substitute into.
1607
1608 // `TransformType` code below will handle picking the element from a pack
1609 // with the index `ArgPackSubstIndex`.
1610 // FIXME: add ability to represent sugarred type for N-th element of a
1611 // builtin pack and produce the sugar here.
1612 QualType R = TransformType(T: T->desugar());
1613 TLB.pushTrivial(Context&: getSema().getASTContext(), T: R, Loc: TL.getBeginLoc());
1614 return R;
1615 }
1616
1617 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1618 ArrayRef<TemplateArgument> PackArgs) {
1619 // Don't do this when rewriting template parameters for CTAD:
1620 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1621 // expanded size, but this never applies since Subst* nodes are not
1622 // created in rewrite scenarios.
1623 //
1624 // 2) The heuristic substitutes into the pattern with pack expansion
1625 // suppressed, which does not meet the requirements for argument
1626 // rewriting when template arguments include a non-pack matching against
1627 // a pack, particularly when rewriting an alias CTAD.
1628 if (TemplateArgs.isRewrite())
1629 return std::nullopt;
1630
1631 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1632 }
1633
1634 template<typename Fn>
1635 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1636 FunctionProtoTypeLoc TL,
1637 CXXRecordDecl *ThisContext,
1638 Qualifiers ThisTypeQuals,
1639 Fn TransformExceptionSpec);
1640
1641 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1642 int indexAdjustment,
1643 UnsignedOrNone NumExpansions,
1644 bool ExpectParameterPack);
1645
1646 using inherited::TransformTemplateTypeParmType;
1647 /// Transforms a template type parameter type by performing
1648 /// substitution of the corresponding template type argument.
1649 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1650 TemplateTypeParmTypeLoc TL,
1651 bool SuppressObjCLifetime);
1652
1653 QualType BuildSubstTemplateTypeParmType(
1654 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1655 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1656 TemplateArgument Arg, SourceLocation NameLoc);
1657
1658 /// Transforms an already-substituted template type parameter pack
1659 /// into either itself (if we aren't substituting into its pack expansion)
1660 /// or the appropriate substituted argument.
1661 using inherited::TransformSubstTemplateTypeParmPackType;
1662 QualType
1663 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1664 SubstTemplateTypeParmPackTypeLoc TL,
1665 bool SuppressObjCLifetime);
1666 QualType
1667 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1668 SubstBuiltinTemplatePackTypeLoc TL);
1669
1670 CXXRecordDecl::LambdaDependencyKind
1671 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1672 if (auto TypeAlias =
1673 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1674 SemaRef&: getSema());
1675 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1676 LambdaCallOperator: LSI->CallOperator, PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) {
1677 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1678 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1679 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1680 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1681 if (TA.isDependent())
1682 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1683 }
1684 return inherited::ComputeLambdaDependency(LSI);
1685 }
1686
1687 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1688 // Do not rebuild lambdas to avoid creating a new type.
1689 // Lambdas have already been processed inside their eval contexts.
1690 if (SemaRef.RebuildingImmediateInvocation)
1691 return E;
1692 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1693 /*InstantiatingLambdaOrBlock=*/true);
1694 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1695
1696 return inherited::TransformLambdaExpr(E);
1697 }
1698
1699 ExprResult TransformBlockExpr(BlockExpr *E) {
1700 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1701 /*InstantiatingLambdaOrBlock=*/true);
1702 return inherited::TransformBlockExpr(E);
1703 }
1704
1705 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1706 LambdaScopeInfo *LSI) {
1707 CXXMethodDecl *MD = LSI->CallOperator;
1708 for (ParmVarDecl *PVD : MD->parameters()) {
1709 assert(PVD && "null in a parameter list");
1710 if (!PVD->hasDefaultArg())
1711 continue;
1712 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1713 // FIXME: Obtain the source location for the '=' token.
1714 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1715 if (SemaRef.SubstDefaultArgument(Loc: EqualLoc, Param: PVD, TemplateArgs)) {
1716 // If substitution fails, the default argument is set to a
1717 // RecoveryExpr that wraps the uninstantiated default argument so
1718 // that downstream diagnostics are omitted.
1719 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1720 Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(), SubExprs: {UninstExpr},
1721 T: UninstExpr->getType());
1722 if (ErrorResult.isUsable())
1723 PVD->setDefaultArg(ErrorResult.get());
1724 }
1725 }
1726 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1727 }
1728
1729 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1730 // Currently, we instantiate the body when instantiating the lambda
1731 // expression. However, `EvaluateConstraints` is disabled during the
1732 // instantiation of the lambda expression, causing the instantiation
1733 // failure of the return type requirement in the body. If p0588r1 is fully
1734 // implemented, the body will be lazily instantiated, and this problem
1735 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1736 // `true` to temporarily fix this issue.
1737 // FIXME: This temporary fix can be removed after fully implementing
1738 // p0588r1.
1739 llvm::SaveAndRestore _(EvaluateConstraints, true);
1740 return inherited::TransformLambdaBody(E, S: Body);
1741 }
1742
1743 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1744 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1745 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1746 if (TransReq.isInvalid())
1747 return TransReq;
1748 assert(TransReq.get() != E &&
1749 "Do not change value of isSatisfied for the existing expression. "
1750 "Create a new expression instead.");
1751 if (E->getBody()->isDependentContext()) {
1752 Sema::SFINAETrap Trap(SemaRef);
1753 // We recreate the RequiresExpr body, but not by instantiating it.
1754 // Produce pending diagnostics for dependent access check.
1755 SemaRef.PerformDependentDiagnostics(Pattern: E->getBody(), TemplateArgs);
1756 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1757 if (Trap.hasErrorOccurred())
1758 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1759 }
1760 return TransReq;
1761 }
1762
1763 bool TransformRequiresExprRequirements(
1764 ArrayRef<concepts::Requirement *> Reqs,
1765 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1766 bool SatisfactionDetermined = false;
1767 for (concepts::Requirement *Req : Reqs) {
1768 concepts::Requirement *TransReq = nullptr;
1769 if (!SatisfactionDetermined) {
1770 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Val: Req))
1771 TransReq = TransformTypeRequirement(Req: TypeReq);
1772 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Val: Req))
1773 TransReq = TransformExprRequirement(Req: ExprReq);
1774 else
1775 TransReq = TransformNestedRequirement(
1776 Req: cast<concepts::NestedRequirement>(Val: Req));
1777 if (!TransReq)
1778 return true;
1779 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1780 // [expr.prim.req]p6
1781 // [...] The substitution and semantic constraint checking
1782 // proceeds in lexical order and stops when a condition that
1783 // determines the result of the requires-expression is
1784 // encountered. [..]
1785 SatisfactionDetermined = true;
1786 } else
1787 TransReq = Req;
1788 Transformed.push_back(Elt: TransReq);
1789 }
1790 return false;
1791 }
1792
1793 TemplateParameterList *TransformTemplateParameterList(
1794 TemplateParameterList *OrigTPL) {
1795 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1796
1797 DeclContext *Owner = OrigTPL->getParam(Idx: 0)->getDeclContext();
1798 TemplateDeclInstantiator DeclInstantiator(getSema(),
1799 /* DeclContext *Owner */ Owner, TemplateArgs);
1800 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1801 return DeclInstantiator.SubstTemplateParams(List: OrigTPL);
1802 }
1803
1804 concepts::TypeRequirement *
1805 TransformTypeRequirement(concepts::TypeRequirement *Req);
1806 concepts::ExprRequirement *
1807 TransformExprRequirement(concepts::ExprRequirement *Req);
1808 concepts::NestedRequirement *
1809 TransformNestedRequirement(concepts::NestedRequirement *Req);
1810 ExprResult TransformRequiresTypeParams(
1811 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1812 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1813 SmallVectorImpl<QualType> &PTypes,
1814 SmallVectorImpl<ParmVarDecl *> &TransParams,
1815 Sema::ExtParameterInfoBuilder &PInfos);
1816 };
1817}
1818
1819bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1820 if (T.isNull())
1821 return true;
1822
1823 if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||
1824 T->containsUnexpandedParameterPack())
1825 return false;
1826
1827 getSema().MarkDeclarationsReferencedInType(Loc, T);
1828 return true;
1829}
1830
1831Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1832 if (!D)
1833 return nullptr;
1834
1835 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: D)) {
1836 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1837 // If the corresponding template argument is NULL or non-existent, it's
1838 // because we are performing instantiation from explicitly-specified
1839 // template arguments in a function template, but there were some
1840 // arguments left unspecified.
1841 if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(),
1842 Index: TTP->getPosition())) {
1843 IsIncomplete = true;
1844 return BailOutOnIncomplete ? nullptr : D;
1845 }
1846
1847 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1848
1849 if (TTP->isParameterPack()) {
1850 assert(Arg.getKind() == TemplateArgument::Pack &&
1851 "Missing argument pack");
1852 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1853 }
1854
1855 TemplateName Template = Arg.getAsTemplate();
1856 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1857 "Wrong kind of template template argument");
1858 return Template.getAsTemplateDecl();
1859 }
1860
1861 // Fall through to find the instantiated declaration for this template
1862 // template parameter.
1863 }
1864
1865 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: D);
1866 PVD && SemaRef.CurrentInstantiationScope &&
1867 (SemaRef.inConstraintSubstitution() ||
1868 SemaRef.inParameterMappingSubstitution()) &&
1869 maybeInstantiateFunctionParameterToScope(OldParm: PVD))
1870 return nullptr;
1871
1872 return SemaRef.FindInstantiatedDecl(Loc, D: cast<NamedDecl>(Val: D), TemplateArgs);
1873}
1874
1875bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope(
1876 ParmVarDecl *OldParm) {
1877 if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(D: OldParm))
1878 return false;
1879
1880 if (!OldParm->isParameterPack())
1881 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
1882 /*NumExpansions=*/std::nullopt,
1883 /*ExpectParameterPack=*/false);
1884
1885 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1886
1887 // Find the parameter packs that could be expanded.
1888 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
1889 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
1890 TypeLoc Pattern = ExpansionTL.getPatternLoc();
1891 SemaRef.collectUnexpandedParameterPacks(TL: Pattern, Unexpanded);
1892 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
1893
1894 bool ShouldExpand = false;
1895 bool RetainExpansion = false;
1896 UnsignedOrNone OrigNumExpansions =
1897 ExpansionTL.getTypePtr()->getNumExpansions();
1898 UnsignedOrNone NumExpansions = OrigNumExpansions;
1899 if (TryExpandParameterPacks(EllipsisLoc: ExpansionTL.getEllipsisLoc(),
1900 PatternRange: Pattern.getSourceRange(), Unexpanded,
1901 /*FailOnPackProducingTemplates=*/true,
1902 ShouldExpand, RetainExpansion, NumExpansions))
1903 return true;
1904
1905 assert(ShouldExpand && !RetainExpansion &&
1906 "Shouldn't preserve pack expansion when evaluating constraints");
1907 ExpandingFunctionParameterPack(Pack: OldParm);
1908 for (unsigned I = 0; I != *NumExpansions; ++I) {
1909 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
1910 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
1911 /*NumExpansions=*/OrigNumExpansions,
1912 /*ExpectParameterPack=*/false))
1913 return true;
1914 }
1915 return false;
1916}
1917
1918Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1919 Decl *Inst = getSema().SubstDecl(D, Owner: getSema().CurContext, TemplateArgs);
1920 if (!Inst)
1921 return nullptr;
1922
1923 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1924 return Inst;
1925}
1926
1927bool TemplateInstantiator::TransformExceptionSpec(
1928 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
1929 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1930 if (ESI.Type == EST_Uninstantiated) {
1931 ESI.instantiate();
1932 Changed = true;
1933 }
1934 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1935}
1936
1937NamedDecl *
1938TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1939 SourceLocation Loc) {
1940 // If the first part of the nested-name-specifier was a template type
1941 // parameter, instantiate that type parameter down to a tag type.
1942 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(Val: D)) {
1943 const TemplateTypeParmType *TTP
1944 = cast<TemplateTypeParmType>(Val: getSema().Context.getTypeDeclType(Decl: TTPD));
1945
1946 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1947 // FIXME: This needs testing w/ member access expressions.
1948 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1949
1950 if (TTP->isParameterPack()) {
1951 assert(Arg.getKind() == TemplateArgument::Pack &&
1952 "Missing argument pack");
1953
1954 if (!getSema().ArgPackSubstIndex)
1955 return nullptr;
1956
1957 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1958 }
1959
1960 QualType T = Arg.getAsType();
1961 if (T.isNull())
1962 return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D));
1963
1964 if (const TagType *Tag = T->getAs<TagType>())
1965 return Tag->getDecl();
1966
1967 // The resulting type is not a tag; complain.
1968 getSema().Diag(Loc, DiagID: diag::err_nested_name_spec_non_tag) << T;
1969 return nullptr;
1970 }
1971 }
1972
1973 return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D));
1974}
1975
1976VarDecl *
1977TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1978 TypeSourceInfo *Declarator,
1979 SourceLocation StartLoc,
1980 SourceLocation NameLoc,
1981 IdentifierInfo *Name) {
1982 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1983 StartLoc, IdLoc: NameLoc, Id: Name);
1984 if (Var)
1985 getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var);
1986 return Var;
1987}
1988
1989VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1990 TypeSourceInfo *TSInfo,
1991 QualType T) {
1992 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TInfo: TSInfo, T);
1993 if (Var)
1994 getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var);
1995 return Var;
1996}
1997
1998TemplateName TemplateInstantiator::TransformTemplateName(
1999 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2000 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2001 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2002 if (Name.getKind() == TemplateName::Template) {
2003 assert(!QualifierLoc && "Unexpected qualifier");
2004 if (auto *TTP =
2005 dyn_cast<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl());
2006 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2007 // If the corresponding template argument is NULL or non-existent, it's
2008 // because we are performing instantiation from explicitly-specified
2009 // template arguments in a function template, but there were some
2010 // arguments left unspecified.
2011 if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(),
2012 Index: TTP->getPosition())) {
2013 IsIncomplete = true;
2014 return BailOutOnIncomplete ? TemplateName() : Name;
2015 }
2016
2017 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2018
2019 if (TemplateArgs.isRewrite()) {
2020 // We're rewriting the template parameter as a reference to another
2021 // template parameter.
2022 Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg);
2023 assert(Arg.getKind() == TemplateArgument::Template &&
2024 "unexpected nontype template argument kind in template rewrite");
2025 return Arg.getAsTemplate();
2026 }
2027
2028 auto [AssociatedDecl, Final] =
2029 TemplateArgs.getAssociatedDecl(Depth: TTP->getDepth());
2030 UnsignedOrNone PackIndex = std::nullopt;
2031 if (TTP->isParameterPack()) {
2032 assert(Arg.getKind() == TemplateArgument::Pack &&
2033 "Missing argument pack");
2034
2035 if (!getSema().ArgPackSubstIndex) {
2036 // We have the template argument pack to substitute, but we're not
2037 // actually expanding the enclosing pack expansion yet. So, just
2038 // keep the entire argument pack.
2039 return getSema().Context.getSubstTemplateTemplateParmPack(
2040 ArgPack: Arg, AssociatedDecl, Index: TTP->getIndex(), Final);
2041 }
2042
2043 PackIndex = SemaRef.getPackIndex(Pack: Arg);
2044 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2045 }
2046
2047 TemplateName Template = Arg.getAsTemplate();
2048 assert(!Template.isNull() && "Null template template argument");
2049 return getSema().Context.getSubstTemplateTemplateParm(
2050 replacement: Template, AssociatedDecl, Index: TTP->getIndex(), PackIndex, Final);
2051 }
2052 }
2053
2054 if (SubstTemplateTemplateParmPackStorage *SubstPack
2055 = Name.getAsSubstTemplateTemplateParmPack()) {
2056 if (!getSema().ArgPackSubstIndex)
2057 return Name;
2058
2059 TemplateArgument Pack = SubstPack->getArgumentPack();
2060 TemplateName Template =
2061 SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack).getAsTemplate();
2062 return getSema().Context.getSubstTemplateTemplateParm(
2063 replacement: Template, AssociatedDecl: SubstPack->getAssociatedDecl(), Index: SubstPack->getIndex(),
2064 PackIndex: SemaRef.getPackIndex(Pack), Final: SubstPack->getFinal());
2065 }
2066
2067 return inherited::TransformTemplateName(
2068 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2069 FirstQualifierInScope, AllowInjectedClassName);
2070}
2071
2072ExprResult
2073TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2074 if (!E->isTypeDependent())
2075 return E;
2076
2077 return getSema().BuildPredefinedExpr(Loc: E->getLocation(), IK: E->getIdentKind());
2078}
2079
2080ExprResult
2081TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2082 NonTypeTemplateParmDecl *NTTP) {
2083 // If the corresponding template argument is NULL or non-existent, it's
2084 // because we are performing instantiation from explicitly-specified
2085 // template arguments in a function template, but there were some
2086 // arguments left unspecified.
2087 if (!TemplateArgs.hasTemplateArgument(Depth: NTTP->getDepth(),
2088 Index: NTTP->getPosition())) {
2089 IsIncomplete = true;
2090 return BailOutOnIncomplete ? ExprError() : E;
2091 }
2092
2093 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2094
2095 if (TemplateArgs.isRewrite()) {
2096 // We're rewriting the template parameter as a reference to another
2097 // template parameter.
2098 Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg);
2099 assert(Arg.getKind() == TemplateArgument::Expression &&
2100 "unexpected nontype template argument kind in template rewrite");
2101 // FIXME: This can lead to the same subexpression appearing multiple times
2102 // in a complete expression.
2103 return Arg.getAsExpr();
2104 }
2105
2106 auto [AssociatedDecl, Final] =
2107 TemplateArgs.getAssociatedDecl(Depth: NTTP->getDepth());
2108 UnsignedOrNone PackIndex = std::nullopt;
2109 if (NTTP->isParameterPack()) {
2110 assert(Arg.getKind() == TemplateArgument::Pack &&
2111 "Missing argument pack");
2112
2113 if (!getSema().ArgPackSubstIndex) {
2114 // We have an argument pack, but we can't select a particular argument
2115 // out of it yet. Therefore, we'll build an expression to hold on to that
2116 // argument pack.
2117 QualType TargetType = SemaRef.SubstType(T: NTTP->getType(), TemplateArgs,
2118 Loc: E->getLocation(),
2119 Entity: NTTP->getDeclName());
2120 if (TargetType.isNull())
2121 return ExprError();
2122
2123 QualType ExprType = TargetType.getNonLValueExprType(Context: SemaRef.Context);
2124 if (TargetType->isRecordType())
2125 ExprType.addConst();
2126 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2127 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2128 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2129 }
2130 PackIndex = SemaRef.getPackIndex(Pack: Arg);
2131 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2132 }
2133 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2134 AssociatedDecl, NTTP, loc: E->getLocation(), Replacement: Arg, PackIndex, Final);
2135}
2136
2137const AnnotateAttr *
2138TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2139 SmallVector<Expr *> Args;
2140 for (Expr *Arg : AA->args()) {
2141 ExprResult Res = getDerived().TransformExpr(E: Arg);
2142 if (Res.isUsable())
2143 Args.push_back(Elt: Res.get());
2144 }
2145 return AnnotateAttr::CreateImplicit(Ctx&: getSema().Context, Annotation: AA->getAnnotation(),
2146 Args: Args.data(), ArgsSize: Args.size(), Range: AA->getRange());
2147}
2148
2149const CXXAssumeAttr *
2150TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2151 ExprResult Res = getDerived().TransformExpr(E: AA->getAssumption());
2152 if (!Res.isUsable())
2153 return AA;
2154
2155 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2156 Res = getSema().BuildCXXAssumeExpr(Assumption: Res.get(), AttrName: AA->getAttrName(),
2157 Range: AA->getRange());
2158 if (!Res.isUsable())
2159 return AA;
2160 }
2161
2162 return CXXAssumeAttr::CreateImplicit(Ctx&: getSema().Context, Assumption: Res.get(),
2163 Range: AA->getRange());
2164}
2165
2166const LoopHintAttr *
2167TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2168 Expr *TransformedExpr = getDerived().TransformExpr(E: LH->getValue()).get();
2169
2170 if (TransformedExpr == LH->getValue())
2171 return LH;
2172
2173 // Generate error if there is a problem with the value.
2174 if (getSema().CheckLoopHintExpr(E: TransformedExpr, Loc: LH->getLocation(),
2175 /*AllowZero=*/LH->getSemanticSpelling() ==
2176 LoopHintAttr::Pragma_unroll))
2177 return LH;
2178
2179 LoopHintAttr::OptionType Option = LH->getOption();
2180 LoopHintAttr::LoopHintState State = LH->getState();
2181
2182 // Since C++ does not have partial instantiation, we would expect a
2183 // transformed loop hint expression to not be value dependent. However, at
2184 // the time of writing, the use of a generic lambda inside a template
2185 // triggers a double instantiation, so we must protect against this event.
2186 // This provision may become unneeded in the future.
2187 if (Option == LoopHintAttr::UnrollCount &&
2188 !TransformedExpr->isValueDependent()) {
2189 llvm::APSInt ValueAPS =
2190 TransformedExpr->EvaluateKnownConstInt(Ctx: getSema().getASTContext());
2191 // The values of 0 and 1 block any unrolling of the loop (also see
2192 // handleLoopHintAttr in SemaStmtAttr).
2193 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2194 Option = LoopHintAttr::Unroll;
2195 State = LoopHintAttr::Disable;
2196 }
2197 }
2198
2199 // Create new LoopHintValueAttr with integral expression in place of the
2200 // non-type template parameter.
2201 return LoopHintAttr::CreateImplicit(Ctx&: getSema().Context, Option, State,
2202 Value: TransformedExpr, CommonInfo: *LH);
2203}
2204const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2205 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2206 if (!A || getSema().CheckNoInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A))
2207 return nullptr;
2208
2209 return A;
2210}
2211const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2212 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2213 if (!A || getSema().CheckAlwaysInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A))
2214 return nullptr;
2215
2216 return A;
2217}
2218
2219const CodeAlignAttr *
2220TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2221 Expr *TransformedExpr = getDerived().TransformExpr(E: CA->getAlignment()).get();
2222 return getSema().BuildCodeAlignAttr(CI: *CA, E: TransformedExpr);
2223}
2224const OpenACCRoutineDeclAttr *
2225TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2226 const OpenACCRoutineDeclAttr *A) {
2227 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2228 "applies to a Function Decl (and a few places for VarDecl)");
2229}
2230
2231ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2232 SourceLocation Loc) {
2233 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2234 return getSema().BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo, D: PD);
2235}
2236
2237ExprResult
2238TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2239 if (getSema().ArgPackSubstIndex) {
2240 // We can expand this parameter pack now.
2241 ValueDecl *D = E->getExpansion(I: *getSema().ArgPackSubstIndex);
2242 ValueDecl *VD = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D));
2243 if (!VD)
2244 return ExprError();
2245 return RebuildVarDeclRefExpr(PD: VD, Loc: E->getExprLoc());
2246 }
2247
2248 QualType T = TransformType(T: E->getType());
2249 if (T.isNull())
2250 return ExprError();
2251
2252 // Transform each of the parameter expansions into the corresponding
2253 // parameters in the instantiation of the function decl.
2254 SmallVector<ValueDecl *, 8> Vars;
2255 Vars.reserve(N: E->getNumExpansions());
2256 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2257 I != End; ++I) {
2258 ValueDecl *D = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D: *I));
2259 if (!D)
2260 return ExprError();
2261 Vars.push_back(Elt: D);
2262 }
2263
2264 auto *PackExpr =
2265 FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: E->getParameterPack(),
2266 NameLoc: E->getParameterPackLocation(), Params: Vars);
2267 getSema().MarkFunctionParmPackReferenced(E: PackExpr);
2268 return PackExpr;
2269}
2270
2271ExprResult
2272TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2273 ValueDecl *PD) {
2274 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2275 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2276 = getSema().CurrentInstantiationScope->findInstantiationOf(D: PD);
2277 assert(Found && "no instantiation for parameter pack");
2278
2279 Decl *TransformedDecl;
2280 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: *Found)) {
2281 // If this is a reference to a function parameter pack which we can
2282 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2283 if (!getSema().ArgPackSubstIndex) {
2284 QualType T = TransformType(T: E->getType());
2285 if (T.isNull())
2286 return ExprError();
2287 auto *PackExpr = FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: PD,
2288 NameLoc: E->getExprLoc(), Params: *Pack);
2289 getSema().MarkFunctionParmPackReferenced(E: PackExpr);
2290 return PackExpr;
2291 }
2292
2293 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2294 } else {
2295 TransformedDecl = cast<Decl *>(Val&: *Found);
2296 }
2297
2298 // We have either an unexpanded pack or a specific expansion.
2299 return RebuildVarDeclRefExpr(PD: cast<ValueDecl>(Val: TransformedDecl),
2300 Loc: E->getExprLoc());
2301}
2302
2303ExprResult
2304TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2305 NamedDecl *D = E->getDecl();
2306
2307 // Handle references to non-type template parameters and non-type template
2308 // parameter packs.
2309 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: D)) {
2310 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2311 return TransformTemplateParmRefExpr(E, NTTP);
2312
2313 // We have a non-type template parameter that isn't fully substituted;
2314 // FindInstantiatedDecl will find it in the local instantiation scope.
2315 }
2316
2317 // Handle references to function parameter packs.
2318 if (VarDecl *PD = dyn_cast<VarDecl>(Val: D))
2319 if (PD->isParameterPack())
2320 return TransformFunctionParmPackRefExpr(E, PD);
2321
2322 return inherited::TransformDeclRefExpr(E);
2323}
2324
2325ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2326 CXXDefaultArgExpr *E) {
2327 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2328 getDescribedFunctionTemplate() &&
2329 "Default arg expressions are never formed in dependent cases.");
2330 return SemaRef.BuildCXXDefaultArgExpr(
2331 CallLoc: E->getUsedLocation(), FD: cast<FunctionDecl>(Val: E->getParam()->getDeclContext()),
2332 Param: E->getParam());
2333}
2334
2335template<typename Fn>
2336QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2337 FunctionProtoTypeLoc TL,
2338 CXXRecordDecl *ThisContext,
2339 Qualifiers ThisTypeQuals,
2340 Fn TransformExceptionSpec) {
2341 // If this is a lambda or block, the transformation MUST be done in the
2342 // CurrentInstantiationScope since it introduces a mapping of
2343 // the original to the newly created transformed parameters.
2344 //
2345 // In that case, TemplateInstantiator::TransformLambdaExpr will
2346 // have already pushed a scope for this prototype, so don't create
2347 // a second one.
2348 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2349 std::optional<LocalInstantiationScope> Scope;
2350 if (!Current || !Current->isLambdaOrBlock())
2351 Scope.emplace(args&: SemaRef, /*CombineWithOuterScope=*/args: true);
2352
2353 return inherited::TransformFunctionProtoType(
2354 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2355}
2356
2357ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2358 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2359 bool ExpectParameterPack) {
2360 auto NewParm = SemaRef.SubstParmVarDecl(
2361 D: OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2362 ExpectParameterPack, EvaluateConstraints);
2363 if (NewParm && SemaRef.getLangOpts().OpenCL)
2364 SemaRef.deduceOpenCLAddressSpace(decl: NewParm);
2365 return NewParm;
2366}
2367
2368QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2369 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2370 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2371 TemplateArgument Arg, SourceLocation NameLoc) {
2372 QualType Replacement = Arg.getAsType();
2373
2374 // If the template parameter had ObjC lifetime qualifiers,
2375 // then any such qualifiers on the replacement type are ignored.
2376 if (SuppressObjCLifetime) {
2377 Qualifiers RQs;
2378 RQs = Replacement.getQualifiers();
2379 RQs.removeObjCLifetime();
2380 Replacement =
2381 SemaRef.Context.getQualifiedType(T: Replacement.getUnqualifiedType(), Qs: RQs);
2382 }
2383
2384 // TODO: only do this uniquing once, at the start of instantiation.
2385 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2386 Replacement, AssociatedDecl, Index, PackIndex, Final);
2387 SubstTemplateTypeParmTypeLoc NewTL =
2388 TLB.push<SubstTemplateTypeParmTypeLoc>(T: Result);
2389 NewTL.setNameLoc(NameLoc);
2390 return Result;
2391}
2392
2393QualType
2394TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2395 TemplateTypeParmTypeLoc TL,
2396 bool SuppressObjCLifetime) {
2397 const TemplateTypeParmType *T = TL.getTypePtr();
2398 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2399 // Replace the template type parameter with its corresponding
2400 // template argument.
2401
2402 // If the corresponding template argument is NULL or doesn't exist, it's
2403 // because we are performing instantiation from explicitly-specified
2404 // template arguments in a function template class, but there were some
2405 // arguments left unspecified.
2406 if (!TemplateArgs.hasTemplateArgument(Depth: T->getDepth(), Index: T->getIndex())) {
2407 IsIncomplete = true;
2408 if (BailOutOnIncomplete)
2409 return QualType();
2410
2411 TemplateTypeParmTypeLoc NewTL
2412 = TLB.push<TemplateTypeParmTypeLoc>(T: TL.getType());
2413 NewTL.setNameLoc(TL.getNameLoc());
2414 return TL.getType();
2415 }
2416
2417 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2418
2419 if (TemplateArgs.isRewrite()) {
2420 // We're rewriting the template parameter as a reference to another
2421 // template parameter.
2422 Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg);
2423 assert(Arg.getKind() == TemplateArgument::Type &&
2424 "unexpected nontype template argument kind in template rewrite");
2425 QualType NewT = Arg.getAsType();
2426 TLB.pushTrivial(Context&: SemaRef.Context, T: NewT, Loc: TL.getNameLoc());
2427 return NewT;
2428 }
2429
2430 auto [AssociatedDecl, Final] =
2431 TemplateArgs.getAssociatedDecl(Depth: T->getDepth());
2432 UnsignedOrNone PackIndex = std::nullopt;
2433 if (T->isParameterPack() ||
2434 // In concept parameter mapping for fold expressions, packs that aren't
2435 // expanded in place are treated as having non-pack dependency, so that
2436 // a PackExpansionType won't prevent expanding the packs outside the
2437 // TreeTransform. However, we still need to unpack the arguments during
2438 // any template argument substitution, so we check the associated
2439 // declaration instead.
2440 (T->getDecl() && T->getDecl()->isTemplateParameterPack())) {
2441 assert(Arg.getKind() == TemplateArgument::Pack &&
2442 "Missing argument pack");
2443
2444 if (!getSema().ArgPackSubstIndex) {
2445 // We have the template argument pack, but we're not expanding the
2446 // enclosing pack expansion yet. Just save the template argument
2447 // pack for later substitution.
2448 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2449 AssociatedDecl, Index: T->getIndex(), Final, ArgPack: Arg);
2450 SubstTemplateTypeParmPackTypeLoc NewTL
2451 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result);
2452 NewTL.setNameLoc(TL.getNameLoc());
2453 return Result;
2454 }
2455
2456 // PackIndex starts from last element.
2457 PackIndex = SemaRef.getPackIndex(Pack: Arg);
2458 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2459 }
2460
2461 assert(Arg.getKind() == TemplateArgument::Type &&
2462 "Template argument kind mismatch");
2463
2464 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2465 AssociatedDecl, Index: T->getIndex(),
2466 PackIndex, Arg, NameLoc: TL.getNameLoc());
2467 }
2468
2469 // The template type parameter comes from an inner template (e.g.,
2470 // the template parameter list of a member template inside the
2471 // template we are instantiating). Create a new template type
2472 // parameter with the template "level" reduced by one.
2473 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2474 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2475 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2476 Val: TransformDecl(Loc: TL.getNameLoc(), D: OldTTPDecl));
2477 QualType Result = getSema().Context.getTemplateTypeParmType(
2478 Depth: T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), Index: T->getIndex(),
2479 ParameterPack: T->isParameterPack(), ParmDecl: NewTTPDecl);
2480 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(T: Result);
2481 NewTL.setNameLoc(TL.getNameLoc());
2482 return Result;
2483}
2484
2485QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2486 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2487 bool SuppressObjCLifetime) {
2488 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2489
2490 Decl *NewReplaced = TransformDecl(Loc: TL.getNameLoc(), D: T->getAssociatedDecl());
2491
2492 if (!getSema().ArgPackSubstIndex) {
2493 // We aren't expanding the parameter pack, so just return ourselves.
2494 QualType Result = TL.getType();
2495 if (NewReplaced != T->getAssociatedDecl())
2496 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2497 AssociatedDecl: NewReplaced, Index: T->getIndex(), Final: T->getFinal(), ArgPack: T->getArgumentPack());
2498 SubstTemplateTypeParmPackTypeLoc NewTL =
2499 TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result);
2500 NewTL.setNameLoc(TL.getNameLoc());
2501 return Result;
2502 }
2503
2504 TemplateArgument Pack = T->getArgumentPack();
2505 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack);
2506 return BuildSubstTemplateTypeParmType(
2507 TLB, SuppressObjCLifetime, Final: T->getFinal(), AssociatedDecl: NewReplaced, Index: T->getIndex(),
2508 PackIndex: SemaRef.getPackIndex(Pack), Arg, NameLoc: TL.getNameLoc());
2509}
2510
2511QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2512 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2513 if (!getSema().ArgPackSubstIndex)
2514 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2515 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2516 Arg: TL.getTypePtr()->getArgumentPack());
2517 TLB.pushTrivial(Context&: SemaRef.getASTContext(), T: Result.getAsType(),
2518 Loc: TL.getBeginLoc());
2519 return Result.getAsType();
2520}
2521
2522static concepts::Requirement::SubstitutionDiagnostic *
2523createSubstDiag(Sema &S, TemplateDeductionInfo &Info,
2524 Sema::EntityPrinter Printer) {
2525 SmallString<128> Message;
2526 SourceLocation ErrorLoc;
2527 if (Info.hasSFINAEDiagnostic()) {
2528 PartialDiagnosticAt PDA(SourceLocation(),
2529 PartialDiagnostic::NullDiagnostic{});
2530 Info.takeSFINAEDiagnostic(PD&: PDA);
2531 PDA.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: Message);
2532 ErrorLoc = PDA.first;
2533 } else {
2534 ErrorLoc = Info.getLocation();
2535 }
2536 SmallString<128> Entity;
2537 llvm::raw_svector_ostream OS(Entity);
2538 Printer(OS);
2539 const ASTContext &C = S.Context;
2540 return new (C) concepts::Requirement::SubstitutionDiagnostic{
2541 .SubstitutedEntity: C.backupStr(S: Entity), .DiagLoc: ErrorLoc, .DiagMessage: C.backupStr(S: Message)};
2542}
2543
2544concepts::Requirement::SubstitutionDiagnostic *
2545Sema::createSubstDiagAt(SourceLocation Location, EntityPrinter Printer) {
2546 SmallString<128> Entity;
2547 llvm::raw_svector_ostream OS(Entity);
2548 Printer(OS);
2549 const ASTContext &C = Context;
2550 return new (C) concepts::Requirement::SubstitutionDiagnostic{
2551 /*SubstitutedEntity=*/C.backupStr(S: Entity),
2552 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2553}
2554
2555ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2556 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2557 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
2558 SmallVectorImpl<QualType> &PTypes,
2559 SmallVectorImpl<ParmVarDecl *> &TransParams,
2560 Sema::ExtParameterInfoBuilder &PInfos) {
2561
2562 TemplateDeductionInfo Info(KWLoc);
2563 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE,
2564 SourceRange{KWLoc, RBraceLoc});
2565 Sema::SFINAETrap Trap(SemaRef, Info);
2566
2567 unsigned ErrorIdx;
2568 if (getDerived().TransformFunctionTypeParams(
2569 Loc: KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, OutParamTypes&: PTypes,
2570 PVars: &TransParams, PInfos, LastParamTransformed: &ErrorIdx) ||
2571 Trap.hasErrorOccurred()) {
2572 SmallVector<concepts::Requirement *, 4> TransReqs;
2573 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2574 // Add a 'failed' Requirement to contain the error that caused the failure
2575 // here.
2576 TransReqs.push_back(Elt: RebuildTypeRequirement(SubstDiag: createSubstDiag(
2577 S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2578 return getDerived().RebuildRequiresExpr(RequiresKWLoc: KWLoc, Body, LParenLoc: RE->getLParenLoc(),
2579 LocalParameters: TransParams, RParenLoc: RE->getRParenLoc(),
2580 Requirements: TransReqs, ClosingBraceLoc: RBraceLoc);
2581 }
2582
2583 return ExprResult{};
2584}
2585
2586concepts::TypeRequirement *
2587TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2588 if (!Req->isDependent() && !AlwaysRebuild())
2589 return Req;
2590 if (Req->isSubstitutionFailure()) {
2591 if (AlwaysRebuild())
2592 return RebuildTypeRequirement(
2593 SubstDiag: Req->getSubstitutionDiagnostic());
2594 return Req;
2595 }
2596
2597 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2598 Sema::SFINAETrap Trap(SemaRef, Info);
2599 Sema::InstantiatingTemplate TypeInst(
2600 SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req,
2601 Req->getType()->getTypeLoc().getSourceRange());
2602 if (TypeInst.isInvalid())
2603 return nullptr;
2604 TypeSourceInfo *TransType = TransformType(TSI: Req->getType());
2605 if (!TransType || Trap.hasErrorOccurred())
2606 return RebuildTypeRequirement(SubstDiag: createSubstDiag(S&: SemaRef, Info,
2607 Printer: [&] (llvm::raw_ostream& OS) {
2608 Req->getType()->getType().print(OS, Policy: SemaRef.getPrintingPolicy());
2609 }));
2610 return RebuildTypeRequirement(T: TransType);
2611}
2612
2613concepts::ExprRequirement *
2614TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2615 if (!Req->isDependent() && !AlwaysRebuild())
2616 return Req;
2617
2618 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2619 TransExpr;
2620 if (Req->isExprSubstitutionFailure())
2621 TransExpr = Req->getExprSubstitutionDiagnostic();
2622 else {
2623 Expr *E = Req->getExpr();
2624 TemplateDeductionInfo Info(E->getBeginLoc());
2625 Sema::SFINAETrap Trap(SemaRef, Info);
2626 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req,
2627 E->getSourceRange());
2628 if (ExprInst.isInvalid())
2629 return nullptr;
2630 ExprResult TransExprRes = TransformExpr(E);
2631 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2632 TransExprRes.get()->hasPlaceholderType())
2633 TransExprRes = SemaRef.CheckPlaceholderExpr(E: TransExprRes.get());
2634 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2635 TransExpr = createSubstDiag(S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) {
2636 E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy());
2637 });
2638 else
2639 TransExpr = TransExprRes.get();
2640 }
2641
2642 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2643 const auto &RetReq = Req->getReturnTypeRequirement();
2644 if (RetReq.isEmpty())
2645 TransRetReq.emplace();
2646 else if (RetReq.isSubstitutionFailure())
2647 TransRetReq.emplace(args: RetReq.getSubstitutionDiagnostic());
2648 else if (RetReq.isTypeConstraint()) {
2649 TemplateParameterList *OrigTPL =
2650 RetReq.getTypeConstraintTemplateParameterList();
2651 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2652 Sema::SFINAETrap Trap(SemaRef, Info);
2653 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req,
2654 OrigTPL->getSourceRange());
2655 if (TPLInst.isInvalid())
2656 return nullptr;
2657 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2658 if (!TPL || Trap.hasErrorOccurred())
2659 TransRetReq.emplace(args: createSubstDiag(S&: SemaRef, Info,
2660 Printer: [&] (llvm::raw_ostream& OS) {
2661 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2662 ->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy());
2663 }));
2664 else {
2665 TPLInst.Clear();
2666 TransRetReq.emplace(args&: TPL);
2667 }
2668 }
2669 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2670 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2671 return RebuildExprRequirement(E, IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(),
2672 Ret: std::move(*TransRetReq));
2673 return RebuildExprRequirement(
2674 SubstDiag: cast<concepts::Requirement::SubstitutionDiagnostic *>(Val&: TransExpr),
2675 IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(), Ret: std::move(*TransRetReq));
2676}
2677
2678concepts::NestedRequirement *
2679TemplateInstantiator::TransformNestedRequirement(
2680 concepts::NestedRequirement *Req) {
2681
2682 ASTContext &C = SemaRef.Context;
2683
2684 Expr *Constraint = Req->getConstraintExpr();
2685 ConstraintSatisfaction Satisfaction;
2686
2687 auto NestedReqWithDiag = [&C, this](Expr *E,
2688 ConstraintSatisfaction Satisfaction) {
2689 Satisfaction.IsSatisfied = false;
2690 SmallString<128> Entity;
2691 llvm::raw_svector_ostream OS(Entity);
2692 E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy());
2693 return new (C) concepts::NestedRequirement(
2694 SemaRef.Context, C.backupStr(S: Entity), std::move(Satisfaction));
2695 };
2696
2697 if (Req->hasInvalidConstraint()) {
2698 if (AlwaysRebuild())
2699 return RebuildNestedRequirement(InvalidConstraintEntity: Req->getInvalidConstraintEntity(),
2700 Satisfaction: Req->getConstraintSatisfaction());
2701 return Req;
2702 }
2703
2704 if (!getEvaluateConstraints()) {
2705 ExprResult TransConstraint = TransformExpr(E: Req->getConstraintExpr());
2706 if (TransConstraint.isInvalid() || !TransConstraint.get())
2707 return nullptr;
2708 if (TransConstraint.get()->isInstantiationDependent())
2709 return new (SemaRef.Context)
2710 concepts::NestedRequirement(TransConstraint.get());
2711 ConstraintSatisfaction Satisfaction;
2712 return new (SemaRef.Context) concepts::NestedRequirement(
2713 SemaRef.Context, TransConstraint.get(), Satisfaction);
2714 }
2715
2716 bool Success;
2717 Expr *NewConstraint;
2718 {
2719 EnterExpressionEvaluationContext ContextRAII(
2720 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2721 Sema::InstantiatingTemplate ConstrInst(
2722 SemaRef, Constraint->getBeginLoc(), Req,
2723 Sema::InstantiatingTemplate::ConstraintsCheck(),
2724 Constraint->getSourceRange());
2725
2726 if (ConstrInst.isInvalid())
2727 return nullptr;
2728
2729 Success = !SemaRef.CheckConstraintSatisfaction(
2730 Entity: Req, AssociatedConstraints: AssociatedConstraint(Constraint, SemaRef.ArgPackSubstIndex),
2731 TemplateArgLists: TemplateArgs, TemplateIDRange: Constraint->getSourceRange(), Satisfaction,
2732 /*TopLevelConceptId=*/nullptr, ConvertedExpr: &NewConstraint);
2733 }
2734
2735 if (!Success || Satisfaction.HasSubstitutionFailure())
2736 return NestedReqWithDiag(Constraint, Satisfaction);
2737
2738 // FIXME: const correctness
2739 // MLTAL might be dependent.
2740 if (!NewConstraint) {
2741 if (!Satisfaction.IsSatisfied)
2742 return NestedReqWithDiag(Constraint, Satisfaction);
2743
2744 NewConstraint = Constraint;
2745 }
2746 return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);
2747}
2748
2749TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
2750 const MultiLevelTemplateArgumentList &Args,
2751 SourceLocation Loc,
2752 DeclarationName Entity,
2753 bool AllowDeducedTST) {
2754 assert(!CodeSynthesisContexts.empty() &&
2755 "Cannot perform an instantiation without some context on the "
2756 "instantiation stack");
2757
2758 if (!T->getType()->isInstantiationDependentType() &&
2759 !T->getType()->isVariablyModifiedType())
2760 return T;
2761
2762 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2763 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(TSI: T)
2764 : Instantiator.TransformType(TSI: T);
2765}
2766
2767TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2768 const MultiLevelTemplateArgumentList &Args,
2769 SourceLocation Loc,
2770 DeclarationName Entity) {
2771 assert(!CodeSynthesisContexts.empty() &&
2772 "Cannot perform an instantiation without some context on the "
2773 "instantiation stack");
2774
2775 if (TL.getType().isNull())
2776 return nullptr;
2777
2778 if (!TL.getType()->isInstantiationDependentType() &&
2779 !TL.getType()->isVariablyModifiedType()) {
2780 // FIXME: Make a copy of the TypeLoc data here, so that we can
2781 // return a new TypeSourceInfo. Inefficient!
2782 TypeLocBuilder TLB;
2783 TLB.pushFullCopy(L: TL);
2784 return TLB.getTypeSourceInfo(Context, T: TL.getType());
2785 }
2786
2787 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2788 TypeLocBuilder TLB;
2789 TLB.reserve(Requested: TL.getFullDataSize());
2790 QualType Result = Instantiator.TransformType(TLB, T: TL);
2791 if (Result.isNull())
2792 return nullptr;
2793
2794 return TLB.getTypeSourceInfo(Context, T: Result);
2795}
2796
2797/// Deprecated form of the above.
2798QualType Sema::SubstType(QualType T,
2799 const MultiLevelTemplateArgumentList &TemplateArgs,
2800 SourceLocation Loc, DeclarationName Entity,
2801 bool *IsIncompleteSubstitution) {
2802 assert(!CodeSynthesisContexts.empty() &&
2803 "Cannot perform an instantiation without some context on the "
2804 "instantiation stack");
2805
2806 // If T is not a dependent type or a variably-modified type, there
2807 // is nothing to do.
2808 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2809 return T;
2810
2811 TemplateInstantiator Instantiator(
2812 *this, TemplateArgs, Loc, Entity,
2813 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2814 QualType QT = Instantiator.TransformType(T);
2815 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2816 *IsIncompleteSubstitution = true;
2817 return QT;
2818}
2819
2820static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2821 if (T->getType()->isInstantiationDependentType() ||
2822 T->getType()->isVariablyModifiedType())
2823 return true;
2824
2825 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2826 if (!TL.getAs<FunctionProtoTypeLoc>())
2827 return false;
2828
2829 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2830 for (ParmVarDecl *P : FP.getParams()) {
2831 // This must be synthesized from a typedef.
2832 if (!P) continue;
2833
2834 // If there are any parameters, a new TypeSourceInfo that refers to the
2835 // instantiated parameters must be built.
2836 return true;
2837 }
2838
2839 return false;
2840}
2841
2842TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
2843 const MultiLevelTemplateArgumentList &Args,
2844 SourceLocation Loc,
2845 DeclarationName Entity,
2846 CXXRecordDecl *ThisContext,
2847 Qualifiers ThisTypeQuals,
2848 bool EvaluateConstraints) {
2849 assert(!CodeSynthesisContexts.empty() &&
2850 "Cannot perform an instantiation without some context on the "
2851 "instantiation stack");
2852
2853 if (!NeedsInstantiationAsFunctionType(T))
2854 return T;
2855
2856 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2857 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2858
2859 TypeLocBuilder TLB;
2860
2861 TypeLoc TL = T->getTypeLoc();
2862 TLB.reserve(Requested: TL.getFullDataSize());
2863
2864 QualType Result;
2865
2866 if (FunctionProtoTypeLoc Proto =
2867 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2868 // Instantiate the type, other than its exception specification. The
2869 // exception specification is instantiated in InitFunctionInstantiation
2870 // once we've built the FunctionDecl.
2871 // FIXME: Set the exception specification to EST_Uninstantiated here,
2872 // instead of rebuilding the function type again later.
2873 Result = Instantiator.TransformFunctionProtoType(
2874 TLB, TL: Proto, ThisContext, ThisTypeQuals,
2875 TransformExceptionSpec: [](FunctionProtoType::ExceptionSpecInfo &ESI,
2876 bool &Changed) { return false; });
2877 } else {
2878 Result = Instantiator.TransformType(TLB, T: TL);
2879 }
2880 // When there are errors resolving types, clang may use IntTy as a fallback,
2881 // breaking our assumption that function declarations have function types.
2882 if (Result.isNull() || !Result->isFunctionType())
2883 return nullptr;
2884
2885 return TLB.getTypeSourceInfo(Context, T: Result);
2886}
2887
2888bool Sema::SubstExceptionSpec(SourceLocation Loc,
2889 FunctionProtoType::ExceptionSpecInfo &ESI,
2890 SmallVectorImpl<QualType> &ExceptionStorage,
2891 const MultiLevelTemplateArgumentList &Args) {
2892 bool Changed = false;
2893 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2894 return Instantiator.TransformExceptionSpec(Loc, ESI, Exceptions&: ExceptionStorage,
2895 Changed);
2896}
2897
2898void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
2899 const MultiLevelTemplateArgumentList &Args) {
2900 FunctionProtoType::ExceptionSpecInfo ESI =
2901 Proto->getExtProtoInfo().ExceptionSpec;
2902
2903 SmallVector<QualType, 4> ExceptionStorage;
2904 if (SubstExceptionSpec(Loc: New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2905 ESI, ExceptionStorage, Args))
2906 // On error, recover by dropping the exception specification.
2907 ESI.Type = EST_None;
2908
2909 UpdateExceptionSpec(FD: New, ESI);
2910}
2911
2912namespace {
2913
2914 struct GetContainedInventedTypeParmVisitor :
2915 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2916 TemplateTypeParmDecl *> {
2917 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2918 TemplateTypeParmDecl *>::Visit;
2919
2920 TemplateTypeParmDecl *Visit(QualType T) {
2921 if (T.isNull())
2922 return nullptr;
2923 return Visit(T: T.getTypePtr());
2924 }
2925 // The deduced type itself.
2926 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2927 const TemplateTypeParmType *T) {
2928 if (!T->getDecl() || !T->getDecl()->isImplicit())
2929 return nullptr;
2930 return T->getDecl();
2931 }
2932
2933 // Only these types can contain 'auto' types, and subsequently be replaced
2934 // by references to invented parameters.
2935
2936 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2937 return Visit(T: T->getPointeeType());
2938 }
2939
2940 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2941 return Visit(T: T->getPointeeType());
2942 }
2943
2944 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2945 return Visit(T: T->getPointeeTypeAsWritten());
2946 }
2947
2948 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2949 return Visit(T: T->getPointeeType());
2950 }
2951
2952 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2953 return Visit(T: T->getElementType());
2954 }
2955
2956 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2957 const DependentSizedExtVectorType *T) {
2958 return Visit(T: T->getElementType());
2959 }
2960
2961 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2962 return Visit(T: T->getElementType());
2963 }
2964
2965 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2966 return VisitFunctionType(T);
2967 }
2968
2969 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2970 return Visit(T: T->getReturnType());
2971 }
2972
2973 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2974 return Visit(T: T->getInnerType());
2975 }
2976
2977 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2978 return Visit(T: T->getModifiedType());
2979 }
2980
2981 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2982 return Visit(T: T->getUnderlyingType());
2983 }
2984
2985 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2986 return Visit(T: T->getOriginalType());
2987 }
2988
2989 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2990 return Visit(T: T->getPattern());
2991 }
2992 };
2993
2994} // namespace
2995
2996bool Sema::SubstTypeConstraint(
2997 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2998 const MultiLevelTemplateArgumentList &TemplateArgs,
2999 bool EvaluateConstraints) {
3000 const ASTTemplateArgumentListInfo *TemplArgInfo =
3001 TC->getTemplateArgsAsWritten();
3002
3003 if (!EvaluateConstraints && !inParameterMappingSubstitution()) {
3004 UnsignedOrNone Index = TC->getArgPackSubstIndex();
3005 if (!Index)
3006 Index = SemaRef.ArgPackSubstIndex;
3007 Inst->setTypeConstraint(CR: TC->getConceptReference(),
3008 ImmediatelyDeclaredConstraint: TC->getImmediatelyDeclaredConstraint(), ArgPackSubstIndex: Index);
3009 return false;
3010 }
3011
3012 TemplateArgumentListInfo InstArgs;
3013
3014 if (TemplArgInfo) {
3015 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3016 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3017 if (SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs,
3018 Outputs&: InstArgs))
3019 return true;
3020 }
3021 return AttachTypeConstraint(
3022 NS: TC->getNestedNameSpecifierLoc(), NameInfo: TC->getConceptNameInfo(),
3023 NamedConcept: TC->getNamedConcept(),
3024 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), TemplateArgs: &InstArgs, ConstrainedParameter: Inst,
3025 EllipsisLoc: Inst->isParameterPack()
3026 ? cast<CXXFoldExpr>(Val: TC->getImmediatelyDeclaredConstraint())
3027 ->getEllipsisLoc()
3028 : SourceLocation());
3029}
3030
3031ParmVarDecl *
3032Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
3033 const MultiLevelTemplateArgumentList &TemplateArgs,
3034 int indexAdjustment, UnsignedOrNone NumExpansions,
3035 bool ExpectParameterPack, bool EvaluateConstraint) {
3036 TypeSourceInfo *OldTSI = OldParm->getTypeSourceInfo();
3037 TypeSourceInfo *NewTSI = nullptr;
3038
3039 TypeLoc OldTL = OldTSI->getTypeLoc();
3040 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3041
3042 // We have a function parameter pack. Substitute into the pattern of the
3043 // expansion.
3044 NewTSI = SubstType(TL: ExpansionTL.getPatternLoc(), Args: TemplateArgs,
3045 Loc: OldParm->getLocation(), Entity: OldParm->getDeclName());
3046 if (!NewTSI)
3047 return nullptr;
3048
3049 if (NewTSI->getType()->containsUnexpandedParameterPack()) {
3050 // We still have unexpanded parameter packs, which means that
3051 // our function parameter is still a function parameter pack.
3052 // Therefore, make its type a pack expansion type.
3053 NewTSI = CheckPackExpansion(Pattern: NewTSI, EllipsisLoc: ExpansionTL.getEllipsisLoc(),
3054 NumExpansions);
3055 } else if (ExpectParameterPack) {
3056 // We expected to get a parameter pack but didn't (because the type
3057 // itself is not a pack expansion type), so complain. This can occur when
3058 // the substitution goes through an alias template that "loses" the
3059 // pack expansion.
3060 Diag(Loc: OldParm->getLocation(),
3061 DiagID: diag::err_function_parameter_pack_without_parameter_packs)
3062 << NewTSI->getType();
3063 return nullptr;
3064 }
3065 } else {
3066 NewTSI = SubstType(T: OldTSI, Args: TemplateArgs, Loc: OldParm->getLocation(),
3067 Entity: OldParm->getDeclName());
3068 }
3069
3070 if (!NewTSI)
3071 return nullptr;
3072
3073 if (NewTSI->getType()->isVoidType()) {
3074 Diag(Loc: OldParm->getLocation(), DiagID: diag::err_param_with_void_type);
3075 return nullptr;
3076 }
3077
3078 // In abbreviated templates, TemplateTypeParmDecls with possible
3079 // TypeConstraints are created when the parameter list is originally parsed.
3080 // The TypeConstraints can therefore reference other functions parameters in
3081 // the abbreviated function template, which is why we must instantiate them
3082 // here, when the instantiated versions of those referenced parameters are in
3083 // scope.
3084 if (TemplateTypeParmDecl *TTP =
3085 GetContainedInventedTypeParmVisitor().Visit(T: OldTSI->getType())) {
3086 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3087 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3088 Val: FindInstantiatedDecl(Loc: TTP->getLocation(), D: TTP, TemplateArgs));
3089 // We will first get here when instantiating the abbreviated function
3090 // template's described function, but we might also get here later.
3091 // Make sure we do not instantiate the TypeConstraint more than once.
3092 if (Inst && !Inst->getTypeConstraint()) {
3093 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraints: EvaluateConstraint))
3094 return nullptr;
3095 }
3096 }
3097 }
3098
3099 ParmVarDecl *NewParm = CheckParameter(
3100 DC: Context.getTranslationUnitDecl(), StartLoc: OldParm->getInnerLocStart(),
3101 NameLoc: OldParm->getLocation(), Name: OldParm->getIdentifier(), T: NewTSI->getType(),
3102 TSInfo: NewTSI, SC: OldParm->getStorageClass());
3103 if (!NewParm)
3104 return nullptr;
3105
3106 // Mark the (new) default argument as uninstantiated (if any).
3107 if (OldParm->hasUninstantiatedDefaultArg()) {
3108 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3109 NewParm->setUninstantiatedDefaultArg(Arg);
3110 } else if (OldParm->hasUnparsedDefaultArg()) {
3111 NewParm->setUnparsedDefaultArg();
3112 UnparsedDefaultArgInstantiations[OldParm].push_back(NewVal: NewParm);
3113 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3114 // Default arguments cannot be substituted until the declaration context
3115 // for the associated function or lambda capture class is available.
3116 // This is necessary for cases like the following where construction of
3117 // the lambda capture class for the outer lambda is dependent on the
3118 // parameter types but where the default argument is dependent on the
3119 // outer lambda's declaration context.
3120 // template <typename T>
3121 // auto f() {
3122 // return [](T = []{ return T{}; }()) { return 0; };
3123 // }
3124 NewParm->setUninstantiatedDefaultArg(Arg);
3125 }
3126
3127 NewParm->setExplicitObjectParameterLoc(
3128 OldParm->getExplicitObjectParamThisLoc());
3129 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
3130
3131 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3132 // Add the new parameter to the instantiated parameter pack.
3133 CurrentInstantiationScope->InstantiatedLocalPackArg(D: OldParm, Inst: NewParm);
3134 } else {
3135 // Introduce an Old -> New mapping
3136 CurrentInstantiationScope->InstantiatedLocal(D: OldParm, Inst: NewParm);
3137 }
3138
3139 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3140 // can be anything, is this right ?
3141 NewParm->setDeclContext(CurContext);
3142
3143 NewParm->setScopeInfo(scopeDepth: OldParm->getFunctionScopeDepth(),
3144 parameterIndex: OldParm->getFunctionScopeIndex() + indexAdjustment);
3145
3146 InstantiateAttrs(TemplateArgs, Pattern: OldParm, Inst: NewParm);
3147
3148 return NewParm;
3149}
3150
3151bool Sema::SubstParmTypes(
3152 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
3153 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3154 const MultiLevelTemplateArgumentList &TemplateArgs,
3155 SmallVectorImpl<QualType> &ParamTypes,
3156 SmallVectorImpl<ParmVarDecl *> *OutParams,
3157 ExtParameterInfoBuilder &ParamInfos) {
3158 assert(!CodeSynthesisContexts.empty() &&
3159 "Cannot perform an instantiation without some context on the "
3160 "instantiation stack");
3161
3162 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3163 DeclarationName());
3164 return Instantiator.TransformFunctionTypeParams(
3165 Loc, Params, ParamTypes: nullptr, ParamInfos: ExtParamInfos, PTypes&: ParamTypes, PVars: OutParams, PInfos&: ParamInfos);
3166}
3167
3168bool Sema::SubstDefaultArgument(
3169 SourceLocation Loc,
3170 ParmVarDecl *Param,
3171 const MultiLevelTemplateArgumentList &TemplateArgs,
3172 bool ForCallExpr) {
3173 FunctionDecl *FD = cast<FunctionDecl>(Val: Param->getDeclContext());
3174 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3175
3176 RecursiveInstGuard AlreadyInstantiating(
3177 *this, Param, RecursiveInstGuard::Kind::DefaultArgument);
3178 if (AlreadyInstantiating) {
3179 Param->setInvalidDecl();
3180 return Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument)
3181 << FD << PatternExpr->getSourceRange();
3182 }
3183
3184 EnterExpressionEvaluationContext EvalContext(
3185 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
3186 NonSFINAEContext _(*this);
3187 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3188 if (Inst.isInvalid())
3189 return true;
3190
3191 ExprResult Result;
3192 // C++ [dcl.fct.default]p5:
3193 // The names in the [default argument] expression are bound, and
3194 // the semantic constraints are checked, at the point where the
3195 // default argument expression appears.
3196 ContextRAII SavedContext(*this, FD);
3197 {
3198 std::optional<LocalInstantiationScope> LIS;
3199
3200 if (ForCallExpr) {
3201 // When instantiating a default argument due to use in a call expression,
3202 // an instantiation scope that includes the parameters of the callee is
3203 // required to satisfy references from the default argument. For example:
3204 // template<typename T> void f(T a, int = decltype(a)());
3205 // void g() { f(0); }
3206 LIS.emplace(args&: *this);
3207 FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern(
3208 /*ForDefinition*/ false);
3209 if (addInstantiatedParametersToScope(Function: FD, PatternDecl: PatternFD, Scope&: *LIS, TemplateArgs))
3210 return true;
3211 }
3212
3213 runWithSufficientStackSpace(Loc, Fn: [&] {
3214 Result = SubstInitializer(E: PatternExpr, TemplateArgs,
3215 /*DirectInit*/ CXXDirectInit: false);
3216 });
3217 }
3218 if (Result.isInvalid())
3219 return true;
3220
3221 if (ForCallExpr) {
3222 // Check the expression as an initializer for the parameter.
3223 InitializedEntity Entity
3224 = InitializedEntity::InitializeParameter(Context, Parm: Param);
3225 InitializationKind Kind = InitializationKind::CreateCopy(
3226 InitLoc: Param->getLocation(),
3227 /*FIXME:EqualLoc*/ EqualLoc: PatternExpr->getBeginLoc());
3228 Expr *ResultE = Result.getAs<Expr>();
3229
3230 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3231 Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: ResultE);
3232 if (Result.isInvalid())
3233 return true;
3234
3235 Result =
3236 ActOnFinishFullExpr(Expr: Result.getAs<Expr>(), CC: Param->getOuterLocStart(),
3237 /*DiscardedValue*/ false);
3238 } else {
3239 // FIXME: Obtain the source location for the '=' token.
3240 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3241 Result = ConvertParamDefaultArgument(Param, DefaultArg: Result.getAs<Expr>(), EqualLoc);
3242 }
3243 if (Result.isInvalid())
3244 return true;
3245
3246 // Remember the instantiated default argument.
3247 Param->setDefaultArg(Result.getAs<Expr>());
3248
3249 return false;
3250}
3251
3252// See TreeTransform::PreparePackForExpansion for the relevant comment.
3253// This function implements the same concept for base specifiers.
3254static bool
3255PreparePackForExpansion(Sema &S, const CXXBaseSpecifier &Base,
3256 const MultiLevelTemplateArgumentList &TemplateArgs,
3257 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3258 SourceRange BaseSourceRange = Base.getSourceRange();
3259 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3260 Info.Ellipsis = Base.getEllipsisLoc();
3261 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3262 TypeSourceInfo *BaseTypeInfo,
3263 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3264 // This is a pack expansion. See whether we should expand it now, or
3265 // wait until later.
3266 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3267 S.collectUnexpandedParameterPacks(TL: BaseTypeInfo->getTypeLoc(), Unexpanded);
3268 if (IsLateExpansionAttempt) {
3269 // Request expansion only when there is an opportunity to expand a pack
3270 // that required a substituion first.
3271 bool SawPackTypes =
3272 llvm::any_of(Range&: Unexpanded, P: [](UnexpandedParameterPack P) {
3273 return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>();
3274 });
3275 if (!SawPackTypes) {
3276 Info.Expand = false;
3277 return false;
3278 }
3279 }
3280
3281 // Determine whether the set of unexpanded parameter packs can and should be
3282 // expanded.
3283 Info.Expand = false;
3284 Info.RetainExpansion = false;
3285 Info.NumExpansions = std::nullopt;
3286 return S.CheckParameterPacksForExpansion(
3287 EllipsisLoc: BaseEllipsisLoc, PatternRange: BaseSourceRange, Unexpanded, TemplateArgs,
3288 /*FailOnPackProducingTemplates=*/false, ShouldExpand&: Info.Expand,
3289 RetainExpansion&: Info.RetainExpansion, NumExpansions&: Info.NumExpansions);
3290 };
3291
3292 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3293 return true;
3294
3295 if (Info.Expand) {
3296 Out = Base.getTypeSourceInfo();
3297 return false;
3298 }
3299
3300 // The resulting base specifier will (still) be a pack expansion.
3301 {
3302 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3303 Out = S.SubstType(T: Base.getTypeSourceInfo(), Args: TemplateArgs,
3304 Loc: BaseSourceRange.getBegin(), Entity: DeclarationName());
3305 }
3306 if (!Out->getType()->containsUnexpandedParameterPack())
3307 return false;
3308
3309 // Some packs will learn their length after substitution.
3310 // We may need to request their expansion.
3311 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3312 return true;
3313 if (Info.Expand)
3314 Info.ExpandUnderForgetSubstitions = true;
3315 return false;
3316}
3317
3318bool
3319Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
3320 CXXRecordDecl *Pattern,
3321 const MultiLevelTemplateArgumentList &TemplateArgs) {
3322 bool Invalid = false;
3323 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3324 for (const auto &Base : Pattern->bases()) {
3325 if (!Base.getType()->isDependentType()) {
3326 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3327 if (RD->isInvalidDecl())
3328 Instantiation->setInvalidDecl();
3329 }
3330 InstantiatedBases.push_back(Elt: new (Context) CXXBaseSpecifier(Base));
3331 continue;
3332 }
3333
3334 SourceLocation EllipsisLoc;
3335 TypeSourceInfo *BaseTypeLoc = nullptr;
3336 if (Base.isPackExpansion()) {
3337 UnexpandedInfo Info;
3338 if (PreparePackForExpansion(S&: *this, Base, TemplateArgs, Out&: BaseTypeLoc,
3339 Info)) {
3340 Invalid = true;
3341 continue;
3342 }
3343
3344 // If we should expand this pack expansion now, do so.
3345 MultiLevelTemplateArgumentList EmptyList;
3346 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3347 if (Info.ExpandUnderForgetSubstitions)
3348 ArgsForSubst = &EmptyList;
3349
3350 if (Info.Expand) {
3351 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3352 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3353
3354 TypeSourceInfo *Expanded =
3355 SubstType(T: BaseTypeLoc, Args: *ArgsForSubst,
3356 Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName());
3357 if (!Expanded) {
3358 Invalid = true;
3359 continue;
3360 }
3361
3362 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3363 Class: Instantiation, SpecifierRange: Base.getSourceRange(), Virtual: Base.isVirtual(),
3364 Access: Base.getAccessSpecifierAsWritten(), TInfo: Expanded,
3365 EllipsisLoc: SourceLocation()))
3366 InstantiatedBases.push_back(Elt: InstantiatedBase);
3367 else
3368 Invalid = true;
3369 }
3370
3371 continue;
3372 }
3373
3374 // The resulting base specifier will (still) be a pack expansion.
3375 EllipsisLoc = Base.getEllipsisLoc();
3376 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3377 BaseTypeLoc =
3378 SubstType(T: BaseTypeLoc, Args: *ArgsForSubst,
3379 Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName());
3380 } else {
3381 BaseTypeLoc = SubstType(T: Base.getTypeSourceInfo(),
3382 Args: TemplateArgs,
3383 Loc: Base.getSourceRange().getBegin(),
3384 Entity: DeclarationName());
3385 }
3386
3387 if (!BaseTypeLoc) {
3388 Invalid = true;
3389 continue;
3390 }
3391
3392 if (CXXBaseSpecifier *InstantiatedBase
3393 = CheckBaseSpecifier(Class: Instantiation,
3394 SpecifierRange: Base.getSourceRange(),
3395 Virtual: Base.isVirtual(),
3396 Access: Base.getAccessSpecifierAsWritten(),
3397 TInfo: BaseTypeLoc,
3398 EllipsisLoc))
3399 InstantiatedBases.push_back(Elt: InstantiatedBase);
3400 else
3401 Invalid = true;
3402 }
3403
3404 if (!Invalid && AttachBaseSpecifiers(Class: Instantiation, Bases: InstantiatedBases))
3405 Invalid = true;
3406
3407 return Invalid;
3408}
3409
3410// Defined via #include from SemaTemplateInstantiateDecl.cpp
3411namespace clang {
3412 namespace sema {
3413 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
3414 const MultiLevelTemplateArgumentList &TemplateArgs);
3415 Attr *instantiateTemplateAttributeForDecl(
3416 const Attr *At, ASTContext &C, Sema &S,
3417 const MultiLevelTemplateArgumentList &TemplateArgs);
3418 }
3419}
3420
3421bool Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3422 CXXRecordDecl *Instantiation,
3423 CXXRecordDecl *Pattern,
3424 const MultiLevelTemplateArgumentList &TemplateArgs,
3425 TemplateSpecializationKind TSK, bool Complain) {
3426#ifndef NDEBUG
3427 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3428 RecursiveInstGuard::Kind::Template);
3429 assert(!AlreadyInstantiating && "should have been caught by caller");
3430#endif
3431
3432 return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern,
3433 TemplateArgs, TSK, Complain);
3434}
3435
3436bool Sema::InstantiateClassImpl(
3437 SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation,
3438 CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs,
3439 TemplateSpecializationKind TSK, bool Complain) {
3440
3441 CXXRecordDecl *PatternDef
3442 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
3443 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3444 InstantiatedFromMember: Instantiation->getInstantiatedFromMemberClass(),
3445 Pattern, PatternDef, TSK, Complain))
3446 return true;
3447
3448 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3449 llvm::TimeTraceMetadata M;
3450 llvm::raw_string_ostream OS(M.Detail);
3451 Instantiation->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
3452 /*Qualified=*/true);
3453 if (llvm::isTimeTraceVerbose()) {
3454 auto Loc = SourceMgr.getExpansionLoc(Loc: Instantiation->getLocation());
3455 M.File = SourceMgr.getFilename(SpellingLoc: Loc);
3456 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3457 }
3458 return M;
3459 });
3460
3461 Pattern = PatternDef;
3462
3463 // Record the point of instantiation.
3464 if (MemberSpecializationInfo *MSInfo
3465 = Instantiation->getMemberSpecializationInfo()) {
3466 MSInfo->setTemplateSpecializationKind(TSK);
3467 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3468 } else if (ClassTemplateSpecializationDecl *Spec
3469 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Instantiation)) {
3470 Spec->setTemplateSpecializationKind(TSK);
3471 Spec->setPointOfInstantiation(PointOfInstantiation);
3472 }
3473
3474 NonSFINAEContext _(*this);
3475 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3476 if (Inst.isInvalid())
3477 return true;
3478 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3479 "instantiating class definition");
3480
3481 // Enter the scope of this instantiation. We don't use
3482 // PushDeclContext because we don't have a scope.
3483 ContextRAII SavedContext(*this, Instantiation);
3484 EnterExpressionEvaluationContext EvalContext(
3485 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3486
3487 // If this is an instantiation of a local class, merge this local
3488 // instantiation scope with the enclosing scope. Otherwise, every
3489 // instantiation of a class has its own local instantiation scope.
3490 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3491 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3492
3493 // Some class state isn't processed immediately but delayed till class
3494 // instantiation completes. We may not be ready to handle any delayed state
3495 // already on the stack as it might correspond to a different class, so save
3496 // it now and put it back later.
3497 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3498
3499 // Pull attributes from the pattern onto the instantiation.
3500 InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation);
3501
3502 // Start the definition of this instantiation.
3503 Instantiation->startDefinition();
3504
3505 // The instantiation is visible here, even if it was first declared in an
3506 // unimported module.
3507 Instantiation->setVisibleDespiteOwningModule();
3508
3509 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3510 Instantiation->setTagKind(Pattern->getTagKind());
3511
3512 // Do substitution on the base class specifiers.
3513 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3514 Instantiation->setInvalidDecl();
3515
3516 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3517 Instantiator.setEvaluateConstraints(false);
3518 SmallVector<Decl*, 4> Fields;
3519 // Delay instantiation of late parsed attributes.
3520 LateInstantiatedAttrVec LateAttrs;
3521 Instantiator.enableLateAttributeInstantiation(LA: &LateAttrs);
3522
3523 bool MightHaveConstexprVirtualFunctions = false;
3524 for (auto *Member : Pattern->decls()) {
3525 // Don't instantiate members not belonging in this semantic context.
3526 // e.g. for:
3527 // @code
3528 // template <int i> class A {
3529 // class B *g;
3530 // };
3531 // @endcode
3532 // 'class B' has the template as lexical context but semantically it is
3533 // introduced in namespace scope.
3534 if (Member->getDeclContext() != Pattern)
3535 continue;
3536
3537 // BlockDecls can appear in a default-member-initializer. They must be the
3538 // child of a BlockExpr, so we only know how to instantiate them from there.
3539 // Similarly, lambda closure types are recreated when instantiating the
3540 // corresponding LambdaExpr.
3541 if (isa<BlockDecl>(Val: Member) ||
3542 (isa<CXXRecordDecl>(Val: Member) && cast<CXXRecordDecl>(Val: Member)->isLambda()))
3543 continue;
3544
3545 if (Member->isInvalidDecl()) {
3546 Instantiation->setInvalidDecl();
3547 continue;
3548 }
3549
3550 Decl *NewMember = Instantiator.Visit(D: Member);
3551 if (NewMember) {
3552 if (FieldDecl *Field = dyn_cast<FieldDecl>(Val: NewMember)) {
3553 Fields.push_back(Elt: Field);
3554 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Val: NewMember)) {
3555 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3556 // specialization causes the implicit instantiation of the definitions
3557 // of unscoped member enumerations.
3558 // Record a point of instantiation for this implicit instantiation.
3559 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3560 Enum->isCompleteDefinition()) {
3561 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3562 assert(MSInfo && "no spec info for member enum specialization");
3563 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
3564 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3565 }
3566 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(Val: NewMember)) {
3567 if (SA->isFailed()) {
3568 // A static_assert failed. Bail out; instantiating this
3569 // class is probably not meaningful.
3570 Instantiation->setInvalidDecl();
3571 break;
3572 }
3573 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewMember)) {
3574 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3575 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3576 MightHaveConstexprVirtualFunctions = true;
3577 }
3578
3579 if (NewMember->isInvalidDecl())
3580 Instantiation->setInvalidDecl();
3581 } else {
3582 // FIXME: Eventually, a NULL return will mean that one of the
3583 // instantiations was a semantic disaster, and we'll want to mark the
3584 // declaration invalid.
3585 // For now, we expect to skip some members that we can't yet handle.
3586 }
3587 }
3588
3589 // Finish checking fields.
3590 ActOnFields(S: nullptr, RecLoc: Instantiation->getLocation(), TagDecl: Instantiation, Fields,
3591 LBrac: SourceLocation(), RBrac: SourceLocation(), AttrList: ParsedAttributesView());
3592 CheckCompletedCXXClass(S: nullptr, Record: Instantiation);
3593
3594 // Default arguments are parsed, if not instantiated. We can go instantiate
3595 // default arg exprs for default constructors if necessary now. Unless we're
3596 // parsing a class, in which case wait until that's finished.
3597 if (ParsingClassDepth == 0)
3598 ActOnFinishCXXNonNestedClass();
3599
3600 // Instantiate late parsed attributes, and attach them to their decls.
3601 // See Sema::InstantiateAttrs
3602 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3603 E = LateAttrs.end(); I != E; ++I) {
3604 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3605 CurrentInstantiationScope = I->Scope;
3606
3607 // Allow 'this' within late-parsed attributes.
3608 auto *ND = cast<NamedDecl>(Val: I->NewDecl);
3609 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: ND->getDeclContext());
3610 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3611 ND->isCXXInstanceMember());
3612
3613 Attr *NewAttr =
3614 instantiateTemplateAttribute(At: I->TmplAttr, C&: Context, S&: *this, TemplateArgs);
3615 if (NewAttr)
3616 I->NewDecl->addAttr(A: NewAttr);
3617 LocalInstantiationScope::deleteScopes(Scope: I->Scope,
3618 Outermost: Instantiator.getStartingScope());
3619 }
3620 Instantiator.disableLateAttributeInstantiation();
3621 LateAttrs.clear();
3622
3623 ActOnFinishDelayedMemberInitializers(Record: Instantiation);
3624
3625 // FIXME: We should do something similar for explicit instantiations so they
3626 // end up in the right module.
3627 if (TSK == TSK_ImplicitInstantiation) {
3628 Instantiation->setLocation(Pattern->getLocation());
3629 Instantiation->setLocStart(Pattern->getInnerLocStart());
3630 Instantiation->setBraceRange(Pattern->getBraceRange());
3631 }
3632
3633 if (!Instantiation->isInvalidDecl()) {
3634 // Perform any dependent diagnostics from the pattern.
3635 if (Pattern->isDependentContext())
3636 PerformDependentDiagnostics(Pattern, TemplateArgs);
3637
3638 // Instantiate any out-of-line class template partial
3639 // specializations now.
3640 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
3641 P = Instantiator.delayed_partial_spec_begin(),
3642 PEnd = Instantiator.delayed_partial_spec_end();
3643 P != PEnd; ++P) {
3644 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3645 ClassTemplate: P->first, PartialSpec: P->second)) {
3646 Instantiation->setInvalidDecl();
3647 break;
3648 }
3649 }
3650
3651 // Instantiate any out-of-line variable template partial
3652 // specializations now.
3653 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
3654 P = Instantiator.delayed_var_partial_spec_begin(),
3655 PEnd = Instantiator.delayed_var_partial_spec_end();
3656 P != PEnd; ++P) {
3657 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3658 VarTemplate: P->first, PartialSpec: P->second)) {
3659 Instantiation->setInvalidDecl();
3660 break;
3661 }
3662 }
3663 }
3664
3665 // Exit the scope of this instantiation.
3666 SavedContext.pop();
3667
3668 if (!Instantiation->isInvalidDecl()) {
3669 // Always emit the vtable for an explicit instantiation definition
3670 // of a polymorphic class template specialization. Otherwise, eagerly
3671 // instantiate only constexpr virtual functions in preparation for their use
3672 // in constant evaluation.
3673 if (TSK == TSK_ExplicitInstantiationDefinition)
3674 MarkVTableUsed(Loc: PointOfInstantiation, Class: Instantiation, DefinitionRequired: true);
3675 else if (MightHaveConstexprVirtualFunctions)
3676 MarkVirtualMembersReferenced(Loc: PointOfInstantiation, RD: Instantiation,
3677 /*ConstexprOnly*/ true);
3678 }
3679
3680 Consumer.HandleTagDeclDefinition(D: Instantiation);
3681
3682 return Instantiation->isInvalidDecl();
3683}
3684
3685bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3686 EnumDecl *Instantiation, EnumDecl *Pattern,
3687 const MultiLevelTemplateArgumentList &TemplateArgs,
3688 TemplateSpecializationKind TSK) {
3689#ifndef NDEBUG
3690 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3691 RecursiveInstGuard::Kind::Template);
3692 assert(!AlreadyInstantiating && "should have been caught by caller");
3693#endif
3694
3695 EnumDecl *PatternDef = Pattern->getDefinition();
3696 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3697 InstantiatedFromMember: Instantiation->getInstantiatedFromMemberEnum(),
3698 Pattern, PatternDef, TSK,/*Complain*/true))
3699 return true;
3700 Pattern = PatternDef;
3701
3702 // Record the point of instantiation.
3703 if (MemberSpecializationInfo *MSInfo
3704 = Instantiation->getMemberSpecializationInfo()) {
3705 MSInfo->setTemplateSpecializationKind(TSK);
3706 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3707 }
3708
3709 NonSFINAEContext _(*this);
3710 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3711 if (Inst.isInvalid())
3712 return true;
3713 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3714 "instantiating enum definition");
3715
3716 // The instantiation is visible here, even if it was first declared in an
3717 // unimported module.
3718 Instantiation->setVisibleDespiteOwningModule();
3719
3720 // Enter the scope of this instantiation. We don't use
3721 // PushDeclContext because we don't have a scope.
3722 ContextRAII SavedContext(*this, Instantiation);
3723 EnterExpressionEvaluationContext EvalContext(
3724 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3725
3726 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3727
3728 // Pull attributes from the pattern onto the instantiation.
3729 InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation);
3730
3731 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3732 Instantiator.InstantiateEnumDefinition(Enum: Instantiation, Pattern);
3733
3734 // Exit the scope of this instantiation.
3735 SavedContext.pop();
3736
3737 return Instantiation->isInvalidDecl();
3738}
3739
3740bool Sema::InstantiateInClassInitializer(
3741 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3742 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3743 // If there is no initializer, we don't need to do anything.
3744 if (!Pattern->hasInClassInitializer())
3745 return false;
3746
3747 assert(Instantiation->getInClassInitStyle() ==
3748 Pattern->getInClassInitStyle() &&
3749 "pattern and instantiation disagree about init style");
3750
3751 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3752 RecursiveInstGuard::Kind::Template);
3753 if (AlreadyInstantiating)
3754 // Error out if we hit an instantiation cycle for this initializer.
3755 return Diag(Loc: PointOfInstantiation,
3756 DiagID: diag::err_default_member_initializer_cycle)
3757 << Instantiation;
3758
3759 // Error out if we haven't parsed the initializer of the pattern yet because
3760 // we are waiting for the closing brace of the outer class.
3761 Expr *OldInit = Pattern->getInClassInitializer();
3762 if (!OldInit) {
3763 RecordDecl *PatternRD = Pattern->getParent();
3764 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3765 Diag(Loc: PointOfInstantiation,
3766 DiagID: diag::err_default_member_initializer_not_yet_parsed)
3767 << OutermostClass << Pattern;
3768 Diag(Loc: Pattern->getEndLoc(),
3769 DiagID: diag::note_default_member_initializer_not_yet_parsed);
3770 Instantiation->setInvalidDecl();
3771 return true;
3772 }
3773
3774 NonSFINAEContext _(*this);
3775 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3776 if (Inst.isInvalid())
3777 return true;
3778 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3779 "instantiating default member init");
3780
3781 // Enter the scope of this instantiation. We don't use PushDeclContext because
3782 // we don't have a scope.
3783 ContextRAII SavedContext(*this, Instantiation->getParent());
3784 EnterExpressionEvaluationContext EvalContext(
3785 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3786 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3787 PointOfInstantiation, Instantiation, CurContext};
3788
3789 LocalInstantiationScope Scope(*this, true);
3790
3791 // Instantiate the initializer.
3792 ActOnStartCXXInClassMemberInitializer();
3793 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3794
3795 ExprResult NewInit = SubstInitializer(E: OldInit, TemplateArgs,
3796 /*CXXDirectInit=*/false);
3797 Expr *Init = NewInit.get();
3798 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3799 ActOnFinishCXXInClassMemberInitializer(
3800 VarDecl: Instantiation, EqualLoc: Init ? Init->getBeginLoc() : SourceLocation(), Init);
3801
3802 if (auto *L = getASTMutationListener())
3803 L->DefaultMemberInitializerInstantiated(D: Instantiation);
3804
3805 // Return true if the in-class initializer is still missing.
3806 return !Instantiation->getInClassInitializer();
3807}
3808
3809namespace {
3810 /// A partial specialization whose template arguments have matched
3811 /// a given template-id.
3812 struct PartialSpecMatchResult {
3813 ClassTemplatePartialSpecializationDecl *Partial;
3814 TemplateArgumentList *Args;
3815 };
3816}
3817
3818bool Sema::usesPartialOrExplicitSpecialization(
3819 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3820 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3821 TSK_ExplicitSpecialization)
3822 return true;
3823
3824 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3825 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
3826 CTD->getPartialSpecializations(PS&: PartialSpecs);
3827 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
3828 // C++ [temp.spec.partial.member]p2:
3829 // If the primary member template is explicitly specialized for a given
3830 // (implicit) specialization of the enclosing class template, the partial
3831 // specializations of the member template are ignored for this
3832 // specialization of the enclosing class template. If a partial
3833 // specialization of the member template is explicitly specialized for a
3834 // given (implicit) specialization of the enclosing class template, the
3835 // primary member template and its other partial specializations are still
3836 // considered for this specialization of the enclosing class template.
3837 if (CTD->getMostRecentDecl()->isMemberSpecialization() &&
3838 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
3839 continue;
3840
3841 TemplateDeductionInfo Info(Loc);
3842 if (DeduceTemplateArguments(Partial: CTPSD,
3843 TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(),
3844 Info) == TemplateDeductionResult::Success)
3845 return true;
3846 }
3847
3848 return false;
3849}
3850
3851/// Get the instantiation pattern to use to instantiate the definition of a
3852/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3853/// template or of a partial specialization).
3854static ActionResult<CXXRecordDecl *> getPatternForClassTemplateSpecialization(
3855 Sema &S, SourceLocation PointOfInstantiation,
3856 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3857 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
3858 std::optional<Sema::NonSFINAEContext> NSC(S);
3859 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3860 if (Inst.isInvalid())
3861 return {/*Invalid=*/true};
3862
3863 llvm::PointerUnion<ClassTemplateDecl *,
3864 ClassTemplatePartialSpecializationDecl *>
3865 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3866 if (!isa<ClassTemplatePartialSpecializationDecl *>(Val: Specialized)) {
3867 // Find best matching specialization.
3868 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3869
3870 // C++ [temp.class.spec.match]p1:
3871 // When a class template is used in a context that requires an
3872 // instantiation of the class, it is necessary to determine
3873 // whether the instantiation is to be generated using the primary
3874 // template or one of the partial specializations. This is done by
3875 // matching the template arguments of the class template
3876 // specialization with the template argument lists of the partial
3877 // specializations.
3878 typedef PartialSpecMatchResult MatchResult;
3879 SmallVector<MatchResult, 4> Matched, ExtraMatched;
3880 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3881 Template->getPartialSpecializations(PS&: PartialSpecs);
3882 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3883 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
3884 // C++ [temp.spec.partial.member]p2:
3885 // If the primary member template is explicitly specialized for a given
3886 // (implicit) specialization of the enclosing class template, the
3887 // partial specializations of the member template are ignored for this
3888 // specialization of the enclosing class template. If a partial
3889 // specialization of the member template is explicitly specialized for a
3890 // given (implicit) specialization of the enclosing class template, the
3891 // primary member template and its other partial specializations are
3892 // still considered for this specialization of the enclosing class
3893 // template.
3894 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
3895 !Partial->getMostRecentDecl()->isMemberSpecialization())
3896 continue;
3897
3898 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3899 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
3900 Partial, TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3901 Result != TemplateDeductionResult::Success) {
3902 // Store the failed-deduction information for use in diagnostics, later.
3903 // TODO: Actually use the failed-deduction info?
3904 FailedCandidates.addCandidate().set(
3905 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
3906 Info: MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info));
3907 (void)Result;
3908 } else {
3909 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
3910 List.push_back(Elt: MatchResult{.Partial: Partial, .Args: Info.takeCanonical()});
3911 }
3912 }
3913 if (Matched.empty() && PrimaryStrictPackMatch)
3914 Matched = std::move(ExtraMatched);
3915
3916 // If we're dealing with a member template where the template parameters
3917 // have been instantiated, this provides the original template parameters
3918 // from which the member template's parameters were instantiated.
3919
3920 if (Matched.size() >= 1) {
3921 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3922 if (Matched.size() == 1) {
3923 // -- If exactly one matching specialization is found, the
3924 // instantiation is generated from that specialization.
3925 // We don't need to do anything for this.
3926 } else {
3927 // -- If more than one matching specialization is found, the
3928 // partial order rules (14.5.4.2) are used to determine
3929 // whether one of the specializations is more specialized
3930 // than the others. If none of the specializations is more
3931 // specialized than all of the other matching
3932 // specializations, then the use of the class template is
3933 // ambiguous and the program is ill-formed.
3934 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
3935 PEnd = Matched.end();
3936 P != PEnd; ++P) {
3937 if (S.getMoreSpecializedPartialSpecialization(
3938 PS1: P->Partial, PS2: Best->Partial, Loc: PointOfInstantiation) ==
3939 P->Partial)
3940 Best = P;
3941 }
3942
3943 // Determine if the best partial specialization is more specialized than
3944 // the others.
3945 bool Ambiguous = false;
3946 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3947 PEnd = Matched.end();
3948 P != PEnd; ++P) {
3949 if (P != Best && S.getMoreSpecializedPartialSpecialization(
3950 PS1: P->Partial, PS2: Best->Partial,
3951 Loc: PointOfInstantiation) != Best->Partial) {
3952 Ambiguous = true;
3953 break;
3954 }
3955 }
3956
3957 if (Ambiguous) {
3958 // Partial ordering did not produce a clear winner. Complain.
3959 Inst.Clear();
3960 NSC.reset();
3961 S.Diag(Loc: PointOfInstantiation,
3962 DiagID: diag::err_partial_spec_ordering_ambiguous)
3963 << ClassTemplateSpec;
3964
3965 // Print the matching partial specializations.
3966 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3967 PEnd = Matched.end();
3968 P != PEnd; ++P)
3969 S.Diag(Loc: P->Partial->getLocation(), DiagID: diag::note_partial_spec_match)
3970 << S.getTemplateArgumentBindingsText(
3971 Params: P->Partial->getTemplateParameters(), Args: *P->Args);
3972
3973 return {/*Invalid=*/true};
3974 }
3975 }
3976
3977 ClassTemplateSpec->setInstantiationOf(PartialSpec: Best->Partial, TemplateArgs: Best->Args);
3978 } else {
3979 // -- If no matches are found, the instantiation is generated
3980 // from the primary template.
3981 }
3982 }
3983
3984 CXXRecordDecl *Pattern = nullptr;
3985 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3986 if (auto *PartialSpec =
3987 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3988 // Instantiate using the best class template partial specialization.
3989 while (PartialSpec->getInstantiatedFromMember()) {
3990 // If we've found an explicit specialization of this class template,
3991 // stop here and use that as the pattern.
3992 if (PartialSpec->isMemberSpecialization())
3993 break;
3994
3995 PartialSpec = PartialSpec->getInstantiatedFromMember();
3996 }
3997 Pattern = PartialSpec;
3998 } else {
3999 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4000 while (Template->getInstantiatedFromMemberTemplate()) {
4001 // If we've found an explicit specialization of this class template,
4002 // stop here and use that as the pattern.
4003 if (Template->isMemberSpecialization())
4004 break;
4005
4006 Template = Template->getInstantiatedFromMemberTemplate();
4007 }
4008 Pattern = Template->getTemplatedDecl();
4009 }
4010
4011 return Pattern;
4012}
4013
4014bool Sema::InstantiateClassTemplateSpecialization(
4015 SourceLocation PointOfInstantiation,
4016 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4017 TemplateSpecializationKind TSK, bool Complain,
4018 bool PrimaryStrictPackMatch) {
4019 // Perform the actual instantiation on the canonical declaration.
4020 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4021 Val: ClassTemplateSpec->getCanonicalDecl());
4022 if (ClassTemplateSpec->isInvalidDecl())
4023 return true;
4024
4025 Sema::RecursiveInstGuard AlreadyInstantiating(
4026 *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template);
4027 if (AlreadyInstantiating)
4028 return false;
4029
4030 bool HadAvaibilityWarning =
4031 ShouldDiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Message: nullptr, ClassReceiver: nullptr)
4032 .first != AR_Available;
4033
4034 ActionResult<CXXRecordDecl *> Pattern =
4035 getPatternForClassTemplateSpecialization(S&: *this, PointOfInstantiation,
4036 ClassTemplateSpec, TSK,
4037 PrimaryStrictPackMatch);
4038
4039 if (!Pattern.isUsable())
4040 return Pattern.isInvalid();
4041
4042 bool Err = InstantiateClassImpl(
4043 PointOfInstantiation, Instantiation: ClassTemplateSpec, Pattern: Pattern.get(),
4044 TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec), TSK, Complain);
4045
4046 // If we haven't already warn on avaibility, consider the avaibility
4047 // attributes of the partial specialization.
4048 // Note that - because we need to have deduced the partial specialization -
4049 // We can only emit these warnings when the specialization is instantiated.
4050 if (!Err && !HadAvaibilityWarning) {
4051 assert(ClassTemplateSpec->getTemplateSpecializationKind() !=
4052 TSK_Undeclared);
4053 DiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Locs: PointOfInstantiation);
4054 }
4055 return Err;
4056}
4057
4058void
4059Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
4060 CXXRecordDecl *Instantiation,
4061 const MultiLevelTemplateArgumentList &TemplateArgs,
4062 TemplateSpecializationKind TSK) {
4063 // FIXME: We need to notify the ASTMutationListener that we did all of these
4064 // things, in case we have an explicit instantiation definition in a PCM, a
4065 // module, or preamble, and the declaration is in an imported AST.
4066 assert(
4067 (TSK == TSK_ExplicitInstantiationDefinition ||
4068 TSK == TSK_ExplicitInstantiationDeclaration ||
4069 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4070 "Unexpected template specialization kind!");
4071 for (auto *D : Instantiation->decls()) {
4072 bool SuppressNew = false;
4073 if (auto *Function = dyn_cast<FunctionDecl>(Val: D)) {
4074 if (FunctionDecl *Pattern =
4075 Function->getInstantiatedFromMemberFunction()) {
4076
4077 if (Function->getTrailingRequiresClause()) {
4078 ConstraintSatisfaction Satisfaction;
4079 if (CheckFunctionConstraints(FD: Function, Satisfaction) ||
4080 !Satisfaction.IsSatisfied) {
4081 continue;
4082 }
4083 }
4084
4085 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4086 continue;
4087
4088 TemplateSpecializationKind PrevTSK =
4089 Function->getTemplateSpecializationKind();
4090 if (PrevTSK == TSK_ExplicitSpecialization)
4091 continue;
4092
4093 if (CheckSpecializationInstantiationRedecl(
4094 NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Function, PrevTSK,
4095 PrevPtOfInstantiation: Function->getPointOfInstantiation(), SuppressNew) ||
4096 SuppressNew)
4097 continue;
4098
4099 // C++11 [temp.explicit]p8:
4100 // An explicit instantiation definition that names a class template
4101 // specialization explicitly instantiates the class template
4102 // specialization and is only an explicit instantiation definition
4103 // of members whose definition is visible at the point of
4104 // instantiation.
4105 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4106 continue;
4107
4108 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4109
4110 if (Function->isDefined()) {
4111 // Let the ASTConsumer know that this function has been explicitly
4112 // instantiated now, and its linkage might have changed.
4113 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Function));
4114 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4115 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4116 } else if (TSK == TSK_ImplicitInstantiation) {
4117 PendingLocalImplicitInstantiations.push_back(
4118 x: std::make_pair(x&: Function, y&: PointOfInstantiation));
4119 }
4120 }
4121 } else if (auto *Var = dyn_cast<VarDecl>(Val: D)) {
4122 if (isa<VarTemplateSpecializationDecl>(Val: Var))
4123 continue;
4124
4125 if (Var->isStaticDataMember()) {
4126 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4127 continue;
4128
4129 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4130 assert(MSInfo && "No member specialization information?");
4131 if (MSInfo->getTemplateSpecializationKind()
4132 == TSK_ExplicitSpecialization)
4133 continue;
4134
4135 if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK,
4136 PrevDecl: Var,
4137 PrevTSK: MSInfo->getTemplateSpecializationKind(),
4138 PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(),
4139 SuppressNew) ||
4140 SuppressNew)
4141 continue;
4142
4143 if (TSK == TSK_ExplicitInstantiationDefinition) {
4144 // C++0x [temp.explicit]p8:
4145 // An explicit instantiation definition that names a class template
4146 // specialization explicitly instantiates the class template
4147 // specialization and is only an explicit instantiation definition
4148 // of members whose definition is visible at the point of
4149 // instantiation.
4150 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
4151 continue;
4152
4153 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4154 InstantiateVariableDefinition(PointOfInstantiation, Var);
4155 } else {
4156 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4157 }
4158 }
4159 } else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
4160 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4161 continue;
4162
4163 // Always skip the injected-class-name, along with any
4164 // redeclarations of nested classes, since both would cause us
4165 // to try to instantiate the members of a class twice.
4166 // Skip closure types; they'll get instantiated when we instantiate
4167 // the corresponding lambda-expression.
4168 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4169 Record->isLambda())
4170 continue;
4171
4172 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4173 assert(MSInfo && "No member specialization information?");
4174
4175 if (MSInfo->getTemplateSpecializationKind()
4176 == TSK_ExplicitSpecialization)
4177 continue;
4178
4179 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4180 TSK == TSK_ExplicitInstantiationDeclaration) {
4181 // On Windows, explicit instantiation decl of the outer class doesn't
4182 // affect the inner class. Typically extern template declarations are
4183 // used in combination with dll import/export annotations, but those
4184 // are not propagated from the outer class templates to inner classes.
4185 // Therefore, do not instantiate inner classes on this platform, so
4186 // that users don't end up with undefined symbols during linking.
4187 continue;
4188 }
4189
4190 if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK,
4191 PrevDecl: Record,
4192 PrevTSK: MSInfo->getTemplateSpecializationKind(),
4193 PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(),
4194 SuppressNew) ||
4195 SuppressNew)
4196 continue;
4197
4198 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4199 assert(Pattern && "Missing instantiated-from-template information");
4200
4201 if (!Record->getDefinition()) {
4202 if (!Pattern->getDefinition()) {
4203 // C++0x [temp.explicit]p8:
4204 // An explicit instantiation definition that names a class template
4205 // specialization explicitly instantiates the class template
4206 // specialization and is only an explicit instantiation definition
4207 // of members whose definition is visible at the point of
4208 // instantiation.
4209 if (TSK == TSK_ExplicitInstantiationDeclaration) {
4210 MSInfo->setTemplateSpecializationKind(TSK);
4211 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4212 }
4213
4214 continue;
4215 }
4216
4217 InstantiateClass(PointOfInstantiation, Instantiation: Record, Pattern,
4218 TemplateArgs,
4219 TSK);
4220 } else {
4221 if (TSK == TSK_ExplicitInstantiationDefinition &&
4222 Record->getTemplateSpecializationKind() ==
4223 TSK_ExplicitInstantiationDeclaration) {
4224 Record->setTemplateSpecializationKind(TSK);
4225 MarkVTableUsed(Loc: PointOfInstantiation, Class: Record, DefinitionRequired: true);
4226 }
4227 }
4228
4229 Pattern = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
4230 if (Pattern)
4231 InstantiateClassMembers(PointOfInstantiation, Instantiation: Pattern, TemplateArgs,
4232 TSK);
4233 } else if (auto *Enum = dyn_cast<EnumDecl>(Val: D)) {
4234 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4235 assert(MSInfo && "No member specialization information?");
4236
4237 if (MSInfo->getTemplateSpecializationKind()
4238 == TSK_ExplicitSpecialization)
4239 continue;
4240
4241 if (CheckSpecializationInstantiationRedecl(
4242 NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Enum,
4243 PrevTSK: MSInfo->getTemplateSpecializationKind(),
4244 PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(), SuppressNew) ||
4245 SuppressNew)
4246 continue;
4247
4248 if (Enum->getDefinition())
4249 continue;
4250
4251 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4252 assert(Pattern && "Missing instantiated-from-template information");
4253
4254 if (TSK == TSK_ExplicitInstantiationDefinition) {
4255 if (!Pattern->getDefinition())
4256 continue;
4257
4258 InstantiateEnum(PointOfInstantiation, Instantiation: Enum, Pattern, TemplateArgs, TSK);
4259 } else {
4260 MSInfo->setTemplateSpecializationKind(TSK);
4261 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4262 }
4263 } else if (auto *Field = dyn_cast<FieldDecl>(Val: D)) {
4264 // No need to instantiate in-class initializers during explicit
4265 // instantiation.
4266 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4267 // Handle local classes which could have substituted template params.
4268 CXXRecordDecl *ClassPattern =
4269 Instantiation->isLocalClass()
4270 ? Instantiation->getInstantiatedFromMemberClass()
4271 : Instantiation->getTemplateInstantiationPattern();
4272
4273 DeclContext::lookup_result Lookup =
4274 ClassPattern->lookup(Name: Field->getDeclName());
4275 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4276 assert(Pattern);
4277 InstantiateInClassInitializer(PointOfInstantiation, Instantiation: Field, Pattern,
4278 TemplateArgs);
4279 }
4280 }
4281 }
4282}
4283
4284void
4285Sema::InstantiateClassTemplateSpecializationMembers(
4286 SourceLocation PointOfInstantiation,
4287 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4288 TemplateSpecializationKind TSK) {
4289 // C++0x [temp.explicit]p7:
4290 // An explicit instantiation that names a class template
4291 // specialization is an explicit instantion of the same kind
4292 // (declaration or definition) of each of its members (not
4293 // including members inherited from base classes) that has not
4294 // been previously explicitly specialized in the translation unit
4295 // containing the explicit instantiation, except as described
4296 // below.
4297 InstantiateClassMembers(PointOfInstantiation, Instantiation: ClassTemplateSpec,
4298 TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec),
4299 TSK);
4300}
4301
4302StmtResult
4303Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
4304 if (!S)
4305 return S;
4306
4307 TemplateInstantiator Instantiator(*this, TemplateArgs,
4308 SourceLocation(),
4309 DeclarationName());
4310 return Instantiator.TransformStmt(S);
4311}
4312
4313bool Sema::SubstTemplateArgument(
4314 const TemplateArgumentLoc &Input,
4315 const MultiLevelTemplateArgumentList &TemplateArgs,
4316 TemplateArgumentLoc &Output, SourceLocation Loc,
4317 const DeclarationName &Entity) {
4318 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4319 return Instantiator.TransformTemplateArgument(Input, Output);
4320}
4321
4322bool Sema::SubstTemplateArguments(
4323 ArrayRef<TemplateArgumentLoc> Args,
4324 const MultiLevelTemplateArgumentList &TemplateArgs,
4325 TemplateArgumentListInfo &Out) {
4326 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4327 DeclarationName());
4328 return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out);
4329}
4330
4331bool Sema::SubstTemplateArgumentsInParameterMapping(
4332 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
4333 const MultiLevelTemplateArgumentList &TemplateArgs,
4334 TemplateArgumentListInfo &Out) {
4335 TemplateInstantiator Instantiator(
4336 TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,
4337 TemplateArgs);
4338 return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out);
4339}
4340
4341ExprResult
4342Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4343 if (!E)
4344 return E;
4345
4346 TemplateInstantiator Instantiator(*this, TemplateArgs,
4347 SourceLocation(),
4348 DeclarationName());
4349 return Instantiator.TransformExpr(E);
4350}
4351
4352ExprResult
4353Sema::SubstCXXIdExpr(Expr *E,
4354 const MultiLevelTemplateArgumentList &TemplateArgs) {
4355 if (!E)
4356 return E;
4357
4358 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4359 DeclarationName());
4360 return Instantiator.TransformAddressOfOperand(E);
4361}
4362
4363ExprResult
4364Sema::SubstConstraintExpr(Expr *E,
4365 const MultiLevelTemplateArgumentList &TemplateArgs) {
4366 // FIXME: should call SubstExpr directly if this function is equivalent or
4367 // should it be different?
4368 return SubstExpr(E, TemplateArgs);
4369}
4370
4371ExprResult Sema::SubstConstraintExprWithoutSatisfaction(
4372 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4373 if (!E)
4374 return E;
4375
4376 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4377 DeclarationName());
4378 Instantiator.setEvaluateConstraints(false);
4379 return Instantiator.TransformExpr(E);
4380}
4381
4382ExprResult Sema::SubstConceptTemplateArguments(
4383 const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr,
4384 const MultiLevelTemplateArgumentList &MLTAL) {
4385 TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(),
4386 DeclarationName());
4387 const ASTTemplateArgumentListInfo *ArgsAsWritten =
4388 CSE->getTemplateArgsAsWritten();
4389 TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(),
4390 ArgsAsWritten->getRAngleLoc());
4391
4392 NonSFINAEContext _(*this);
4393 Sema::InstantiatingTemplate Inst(
4394 *this, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),
4395 Sema::InstantiatingTemplate::ConstraintNormalization{},
4396 CSE->getNamedConcept(),
4397 ArgsAsWritten->arguments().front().getSourceRange());
4398
4399 if (Inst.isInvalid())
4400 return ExprError();
4401
4402 if (Instantiator.TransformConceptTemplateArguments(
4403 First: ArgsAsWritten->getTemplateArgs(),
4404 Last: ArgsAsWritten->getTemplateArgs() +
4405 ArgsAsWritten->getNumTemplateArgs(),
4406 Outputs&: SubstArgs))
4407 return true;
4408
4409 llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector(
4410 C: SubstArgs.arguments(),
4411 F: [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); });
4412
4413 MultiLevelTemplateArgumentList MLTALForConstraint =
4414 getTemplateInstantiationArgs(
4415 ND: CSE->getNamedConcept(),
4416 DC: CSE->getNamedConcept()->getLexicalDeclContext(),
4417 /*Final=*/false,
4418 /*Innermost=*/NewArgList,
4419 /*RelativeToPrimary=*/true,
4420 /*Pattern=*/nullptr,
4421 /*ForConstraintInstantiation=*/true);
4422
4423 // Rebuild a constraint, only substituting non-dependent concept names
4424 // and nothing else.
4425 // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>.
4426 // only SomeConceptName is substituted, in the constraint expression of C.
4427 struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> {
4428 using Base = TreeTransform<ConstraintExprTransformer>;
4429 MultiLevelTemplateArgumentList &MLTAL;
4430
4431 ConstraintExprTransformer(Sema &SemaRef,
4432 MultiLevelTemplateArgumentList &MLTAL)
4433 : TreeTransform(SemaRef), MLTAL(MLTAL) {}
4434
4435 ExprResult TransformExpr(Expr *E) {
4436 if (!E)
4437 return E;
4438 switch (E->getStmtClass()) {
4439 case Stmt::BinaryOperatorClass:
4440 case Stmt::ConceptSpecializationExprClass:
4441 case Stmt::ParenExprClass:
4442 case Stmt::UnresolvedLookupExprClass:
4443 return Base::TransformExpr(E);
4444 default:
4445 break;
4446 }
4447 return E;
4448 }
4449
4450 // Rebuild both branches of a conjunction / disjunction
4451 // even if there is a substitution failure in one of
4452 // the branch.
4453 ExprResult TransformBinaryOperator(BinaryOperator *E) {
4454 if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd ||
4455 E->getOpcode() == BinaryOperatorKind::BO_LOr))
4456 return E;
4457
4458 ExprResult LHS = TransformExpr(E: E->getLHS());
4459 ExprResult RHS = TransformExpr(E: E->getRHS());
4460
4461 if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
4462 return E;
4463
4464 return BinaryOperator::Create(C: SemaRef.Context, lhs: LHS.get(), rhs: RHS.get(),
4465 opc: E->getOpcode(), ResTy: SemaRef.Context.BoolTy,
4466 VK: VK_PRValue, OK: OK_Ordinary,
4467 opLoc: E->getOperatorLoc(), FPFeatures: FPOptionsOverride{});
4468 }
4469
4470 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
4471 TemplateArgumentLoc &Output,
4472 bool Uneval = false) {
4473 if (Input.getArgument().isConceptOrConceptTemplateParameter())
4474 return Base::TransformTemplateArgument(Input, Output, Uneval);
4475
4476 Output = Input;
4477 return false;
4478 }
4479
4480 ExprResult TransformUnresolvedLookupExpr(UnresolvedLookupExpr *E,
4481 bool IsAddressOfOperand = false) {
4482 if (E->isConceptReference()) {
4483 ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs: MLTAL);
4484 return Res;
4485 }
4486 return E;
4487 }
4488 };
4489
4490 ConstraintExprTransformer Transformer(*this, MLTALForConstraint);
4491 ExprResult Res =
4492 Transformer.TransformExpr(E: const_cast<Expr *>(ConstraintExpr));
4493 return Res;
4494}
4495
4496ExprResult Sema::SubstInitializer(Expr *Init,
4497 const MultiLevelTemplateArgumentList &TemplateArgs,
4498 bool CXXDirectInit) {
4499 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4500 DeclarationName());
4501 return Instantiator.TransformInitializer(Init, NotCopyInit: CXXDirectInit);
4502}
4503
4504bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4505 const MultiLevelTemplateArgumentList &TemplateArgs,
4506 SmallVectorImpl<Expr *> &Outputs) {
4507 if (Exprs.empty())
4508 return false;
4509
4510 TemplateInstantiator Instantiator(*this, TemplateArgs,
4511 SourceLocation(),
4512 DeclarationName());
4513 return Instantiator.TransformExprs(Inputs: Exprs.data(), NumInputs: Exprs.size(),
4514 IsCall, Outputs);
4515}
4516
4517NestedNameSpecifierLoc
4518Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4519 const MultiLevelTemplateArgumentList &TemplateArgs) {
4520 if (!NNS)
4521 return NestedNameSpecifierLoc();
4522
4523 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4524 DeclarationName());
4525 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4526}
4527
4528DeclarationNameInfo
4529Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4530 const MultiLevelTemplateArgumentList &TemplateArgs) {
4531 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4532 NameInfo.getName());
4533 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4534}
4535
4536TemplateName
4537Sema::SubstTemplateName(SourceLocation TemplateKWLoc,
4538 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4539 SourceLocation NameLoc,
4540 const MultiLevelTemplateArgumentList &TemplateArgs) {
4541 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4542 DeclarationName());
4543 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4544 NameLoc);
4545}
4546
4547static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4548 // When storing ParmVarDecls in the local instantiation scope, we always
4549 // want to use the ParmVarDecl from the canonical function declaration,
4550 // since the map is then valid for any redeclaration or definition of that
4551 // function.
4552 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: D)) {
4553 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
4554 unsigned i = PV->getFunctionScopeIndex();
4555 // This parameter might be from a freestanding function type within the
4556 // function and isn't necessarily referring to one of FD's parameters.
4557 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4558 return FD->getCanonicalDecl()->getParamDecl(i);
4559 }
4560 }
4561 return D;
4562}
4563
4564llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4565LocalInstantiationScope::getInstantiationOfIfExists(const Decl *D) {
4566 D = getCanonicalParmVarDecl(D);
4567 for (LocalInstantiationScope *Current = this; Current;
4568 Current = Current->Outer) {
4569
4570 // Check if we found something within this scope.
4571 const Decl *CheckD = D;
4572 do {
4573 LocalDeclsMap::iterator Found = Current->LocalDecls.find(Val: CheckD);
4574 if (Found != Current->LocalDecls.end())
4575 return &Found->second;
4576
4577 // If this is a tag declaration, it's possible that we need to look for
4578 // a previous declaration.
4579 if (const TagDecl *Tag = dyn_cast<TagDecl>(Val: CheckD))
4580 CheckD = Tag->getPreviousDecl();
4581 else
4582 CheckD = nullptr;
4583 } while (CheckD);
4584
4585 // If we aren't combined with our outer scope, we're done.
4586 if (!Current->CombineWithOuterScope)
4587 break;
4588 }
4589
4590 return nullptr;
4591}
4592
4593llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4594LocalInstantiationScope::findInstantiationOf(const Decl *D) {
4595 auto *Result = getInstantiationOfIfExists(D);
4596 if (Result)
4597 return Result;
4598 // If we're performing a partial substitution during template argument
4599 // deduction, we may not have values for template parameters yet.
4600 if (isa<NonTypeTemplateParmDecl>(Val: D) || isa<TemplateTypeParmDecl>(Val: D) ||
4601 isa<TemplateTemplateParmDecl>(Val: D))
4602 return nullptr;
4603
4604 // Local types referenced prior to definition may require instantiation.
4605 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D))
4606 if (RD->isLocalClass())
4607 return nullptr;
4608
4609 // Enumeration types referenced prior to definition may appear as a result of
4610 // error recovery.
4611 if (isa<EnumDecl>(Val: D))
4612 return nullptr;
4613
4614 // Materialized typedefs/type alias for implicit deduction guides may require
4615 // instantiation.
4616 if (isa<TypedefNameDecl>(Val: D) &&
4617 isa<CXXDeductionGuideDecl>(Val: D->getDeclContext()))
4618 return nullptr;
4619
4620 // If we didn't find the decl, then we either have a sema bug, or we have a
4621 // forward reference to a label declaration. Return null to indicate that
4622 // we have an uninstantiated label.
4623 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4624 return nullptr;
4625}
4626
4627void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
4628 D = getCanonicalParmVarDecl(D);
4629 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4630 if (Stored.isNull()) {
4631#ifndef NDEBUG
4632 // It should not be present in any surrounding scope either.
4633 LocalInstantiationScope *Current = this;
4634 while (Current->CombineWithOuterScope && Current->Outer) {
4635 Current = Current->Outer;
4636 assert(!Current->LocalDecls.contains(D) &&
4637 "Instantiated local in inner and outer scopes");
4638 }
4639#endif
4640 Stored = Inst;
4641 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: Stored)) {
4642 Pack->push_back(Elt: cast<ValueDecl>(Val: Inst));
4643 } else {
4644 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4645 }
4646}
4647
4648void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
4649 VarDecl *Inst) {
4650 D = getCanonicalParmVarDecl(D);
4651 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(Val&: LocalDecls[D]);
4652 Pack->push_back(Elt: Inst);
4653}
4654
4655void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
4656#ifndef NDEBUG
4657 // This should be the first time we've been told about this decl.
4658 for (LocalInstantiationScope *Current = this;
4659 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4660 assert(!Current->LocalDecls.contains(D) &&
4661 "Creating local pack after instantiation of local");
4662#endif
4663
4664 D = getCanonicalParmVarDecl(D);
4665 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4666 DeclArgumentPack *Pack = new DeclArgumentPack;
4667 Stored = Pack;
4668 ArgumentPacks.push_back(Elt: Pack);
4669}
4670
4671bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
4672 for (DeclArgumentPack *Pack : ArgumentPacks)
4673 if (llvm::is_contained(Range&: *Pack, Element: D))
4674 return true;
4675 return false;
4676}
4677
4678void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
4679 const TemplateArgument *ExplicitArgs,
4680 unsigned NumExplicitArgs) {
4681 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4682 "Already have a partially-substituted pack");
4683 assert((!PartiallySubstitutedPack
4684 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4685 "Wrong number of arguments in partially-substituted pack");
4686 PartiallySubstitutedPack = Pack;
4687 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4688 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4689}
4690
4691NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
4692 const TemplateArgument **ExplicitArgs,
4693 unsigned *NumExplicitArgs) const {
4694 if (ExplicitArgs)
4695 *ExplicitArgs = nullptr;
4696 if (NumExplicitArgs)
4697 *NumExplicitArgs = 0;
4698
4699 for (const LocalInstantiationScope *Current = this; Current;
4700 Current = Current->Outer) {
4701 if (Current->PartiallySubstitutedPack) {
4702 if (ExplicitArgs)
4703 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4704 if (NumExplicitArgs)
4705 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4706
4707 return Current->PartiallySubstitutedPack;
4708 }
4709
4710 if (!Current->CombineWithOuterScope)
4711 break;
4712 }
4713
4714 return nullptr;
4715}
4716