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