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

source code of clang/lib/Sema/SemaTemplateInstantiate.cpp