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

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