clang 21.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
579 return false;
580
581 // This function should never be called when Kind's value is Memoization.
582 case Memoization:
583 break;
584 }
585
586 llvm_unreachable("Invalid SynthesisKind!");
587}
588
591 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
592 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
593 sema::TemplateDeductionInfo *DeductionInfo)
594 : SemaRef(SemaRef) {
595 // Don't allow further instantiation if a fatal error and an uncompilable
596 // error have occurred. Any diagnostics we might have raised will not be
597 // visible, and we do not need to construct a correct AST.
600 Invalid = true;
601 return;
602 }
603 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
604 if (!Invalid) {
606 Inst.Kind = Kind;
607 Inst.PointOfInstantiation = PointOfInstantiation;
608 Inst.Entity = Entity;
609 Inst.Template = Template;
610 Inst.TemplateArgs = TemplateArgs.data();
611 Inst.NumTemplateArgs = TemplateArgs.size();
612 Inst.DeductionInfo = DeductionInfo;
613 Inst.InstantiationRange = InstantiationRange;
615
616 AlreadyInstantiating = !Inst.Entity ? false :
618 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
619 .second;
621 }
622}
623
625 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
626 SourceRange InstantiationRange)
628 CodeSynthesisContext::TemplateInstantiation,
629 PointOfInstantiation, InstantiationRange, Entity) {}
630
632 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
633 ExceptionSpecification, SourceRange InstantiationRange)
635 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
636 PointOfInstantiation, InstantiationRange, Entity) {}
637
639 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
640 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
641 SourceRange InstantiationRange)
643 SemaRef,
644 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
645 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
646 Template, TemplateArgs) {}
647
649 Sema &SemaRef, SourceLocation PointOfInstantiation,
651 ArrayRef<TemplateArgument> TemplateArgs,
653 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
654 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
655 InstantiationRange, FunctionTemplate, nullptr,
656 TemplateArgs, &DeductionInfo) {
660}
661
663 Sema &SemaRef, SourceLocation PointOfInstantiation,
664 TemplateDecl *Template,
665 ArrayRef<TemplateArgument> TemplateArgs,
666 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
668 SemaRef,
669 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
670 PointOfInstantiation, InstantiationRange, Template, nullptr,
671 TemplateArgs, &DeductionInfo) {}
672
674 Sema &SemaRef, SourceLocation PointOfInstantiation,
676 ArrayRef<TemplateArgument> TemplateArgs,
677 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
679 SemaRef,
680 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
681 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
682 TemplateArgs, &DeductionInfo) {}
683
685 Sema &SemaRef, SourceLocation PointOfInstantiation,
687 ArrayRef<TemplateArgument> TemplateArgs,
688 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
690 SemaRef,
691 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
692 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
693 TemplateArgs, &DeductionInfo) {}
694
696 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
697 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
699 SemaRef,
700 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
701 PointOfInstantiation, InstantiationRange, Param, nullptr,
702 TemplateArgs) {}
703
705 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
707 SourceRange InstantiationRange)
709 SemaRef,
710 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
711 PointOfInstantiation, InstantiationRange, Param, Template,
712 TemplateArgs) {}
713
715 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
717 SourceRange InstantiationRange)
719 SemaRef,
720 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
721 PointOfInstantiation, InstantiationRange, Param, Template,
722 TemplateArgs) {}
723
725 Sema &SemaRef, SourceLocation PointOfInstantiation,
727 SourceRange InstantiationRange)
729 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
730 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
731 /*Template=*/nullptr, TemplateArgs) {}
732
734 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
735 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
736 SourceRange InstantiationRange)
738 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
739 PointOfInstantiation, InstantiationRange, Param, Template,
740 TemplateArgs) {}
741
743 Sema &SemaRef, SourceLocation PointOfInstantiation,
745 SourceRange InstantiationRange)
747 SemaRef, CodeSynthesisContext::RequirementInstantiation,
748 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
749 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
750
752 Sema &SemaRef, SourceLocation PointOfInstantiation,
754 SourceRange InstantiationRange)
756 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
757 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
758 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
759
761 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
762 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
764 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
765 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
766 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
767
769 Sema &SemaRef, SourceLocation PointOfInstantiation,
770 ConstraintsCheck, NamedDecl *Template,
771 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
774 PointOfInstantiation, InstantiationRange, Template, nullptr,
775 TemplateArgs) {}
776
778 Sema &SemaRef, SourceLocation PointOfInstantiation,
780 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
783 PointOfInstantiation, InstantiationRange, Template, nullptr,
784 {}, &DeductionInfo) {}
785
787 Sema &SemaRef, SourceLocation PointOfInstantiation,
789 SourceRange InstantiationRange)
792 PointOfInstantiation, InstantiationRange, Template) {}
793
795 Sema &SemaRef, SourceLocation PointOfInstantiation,
797 SourceRange InstantiationRange)
800 PointOfInstantiation, InstantiationRange, Template) {}
801
803 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
804 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
806 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
807 PointOfInstantiation, InstantiationRange, Entity) {}
808
811 TemplateDecl *PArg, SourceRange InstantiationRange)
813 ArgLoc, InstantiationRange, PArg) {}
814
816 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
818
819 CodeSynthesisContexts.push_back(Ctx);
820
821 if (!Ctx.isInstantiationRecord())
823
824 // Check to see if we're low on stack space. We can't do anything about this
825 // from here, but we can at least warn the user.
826 StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);
827}
828
830 auto &Active = CodeSynthesisContexts.back();
831 if (!Active.isInstantiationRecord()) {
832 assert(NonInstantiationEntries > 0);
834 }
835
836 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
837
838 // Name lookup no longer looks in this template's defining module.
839 assert(CodeSynthesisContexts.size() >=
841 "forgot to remove a lookup module for a template instantiation");
842 if (CodeSynthesisContexts.size() ==
845 LookupModulesCache.erase(M);
847 }
848
849 // If we've left the code synthesis context for the current context stack,
850 // stop remembering that we've emitted that stack.
851 if (CodeSynthesisContexts.size() ==
854
855 CodeSynthesisContexts.pop_back();
856}
857
859 if (!Invalid) {
860 if (!AlreadyInstantiating) {
861 auto &Active = SemaRef.CodeSynthesisContexts.back();
862 if (Active.Entity)
864 {Active.Entity->getCanonicalDecl(), Active.Kind});
865 }
866
869
871 Invalid = true;
872 }
873}
874
875static std::string convertCallArgsToString(Sema &S,
877 std::string Result;
878 llvm::raw_string_ostream OS(Result);
879 llvm::ListSeparator Comma;
880 for (const Expr *Arg : Args) {
881 OS << Comma;
882 Arg->IgnoreParens()->printPretty(OS, nullptr,
884 }
885 return Result;
886}
887
888bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
889 SourceLocation PointOfInstantiation,
890 SourceRange InstantiationRange) {
893 if ((SemaRef.CodeSynthesisContexts.size() -
895 <= SemaRef.getLangOpts().InstantiationDepth)
896 return false;
897
898 SemaRef.Diag(PointOfInstantiation,
899 diag::err_template_recursion_depth_exceeded)
900 << SemaRef.getLangOpts().InstantiationDepth
901 << InstantiationRange;
902 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
903 << SemaRef.getLangOpts().InstantiationDepth;
904 return true;
905}
906
908 // Determine which template instantiations to skip, if any.
909 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
910 unsigned Limit = Diags.getTemplateBacktraceLimit();
911 if (Limit && Limit < CodeSynthesisContexts.size()) {
912 SkipStart = Limit / 2 + Limit % 2;
913 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
914 }
915
916 // FIXME: In all of these cases, we need to show the template arguments
917 unsigned InstantiationIdx = 0;
919 Active = CodeSynthesisContexts.rbegin(),
920 ActiveEnd = CodeSynthesisContexts.rend();
921 Active != ActiveEnd;
922 ++Active, ++InstantiationIdx) {
923 // Skip this instantiation?
924 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
925 if (InstantiationIdx == SkipStart) {
926 // Note that we're skipping instantiations.
927 Diags.Report(Active->PointOfInstantiation,
928 diag::note_instantiation_contexts_suppressed)
929 << unsigned(CodeSynthesisContexts.size() - Limit);
930 }
931 continue;
932 }
933
934 switch (Active->Kind) {
936 Decl *D = Active->Entity;
937 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
938 unsigned DiagID = diag::note_template_member_class_here;
939 if (isa<ClassTemplateSpecializationDecl>(Record))
940 DiagID = diag::note_template_class_instantiation_here;
941 Diags.Report(Active->PointOfInstantiation, DiagID)
942 << Record << Active->InstantiationRange;
943 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
944 unsigned DiagID;
945 if (Function->getPrimaryTemplate())
946 DiagID = diag::note_function_template_spec_here;
947 else
948 DiagID = diag::note_template_member_function_here;
949 Diags.Report(Active->PointOfInstantiation, DiagID)
950 << Function
951 << Active->InstantiationRange;
952 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
953 Diags.Report(Active->PointOfInstantiation,
954 VD->isStaticDataMember()?
955 diag::note_template_static_data_member_def_here
956 : diag::note_template_variable_def_here)
957 << VD
958 << Active->InstantiationRange;
959 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
960 Diags.Report(Active->PointOfInstantiation,
961 diag::note_template_enum_def_here)
962 << ED
963 << Active->InstantiationRange;
964 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
965 Diags.Report(Active->PointOfInstantiation,
966 diag::note_template_nsdmi_here)
967 << FD << Active->InstantiationRange;
968 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
969 Diags.Report(Active->PointOfInstantiation,
970 diag::note_template_class_instantiation_here)
971 << CTD << Active->InstantiationRange;
972 }
973 break;
974 }
975
977 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
978 SmallString<128> TemplateArgsStr;
979 llvm::raw_svector_ostream OS(TemplateArgsStr);
980 Template->printName(OS, getPrintingPolicy());
981 printTemplateArgumentList(OS, Active->template_arguments(),
983 Diags.Report(Active->PointOfInstantiation,
984 diag::note_default_arg_instantiation_here)
985 << OS.str()
986 << Active->InstantiationRange;
987 break;
988 }
989
991 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
992 Diags.Report(Active->PointOfInstantiation,
993 diag::note_explicit_template_arg_substitution_here)
994 << FnTmpl
996 Active->TemplateArgs,
997 Active->NumTemplateArgs)
998 << Active->InstantiationRange;
999 break;
1000 }
1001
1003 if (FunctionTemplateDecl *FnTmpl =
1004 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1005 Diags.Report(Active->PointOfInstantiation,
1006 diag::note_function_template_deduction_instantiation_here)
1007 << FnTmpl
1008 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1009 Active->TemplateArgs,
1010 Active->NumTemplateArgs)
1011 << Active->InstantiationRange;
1012 } else {
1013 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1014 isa<VarTemplateSpecializationDecl>(Active->Entity);
1015 bool IsTemplate = false;
1016 TemplateParameterList *Params;
1017 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1018 IsTemplate = true;
1019 Params = D->getTemplateParameters();
1020 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1021 Active->Entity)) {
1022 Params = D->getTemplateParameters();
1023 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1024 Active->Entity)) {
1025 Params = D->getTemplateParameters();
1026 } else {
1027 llvm_unreachable("unexpected template kind");
1028 }
1029
1030 Diags.Report(Active->PointOfInstantiation,
1031 diag::note_deduced_template_arg_substitution_here)
1032 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1033 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1034 Active->NumTemplateArgs)
1035 << Active->InstantiationRange;
1036 }
1037 break;
1038 }
1039
1041 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1042 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1043
1044 SmallString<128> TemplateArgsStr;
1045 llvm::raw_svector_ostream OS(TemplateArgsStr);
1047 printTemplateArgumentList(OS, Active->template_arguments(),
1049 Diags.Report(Active->PointOfInstantiation,
1050 diag::note_default_function_arg_instantiation_here)
1051 << OS.str()
1052 << Active->InstantiationRange;
1053 break;
1054 }
1055
1057 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1058 std::string Name;
1059 if (!Parm->getName().empty())
1060 Name = std::string(" '") + Parm->getName().str() + "'";
1061
1062 TemplateParameterList *TemplateParams = nullptr;
1063 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1064 TemplateParams = Template->getTemplateParameters();
1065 else
1066 TemplateParams =
1067 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1068 ->getTemplateParameters();
1069 Diags.Report(Active->PointOfInstantiation,
1070 diag::note_prior_template_arg_substitution)
1071 << isa<TemplateTemplateParmDecl>(Parm)
1072 << Name
1073 << getTemplateArgumentBindingsText(TemplateParams,
1074 Active->TemplateArgs,
1075 Active->NumTemplateArgs)
1076 << Active->InstantiationRange;
1077 break;
1078 }
1079
1081 TemplateParameterList *TemplateParams = nullptr;
1082 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1083 TemplateParams = Template->getTemplateParameters();
1084 else
1085 TemplateParams =
1086 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1087 ->getTemplateParameters();
1088
1089 Diags.Report(Active->PointOfInstantiation,
1090 diag::note_template_default_arg_checking)
1091 << getTemplateArgumentBindingsText(TemplateParams,
1092 Active->TemplateArgs,
1093 Active->NumTemplateArgs)
1094 << Active->InstantiationRange;
1095 break;
1096 }
1097
1099 Diags.Report(Active->PointOfInstantiation,
1100 diag::note_evaluating_exception_spec_here)
1101 << cast<FunctionDecl>(Active->Entity);
1102 break;
1103
1105 Diags.Report(Active->PointOfInstantiation,
1106 diag::note_template_exception_spec_instantiation_here)
1107 << cast<FunctionDecl>(Active->Entity)
1108 << Active->InstantiationRange;
1109 break;
1110
1112 Diags.Report(Active->PointOfInstantiation,
1113 diag::note_template_requirement_instantiation_here)
1114 << Active->InstantiationRange;
1115 break;
1117 Diags.Report(Active->PointOfInstantiation,
1118 diag::note_template_requirement_params_instantiation_here)
1119 << Active->InstantiationRange;
1120 break;
1121
1123 Diags.Report(Active->PointOfInstantiation,
1124 diag::note_nested_requirement_here)
1125 << Active->InstantiationRange;
1126 break;
1127
1129 Diags.Report(Active->PointOfInstantiation,
1130 diag::note_in_declaration_of_implicit_special_member)
1131 << cast<CXXRecordDecl>(Active->Entity)
1132 << llvm::to_underlying(Active->SpecialMember);
1133 break;
1134
1136 Diags.Report(Active->Entity->getLocation(),
1137 diag::note_in_declaration_of_implicit_equality_comparison);
1138 break;
1139
1141 // FIXME: For synthesized functions that are not defaulted,
1142 // produce a note.
1143 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1146 if (DFK.isSpecialMember()) {
1147 auto *MD = cast<CXXMethodDecl>(FD);
1148 Diags.Report(Active->PointOfInstantiation,
1149 diag::note_member_synthesized_at)
1150 << MD->isExplicitlyDefaulted()
1151 << llvm::to_underlying(DFK.asSpecialMember())
1152 << Context.getTagDeclType(MD->getParent());
1153 } else if (DFK.isComparison()) {
1154 QualType RecordType = FD->getParamDecl(0)
1155 ->getType()
1156 .getNonReferenceType()
1157 .getUnqualifiedType();
1158 Diags.Report(Active->PointOfInstantiation,
1159 diag::note_comparison_synthesized_at)
1160 << (int)DFK.asComparison() << RecordType;
1161 }
1162 break;
1163 }
1164
1166 Diags.Report(Active->Entity->getLocation(),
1167 diag::note_rewriting_operator_as_spaceship);
1168 break;
1169
1171 Diags.Report(Active->PointOfInstantiation,
1172 diag::note_in_binding_decl_init)
1173 << cast<BindingDecl>(Active->Entity);
1174 break;
1175
1177 Diags.Report(Active->PointOfInstantiation,
1178 diag::note_due_to_dllexported_class)
1179 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1180 break;
1181
1183 Diags.Report(Active->PointOfInstantiation,
1184 diag::note_building_builtin_dump_struct_call)
1186 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1187 break;
1188
1190 break;
1191
1193 Diags.Report(Active->PointOfInstantiation,
1194 diag::note_lambda_substitution_here);
1195 break;
1197 unsigned DiagID = 0;
1198 if (!Active->Entity) {
1199 Diags.Report(Active->PointOfInstantiation,
1200 diag::note_nested_requirement_here)
1201 << Active->InstantiationRange;
1202 break;
1203 }
1204 if (isa<ConceptDecl>(Active->Entity))
1205 DiagID = diag::note_concept_specialization_here;
1206 else if (isa<TemplateDecl>(Active->Entity))
1207 DiagID = diag::note_checking_constraints_for_template_id_here;
1208 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1209 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1210 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1211 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1212 else {
1213 assert(isa<FunctionDecl>(Active->Entity));
1214 DiagID = diag::note_checking_constraints_for_function_here;
1215 }
1216 SmallString<128> TemplateArgsStr;
1217 llvm::raw_svector_ostream OS(TemplateArgsStr);
1218 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1219 if (!isa<FunctionDecl>(Active->Entity)) {
1220 printTemplateArgumentList(OS, Active->template_arguments(),
1222 }
1223 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1224 << Active->InstantiationRange;
1225 break;
1226 }
1228 Diags.Report(Active->PointOfInstantiation,
1229 diag::note_constraint_substitution_here)
1230 << Active->InstantiationRange;
1231 break;
1233 Diags.Report(Active->PointOfInstantiation,
1234 diag::note_constraint_normalization_here)
1235 << cast<NamedDecl>(Active->Entity) << Active->InstantiationRange;
1236 break;
1238 Diags.Report(Active->PointOfInstantiation,
1239 diag::note_parameter_mapping_substitution_here)
1240 << Active->InstantiationRange;
1241 break;
1243 Diags.Report(Active->PointOfInstantiation,
1244 diag::note_building_deduction_guide_here);
1245 break;
1247 Diags.Report(Active->PointOfInstantiation,
1248 diag::note_template_type_alias_instantiation_here)
1249 << cast<TypeAliasTemplateDecl>(Active->Entity)
1250 << Active->InstantiationRange;
1251 break;
1253 Diags.Report(Active->PointOfInstantiation,
1254 diag::note_template_arg_template_params_mismatch);
1255 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1256 ParamLoc.isValid())
1257 Diags.Report(ParamLoc, diag::note_template_prev_declaration)
1258 << /*isTemplateTemplateParam=*/true << Active->InstantiationRange;
1259 break;
1260 }
1261 }
1262}
1263
1264std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1266 return std::optional<TemplateDeductionInfo *>(nullptr);
1267
1269 Active = CodeSynthesisContexts.rbegin(),
1270 ActiveEnd = CodeSynthesisContexts.rend();
1271 Active != ActiveEnd;
1272 ++Active)
1273 {
1274 switch (Active->Kind) {
1276 // An instantiation of an alias template may or may not be a SFINAE
1277 // context, depending on what else is on the stack.
1278 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1279 break;
1280 [[fallthrough]];
1288 // This is a template instantiation, so there is no SFINAE.
1289 return std::nullopt;
1291 // [temp.deduct]p9
1292 // A lambda-expression appearing in a function type or a template
1293 // parameter is not considered part of the immediate context for the
1294 // purposes of template argument deduction.
1295 // CWG2672: A lambda-expression body is never in the immediate context.
1296 return std::nullopt;
1297
1303 // A default template argument instantiation and substitution into
1304 // template parameters with arguments for prior parameters may or may
1305 // not be a SFINAE context; look further up the stack.
1306 break;
1307
1310 // We're either substituting explicitly-specified template arguments,
1311 // deduced template arguments. SFINAE applies unless we are in a lambda
1312 // body, see [temp.deduct]p9.
1316 // SFINAE always applies in a constraint expression or a requirement
1317 // in a requires expression.
1318 assert(Active->DeductionInfo && "Missing deduction info pointer");
1319 return Active->DeductionInfo;
1320
1328 // This happens in a context unrelated to template instantiation, so
1329 // there is no SFINAE.
1330 return std::nullopt;
1331
1333 // FIXME: This should not be treated as a SFINAE context, because
1334 // we will cache an incorrect exception specification. However, clang
1335 // bootstrap relies this! See PR31692.
1336 break;
1337
1339 break;
1340 }
1341
1342 // The inner context was transparent for SFINAE. If it occurred within a
1343 // non-instantiation SFINAE context, then SFINAE applies.
1344 if (Active->SavedInNonInstantiationSFINAEContext)
1345 return std::optional<TemplateDeductionInfo *>(nullptr);
1346 }
1347
1348 return std::nullopt;
1349}
1350
1351//===----------------------------------------------------------------------===/
1352// Template Instantiation for Types
1353//===----------------------------------------------------------------------===/
1354namespace {
1355 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1356 const MultiLevelTemplateArgumentList &TemplateArgs;
1358 DeclarationName Entity;
1359 // Whether to evaluate the C++20 constraints or simply substitute into them.
1360 bool EvaluateConstraints = true;
1361 // Whether Substitution was Incomplete, that is, we tried to substitute in
1362 // any user provided template arguments which were null.
1363 bool IsIncomplete = false;
1364 // Whether an incomplete substituion should be treated as an error.
1365 bool BailOutOnIncomplete;
1366
1367 public:
1368 typedef TreeTransform<TemplateInstantiator> inherited;
1369
1370 TemplateInstantiator(Sema &SemaRef,
1371 const MultiLevelTemplateArgumentList &TemplateArgs,
1373 bool BailOutOnIncomplete = false)
1374 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1375 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1376
1377 void setEvaluateConstraints(bool B) {
1378 EvaluateConstraints = B;
1379 }
1380 bool getEvaluateConstraints() {
1381 return EvaluateConstraints;
1382 }
1383
1384 /// Determine whether the given type \p T has already been
1385 /// transformed.
1386 ///
1387 /// For the purposes of template instantiation, a type has already been
1388 /// transformed if it is NULL or if it is not dependent.
1389 bool AlreadyTransformed(QualType T);
1390
1391 /// Returns the location of the entity being instantiated, if known.
1392 SourceLocation getBaseLocation() { return Loc; }
1393
1394 /// Returns the name of the entity being instantiated, if any.
1395 DeclarationName getBaseEntity() { return Entity; }
1396
1397 /// Returns whether any substitution so far was incomplete.
1398 bool getIsIncomplete() const { return IsIncomplete; }
1399
1400 /// Sets the "base" location and entity when that
1401 /// information is known based on another transformation.
1402 void setBase(SourceLocation Loc, DeclarationName Entity) {
1403 this->Loc = Loc;
1404 this->Entity = Entity;
1405 }
1406
1407 unsigned TransformTemplateDepth(unsigned Depth) {
1408 return TemplateArgs.getNewDepth(Depth);
1409 }
1410
1411 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1412 int Index = getSema().ArgumentPackSubstitutionIndex;
1413 if (Index == -1)
1414 return std::nullopt;
1415 return Pack.pack_size() - 1 - Index;
1416 }
1417
1418 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1419 SourceRange PatternRange,
1421 bool &ShouldExpand, bool &RetainExpansion,
1422 std::optional<unsigned> &NumExpansions) {
1423 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1424 PatternRange, Unexpanded,
1425 TemplateArgs,
1426 ShouldExpand,
1427 RetainExpansion,
1428 NumExpansions);
1429 }
1430
1431 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1433 }
1434
1435 TemplateArgument ForgetPartiallySubstitutedPack() {
1436 TemplateArgument Result;
1437 if (NamedDecl *PartialPack
1439 MultiLevelTemplateArgumentList &TemplateArgs
1440 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1441 unsigned Depth, Index;
1442 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1443 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1444 Result = TemplateArgs(Depth, Index);
1445 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1446 } else {
1447 IsIncomplete = true;
1448 if (BailOutOnIncomplete)
1449 return TemplateArgument();
1450 }
1451 }
1452
1453 return Result;
1454 }
1455
1456 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1457 if (Arg.isNull())
1458 return;
1459
1460 if (NamedDecl *PartialPack
1462 MultiLevelTemplateArgumentList &TemplateArgs
1463 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1464 unsigned Depth, Index;
1465 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1466 TemplateArgs.setArgument(Depth, Index, Arg);
1467 }
1468 }
1469
1470 /// Transform the given declaration by instantiating a reference to
1471 /// this declaration.
1472 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1473
1474 void transformAttrs(Decl *Old, Decl *New) {
1475 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1476 }
1477
1478 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1479 if (Old->isParameterPack() &&
1480 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1482 for (auto *New : NewDecls)
1484 Old, cast<VarDecl>(New));
1485 return;
1486 }
1487
1488 assert(NewDecls.size() == 1 &&
1489 "should only have multiple expansions for a pack");
1490 Decl *New = NewDecls.front();
1491
1492 // If we've instantiated the call operator of a lambda or the call
1493 // operator template of a generic lambda, update the "instantiation of"
1494 // information.
1495 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1496 if (NewMD && isLambdaCallOperator(NewMD)) {
1497 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1498 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1499 NewTD->setInstantiatedFromMemberTemplate(
1500 OldMD->getDescribedFunctionTemplate());
1501 else
1502 NewMD->setInstantiationOfMemberFunction(OldMD,
1504 }
1505
1507
1508 // We recreated a local declaration, but not by instantiating it. There
1509 // may be pending dependent diagnostics to produce.
1510 if (auto *DC = dyn_cast<DeclContext>(Old);
1511 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1512 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1513 }
1514
1515 /// Transform the definition of the given declaration by
1516 /// instantiating it.
1517 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1518
1519 /// Transform the first qualifier within a scope by instantiating the
1520 /// declaration.
1521 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1522
1523 bool TransformExceptionSpec(SourceLocation Loc,
1525 SmallVectorImpl<QualType> &Exceptions,
1526 bool &Changed);
1527
1528 /// Rebuild the exception declaration and register the declaration
1529 /// as an instantiated local.
1530 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1532 SourceLocation StartLoc,
1533 SourceLocation NameLoc,
1534 IdentifierInfo *Name);
1535
1536 /// Rebuild the Objective-C exception declaration and register the
1537 /// declaration as an instantiated local.
1538 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1539 TypeSourceInfo *TSInfo, QualType T);
1540
1541 /// Check for tag mismatches when instantiating an
1542 /// elaborated type.
1543 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1544 ElaboratedTypeKeyword Keyword,
1545 NestedNameSpecifierLoc QualifierLoc,
1546 QualType T);
1547
1549 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1550 SourceLocation NameLoc,
1551 QualType ObjectType = QualType(),
1552 NamedDecl *FirstQualifierInScope = nullptr,
1553 bool AllowInjectedClassName = false);
1554
1555 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1556 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1557 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1558 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1559 const Stmt *InstS,
1560 const NoInlineAttr *A);
1561 const AlwaysInlineAttr *
1562 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1563 const AlwaysInlineAttr *A);
1564 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1565 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1566 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1567 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1568
1569 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1571 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1573 ExprResult TransformSubstNonTypeTemplateParmExpr(
1575
1576 /// Rebuild a DeclRefExpr for a VarDecl reference.
1577 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1578
1579 /// Transform a reference to a function or init-capture parameter pack.
1580 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1581
1582 /// Transform a FunctionParmPackExpr which was built when we couldn't
1583 /// expand a function parameter pack reference which refers to an expanded
1584 /// pack.
1585 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1586
1587 // Transform a ResolvedUnexpandedPackExpr
1589 TransformResolvedUnexpandedPackExpr(ResolvedUnexpandedPackExpr *E);
1590
1591 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1593 // Call the base version; it will forward to our overridden version below.
1594 return inherited::TransformFunctionProtoType(TLB, TL);
1595 }
1596
1597 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1599 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1600 // Special case for transforming a deduction guide, we return a
1601 // transformed TemplateSpecializationType.
1602 if (Type.isNull() &&
1603 SemaRef.CodeSynthesisContexts.back().Kind ==
1605 // Return a TemplateSpecializationType for transforming a deduction
1606 // guide.
1607 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1608 auto Type =
1609 inherited::TransformType(ICT->getInjectedSpecializationType());
1610 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1611 return Type;
1612 }
1613 }
1614 return Type;
1615 }
1616 // Override the default version to handle a rewrite-template-arg-pack case
1617 // for building a deduction guide.
1618 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1619 TemplateArgumentLoc &Output,
1620 bool Uneval = false) {
1621 const TemplateArgument &Arg = Input.getArgument();
1622 std::vector<TemplateArgument> TArgs;
1623 switch (Arg.getKind()) {
1625 // Literally rewrite the template argument pack, instead of unpacking
1626 // it.
1627 for (auto &pack : Arg.getPackAsArray()) {
1629 pack, QualType(), SourceLocation{});
1630 TemplateArgumentLoc Output;
1631 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1632 return true; // fails
1633 TArgs.push_back(Output.getArgument());
1634 }
1635 Output = SemaRef.getTrivialTemplateArgumentLoc(
1636 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1638 return false;
1639 default:
1640 break;
1641 }
1642 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1643 }
1644
1645 template<typename Fn>
1646 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1648 CXXRecordDecl *ThisContext,
1649 Qualifiers ThisTypeQuals,
1650 Fn TransformExceptionSpec);
1651
1652 ParmVarDecl *
1653 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1654 std::optional<unsigned> NumExpansions,
1655 bool ExpectParameterPack);
1656
1657 using inherited::TransformTemplateTypeParmType;
1658 /// Transforms a template type parameter type by performing
1659 /// substitution of the corresponding template type argument.
1660 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1662 bool SuppressObjCLifetime);
1663
1664 QualType BuildSubstTemplateTypeParmType(
1665 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1666 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1667 TemplateArgument Arg, SourceLocation NameLoc);
1668
1669 /// Transforms an already-substituted template type parameter pack
1670 /// into either itself (if we aren't substituting into its pack expansion)
1671 /// or the appropriate substituted argument.
1672 using inherited::TransformSubstTemplateTypeParmPackType;
1673 QualType
1674 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1676 bool SuppressObjCLifetime);
1677
1678 QualType
1679 TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
1682 if (Type->getSubstitutionFlag() !=
1683 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace)
1684 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1685
1686 assert(Type->getPackIndex());
1687 TemplateArgument TA = TemplateArgs(
1688 Type->getReplacedParameter()->getDepth(), Type->getIndex());
1689 assert(*Type->getPackIndex() + 1 <= TA.pack_size());
1691 SemaRef, TA.pack_size() - 1 - *Type->getPackIndex());
1692
1693 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1694 }
1695
1697 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1698 if (auto TypeAlias =
1699 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1700 getSema());
1701 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1702 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1703 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1704 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1705 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1706 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1707 if (TA.isDependent())
1708 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1709 }
1710 return inherited::ComputeLambdaDependency(LSI);
1711 }
1712
1713 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1714 // Do not rebuild lambdas to avoid creating a new type.
1715 // Lambdas have already been processed inside their eval contexts.
1717 return E;
1718 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1719 /*InstantiatingLambdaOrBlock=*/true);
1721
1722 return inherited::TransformLambdaExpr(E);
1723 }
1724
1725 ExprResult TransformBlockExpr(BlockExpr *E) {
1726 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1727 /*InstantiatingLambdaOrBlock=*/true);
1728 return inherited::TransformBlockExpr(E);
1729 }
1730
1731 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1732 LambdaScopeInfo *LSI) {
1733 CXXMethodDecl *MD = LSI->CallOperator;
1734 for (ParmVarDecl *PVD : MD->parameters()) {
1735 assert(PVD && "null in a parameter list");
1736 if (!PVD->hasDefaultArg())
1737 continue;
1738 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1739 // FIXME: Obtain the source location for the '=' token.
1740 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1741 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1742 // If substitution fails, the default argument is set to a
1743 // RecoveryExpr that wraps the uninstantiated default argument so
1744 // that downstream diagnostics are omitted.
1745 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1746 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1747 UninstExpr->getType());
1748 if (ErrorResult.isUsable())
1749 PVD->setDefaultArg(ErrorResult.get());
1750 }
1751 }
1752 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1753 }
1754
1755 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1756 // Currently, we instantiate the body when instantiating the lambda
1757 // expression. However, `EvaluateConstraints` is disabled during the
1758 // instantiation of the lambda expression, causing the instantiation
1759 // failure of the return type requirement in the body. If p0588r1 is fully
1760 // implemented, the body will be lazily instantiated, and this problem
1761 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1762 // `true` to temporarily fix this issue.
1763 // FIXME: This temporary fix can be removed after fully implementing
1764 // p0588r1.
1765 llvm::SaveAndRestore _(EvaluateConstraints, true);
1766 return inherited::TransformLambdaBody(E, Body);
1767 }
1768
1769 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1770 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1771 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1772 if (TransReq.isInvalid())
1773 return TransReq;
1774 assert(TransReq.get() != E &&
1775 "Do not change value of isSatisfied for the existing expression. "
1776 "Create a new expression instead.");
1777 if (E->getBody()->isDependentContext()) {
1778 Sema::SFINAETrap Trap(SemaRef);
1779 // We recreate the RequiresExpr body, but not by instantiating it.
1780 // Produce pending diagnostics for dependent access check.
1781 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1782 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1783 if (Trap.hasErrorOccurred())
1784 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1785 }
1786 return TransReq;
1787 }
1788
1789 bool TransformRequiresExprRequirements(
1792 bool SatisfactionDetermined = false;
1793 for (concepts::Requirement *Req : Reqs) {
1794 concepts::Requirement *TransReq = nullptr;
1795 if (!SatisfactionDetermined) {
1796 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1797 TransReq = TransformTypeRequirement(TypeReq);
1798 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1799 TransReq = TransformExprRequirement(ExprReq);
1800 else
1801 TransReq = TransformNestedRequirement(
1802 cast<concepts::NestedRequirement>(Req));
1803 if (!TransReq)
1804 return true;
1805 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1806 // [expr.prim.req]p6
1807 // [...] The substitution and semantic constraint checking
1808 // proceeds in lexical order and stops when a condition that
1809 // determines the result of the requires-expression is
1810 // encountered. [..]
1811 SatisfactionDetermined = true;
1812 } else
1813 TransReq = Req;
1814 Transformed.push_back(TransReq);
1815 }
1816 return false;
1817 }
1818
1819 TemplateParameterList *TransformTemplateParameterList(
1820 TemplateParameterList *OrigTPL) {
1821 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1822
1823 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1824 TemplateDeclInstantiator DeclInstantiator(getSema(),
1825 /* DeclContext *Owner */ Owner, TemplateArgs);
1826 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1827 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1828 }
1829
1831 TransformTypeRequirement(concepts::TypeRequirement *Req);
1833 TransformExprRequirement(concepts::ExprRequirement *Req);
1835 TransformNestedRequirement(concepts::NestedRequirement *Req);
1836 ExprResult TransformRequiresTypeParams(
1837 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1840 SmallVectorImpl<ParmVarDecl *> &TransParams,
1842
1843 private:
1845 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1846 const NonTypeTemplateParmDecl *parm,
1848 std::optional<unsigned> PackIndex);
1849 };
1850}
1851
1852bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1853 if (T.isNull())
1854 return true;
1855
1858 return false;
1859
1860 getSema().MarkDeclarationsReferencedInType(Loc, T);
1861 return true;
1862}
1863
1864static TemplateArgument
1866 assert(S.ArgumentPackSubstitutionIndex >= 0);
1867 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1869 if (Arg.isPackExpansion())
1870 Arg = Arg.getPackExpansionPattern();
1871 return Arg;
1872}
1873
1874Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1875 if (!D)
1876 return nullptr;
1877
1878 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1879 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1880 // If the corresponding template argument is NULL or non-existent, it's
1881 // because we are performing instantiation from explicitly-specified
1882 // template arguments in a function template, but there were some
1883 // arguments left unspecified.
1884 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1885 TTP->getPosition())) {
1886 IsIncomplete = true;
1887 return BailOutOnIncomplete ? nullptr : D;
1888 }
1889
1890 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1891
1892 if (TTP->isParameterPack()) {
1893 assert(Arg.getKind() == TemplateArgument::Pack &&
1894 "Missing argument pack");
1895 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1896 }
1897
1898 TemplateName Template = Arg.getAsTemplate();
1899 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1900 "Wrong kind of template template argument");
1901 return Template.getAsTemplateDecl();
1902 }
1903
1904 // Fall through to find the instantiated declaration for this template
1905 // template parameter.
1906 }
1907
1908 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1909}
1910
1911Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1912 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1913 if (!Inst)
1914 return nullptr;
1915
1916 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1917 return Inst;
1918}
1919
1920bool TemplateInstantiator::TransformExceptionSpec(
1922 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1923 if (ESI.Type == EST_Uninstantiated) {
1924 ESI.instantiate();
1925 Changed = true;
1926 }
1927 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1928}
1929
1930NamedDecl *
1931TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1933 // If the first part of the nested-name-specifier was a template type
1934 // parameter, instantiate that type parameter down to a tag type.
1935 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1936 const TemplateTypeParmType *TTP
1937 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1938
1939 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1940 // FIXME: This needs testing w/ member access expressions.
1941 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1942
1943 if (TTP->isParameterPack()) {
1944 assert(Arg.getKind() == TemplateArgument::Pack &&
1945 "Missing argument pack");
1946
1947 if (getSema().ArgumentPackSubstitutionIndex == -1)
1948 return nullptr;
1949
1950 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1951 }
1952
1953 QualType T = Arg.getAsType();
1954 if (T.isNull())
1955 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1956
1957 if (const TagType *Tag = T->getAs<TagType>())
1958 return Tag->getDecl();
1959
1960 // The resulting type is not a tag; complain.
1961 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1962 return nullptr;
1963 }
1964 }
1965
1966 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1967}
1968
1969VarDecl *
1970TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1972 SourceLocation StartLoc,
1973 SourceLocation NameLoc,
1974 IdentifierInfo *Name) {
1975 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1976 StartLoc, NameLoc, Name);
1977 if (Var)
1978 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1979 return Var;
1980}
1981
1982VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1983 TypeSourceInfo *TSInfo,
1984 QualType T) {
1985 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1986 if (Var)
1987 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1988 return Var;
1989}
1990
1992TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1993 ElaboratedTypeKeyword Keyword,
1994 NestedNameSpecifierLoc QualifierLoc,
1995 QualType T) {
1996 if (const TagType *TT = T->getAs<TagType>()) {
1997 TagDecl* TD = TT->getDecl();
1998
1999 SourceLocation TagLocation = KeywordLoc;
2000
2002
2003 // TODO: should we even warn on struct/class mismatches for this? Seems
2004 // like it's likely to produce a lot of spurious errors.
2005 if (Id && Keyword != ElaboratedTypeKeyword::None &&
2008 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
2009 TagLocation, Id)) {
2010 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
2011 << Id
2013 TD->getKindName());
2014 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
2015 }
2016 }
2017 }
2018
2019 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
2020}
2021
2022TemplateName TemplateInstantiator::TransformTemplateName(
2023 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
2024 QualType ObjectType, NamedDecl *FirstQualifierInScope,
2025 bool AllowInjectedClassName) {
2027 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
2028 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2029 // If the corresponding template argument is NULL or non-existent, it's
2030 // because we are performing instantiation from explicitly-specified
2031 // template arguments in a function template, but there were some
2032 // arguments left unspecified.
2033 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2034 TTP->getPosition())) {
2035 IsIncomplete = true;
2036 return BailOutOnIncomplete ? TemplateName() : Name;
2037 }
2038
2039 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2040
2041 if (TemplateArgs.isRewrite()) {
2042 // We're rewriting the template parameter as a reference to another
2043 // template parameter.
2044 if (Arg.getKind() == TemplateArgument::Pack) {
2045 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2046 "unexpected pack arguments in template rewrite");
2047 Arg = Arg.pack_begin()->getPackExpansionPattern();
2048 }
2049 assert(Arg.getKind() == TemplateArgument::Template &&
2050 "unexpected nontype template argument kind in template rewrite");
2051 return Arg.getAsTemplate();
2052 }
2053
2054 auto [AssociatedDecl, Final] =
2055 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2056 std::optional<unsigned> PackIndex;
2057 if (TTP->isParameterPack()) {
2058 assert(Arg.getKind() == TemplateArgument::Pack &&
2059 "Missing argument pack");
2060
2061 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2062 // We have the template argument pack to substitute, but we're not
2063 // actually expanding the enclosing pack expansion yet. So, just
2064 // keep the entire argument pack.
2065 return getSema().Context.getSubstTemplateTemplateParmPack(
2066 Arg, AssociatedDecl, TTP->getIndex(), Final);
2067 }
2068
2069 PackIndex = getPackIndex(Arg);
2070 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2071 }
2072
2073 TemplateName Template = Arg.getAsTemplate();
2074 assert(!Template.isNull() && "Null template template argument");
2075
2076 if (Final)
2077 return Template;
2078 return getSema().Context.getSubstTemplateTemplateParm(
2079 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2080 }
2081 }
2082
2084 = Name.getAsSubstTemplateTemplateParmPack()) {
2085 if (getSema().ArgumentPackSubstitutionIndex == -1)
2086 return Name;
2087
2088 TemplateArgument Pack = SubstPack->getArgumentPack();
2089 TemplateName Template =
2091 if (SubstPack->getFinal())
2092 return Template;
2093 return getSema().Context.getSubstTemplateTemplateParm(
2094 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2095 getPackIndex(Pack));
2096 }
2097
2098 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2099 FirstQualifierInScope,
2100 AllowInjectedClassName);
2101}
2102
2104TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2105 if (!E->isTypeDependent())
2106 return E;
2107
2108 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2109}
2110
2112TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2114 // If the corresponding template argument is NULL or non-existent, it's
2115 // because we are performing instantiation from explicitly-specified
2116 // template arguments in a function template, but there were some
2117 // arguments left unspecified.
2118 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2119 NTTP->getPosition())) {
2120 IsIncomplete = true;
2121 return BailOutOnIncomplete ? ExprError() : E;
2122 }
2123
2124 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2125
2126 if (TemplateArgs.isRewrite()) {
2127 // We're rewriting the template parameter as a reference to another
2128 // template parameter.
2129 if (Arg.getKind() == TemplateArgument::Pack) {
2130 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2131 "unexpected pack arguments in template rewrite");
2132 Arg = Arg.pack_begin()->getPackExpansionPattern();
2133 }
2134 assert(Arg.getKind() == TemplateArgument::Expression &&
2135 "unexpected nontype template argument kind in template rewrite");
2136 // FIXME: This can lead to the same subexpression appearing multiple times
2137 // in a complete expression.
2138 return Arg.getAsExpr();
2139 }
2140
2141 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2142 std::optional<unsigned> PackIndex;
2143 if (NTTP->isParameterPack()) {
2144 assert(Arg.getKind() == TemplateArgument::Pack &&
2145 "Missing argument pack");
2146
2147 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2148 // We have an argument pack, but we can't select a particular argument
2149 // out of it yet. Therefore, we'll build an expression to hold on to that
2150 // argument pack.
2151 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2152 E->getLocation(),
2153 NTTP->getDeclName());
2154 if (TargetType.isNull())
2155 return ExprError();
2156
2157 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2158 if (TargetType->isRecordType())
2159 ExprType.addConst();
2160 // FIXME: Pass in Final.
2162 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2163 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2164 }
2165 PackIndex = getPackIndex(Arg);
2166 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2167 }
2168 // FIXME: Don't put subst node on Final replacement.
2169 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2170 Arg, PackIndex);
2171}
2172
2173const AnnotateAttr *
2174TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2176 for (Expr *Arg : AA->args()) {
2177 ExprResult Res = getDerived().TransformExpr(Arg);
2178 if (Res.isUsable())
2179 Args.push_back(Res.get());
2180 }
2181 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2182 Args.data(), Args.size(), AA->getRange());
2183}
2184
2185const CXXAssumeAttr *
2186TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2187 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2188 if (!Res.isUsable())
2189 return AA;
2190
2191 Res = getSema().ActOnFinishFullExpr(Res.get(),
2192 /*DiscardedValue=*/false);
2193 if (!Res.isUsable())
2194 return AA;
2195
2196 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2197 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2198 AA->getRange());
2199 if (!Res.isUsable())
2200 return AA;
2201 }
2202
2203 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2204 AA->getRange());
2205}
2206
2207const LoopHintAttr *
2208TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2209 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2210
2211 if (TransformedExpr == LH->getValue())
2212 return LH;
2213
2214 // Generate error if there is a problem with the value.
2215 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2216 LH->getSemanticSpelling() ==
2217 LoopHintAttr::Pragma_unroll))
2218 return LH;
2219
2220 LoopHintAttr::OptionType Option = LH->getOption();
2221 LoopHintAttr::LoopHintState State = LH->getState();
2222
2223 llvm::APSInt ValueAPS =
2224 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2225 // The values of 0 and 1 block any unrolling of the loop.
2226 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2227 Option = LoopHintAttr::Unroll;
2228 State = LoopHintAttr::Disable;
2229 }
2230
2231 // Create new LoopHintValueAttr with integral expression in place of the
2232 // non-type template parameter.
2233 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2234 TransformedExpr, *LH);
2235}
2236const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2237 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2238 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2239 return nullptr;
2240
2241 return A;
2242}
2243const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2244 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2245 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2246 return nullptr;
2247
2248 return A;
2249}
2250
2251const CodeAlignAttr *
2252TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2253 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2254 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2255}
2256
2257ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2258 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2260 std::optional<unsigned> PackIndex) {
2261 ExprResult result;
2262
2263 // Determine the substituted parameter type. We can usually infer this from
2264 // the template argument, but not always.
2265 auto SubstParamType = [&] {
2266 QualType T;
2267 if (parm->isExpandedParameterPack())
2269 else
2270 T = parm->getType();
2271 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2272 T = cast<PackExpansionType>(T)->getPattern();
2273 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2274 };
2275
2276 bool refParam = false;
2277
2278 // The template argument itself might be an expression, in which case we just
2279 // return that expression. This happens when substituting into an alias
2280 // template.
2281 if (arg.getKind() == TemplateArgument::Expression) {
2282 Expr *argExpr = arg.getAsExpr();
2283 result = argExpr;
2284 if (argExpr->isLValue()) {
2285 if (argExpr->getType()->isRecordType()) {
2286 // Check whether the parameter was actually a reference.
2287 QualType paramType = SubstParamType();
2288 if (paramType.isNull())
2289 return ExprError();
2290 refParam = paramType->isReferenceType();
2291 } else {
2292 refParam = true;
2293 }
2294 }
2295 } else if (arg.getKind() == TemplateArgument::Declaration ||
2296 arg.getKind() == TemplateArgument::NullPtr) {
2297 if (arg.getKind() == TemplateArgument::Declaration) {
2298 ValueDecl *VD = arg.getAsDecl();
2299
2300 // Find the instantiation of the template argument. This is
2301 // required for nested templates.
2302 VD = cast_or_null<ValueDecl>(
2303 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2304 if (!VD)
2305 return ExprError();
2306 }
2307
2308 QualType paramType = arg.getNonTypeTemplateArgumentType();
2309 assert(!paramType.isNull() && "type substitution failed for param type");
2310 assert(!paramType->isDependentType() && "param type still dependent");
2311 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2312 refParam = paramType->isReferenceType();
2313 } else {
2314 QualType paramType = arg.getNonTypeTemplateArgumentType();
2316 refParam = paramType->isReferenceType();
2317 assert(result.isInvalid() ||
2319 paramType.getNonReferenceType()));
2320 }
2321
2322 if (result.isInvalid())
2323 return ExprError();
2324
2325 Expr *resultExpr = result.get();
2326 // FIXME: Don't put subst node on final replacement.
2328 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2329 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2330}
2331
2333TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2335 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2336 // We aren't expanding the parameter pack, so just return ourselves.
2337 return E;
2338 }
2339
2340 TemplateArgument Pack = E->getArgumentPack();
2342 // FIXME: Don't put subst node on final replacement.
2343 return transformNonTypeTemplateParmRef(
2344 E->getAssociatedDecl(), E->getParameterPack(),
2345 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2346}
2347
2349TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2351 ExprResult SubstReplacement = E->getReplacement();
2352 if (!isa<ConstantExpr>(SubstReplacement.get()))
2353 SubstReplacement = TransformExpr(E->getReplacement());
2354 if (SubstReplacement.isInvalid())
2355 return true;
2356 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2357 if (SubstType.isNull())
2358 return true;
2359 // The type may have been previously dependent and not now, which means we
2360 // might have to implicit cast the argument to the new type, for example:
2361 // template<auto T, decltype(T) U>
2362 // concept C = sizeof(U) == 4;
2363 // void foo() requires C<2, 'a'> { }
2364 // When normalizing foo(), we first form the normalized constraints of C:
2365 // AtomicExpr(sizeof(U) == 4,
2366 // U=SubstNonTypeTemplateParmExpr(Param=U,
2367 // Expr=DeclRef(U),
2368 // Type=decltype(T)))
2369 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2370 // produce:
2371 // AtomicExpr(sizeof(U) == 4,
2372 // U=SubstNonTypeTemplateParmExpr(Param=U,
2373 // Expr=ImpCast(
2374 // decltype(2),
2375 // SubstNTTPE(Param=U, Expr='a',
2376 // Type=char)),
2377 // Type=decltype(2)))
2378 // The call to CheckTemplateArgument here produces the ImpCast.
2379 TemplateArgument SugaredConverted, CanonicalConverted;
2380 if (SemaRef
2382 E->getParameter(), SubstType, SubstReplacement.get(),
2383 SugaredConverted, CanonicalConverted,
2384 /*PartialOrderingTTP=*/false, Sema::CTAK_Specified)
2385 .isInvalid())
2386 return true;
2387 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2388 E->getParameter(), E->getExprLoc(),
2389 SugaredConverted, E->getPackIndex());
2390}
2391
2392ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2394 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2395 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2396}
2397
2399TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2400 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2401 // We can expand this parameter pack now.
2402 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
2403 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2404 if (!VD)
2405 return ExprError();
2406 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2407 }
2408
2409 QualType T = TransformType(E->getType());
2410 if (T.isNull())
2411 return ExprError();
2412
2413 // Transform each of the parameter expansions into the corresponding
2414 // parameters in the instantiation of the function decl.
2416 Vars.reserve(E->getNumExpansions());
2417 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2418 I != End; ++I) {
2419 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2420 if (!D)
2421 return ExprError();
2422 Vars.push_back(D);
2423 }
2424
2425 auto *PackExpr =
2426 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
2427 E->getParameterPackLocation(), Vars);
2428 getSema().MarkFunctionParmPackReferenced(PackExpr);
2429 return PackExpr;
2430}
2431
2433TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2434 VarDecl *PD) {
2435 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2436 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2437 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2438 assert(Found && "no instantiation for parameter pack");
2439
2440 Decl *TransformedDecl;
2441 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2442 // If this is a reference to a function parameter pack which we can
2443 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2444 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2445 QualType T = TransformType(E->getType());
2446 if (T.isNull())
2447 return ExprError();
2448 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2449 E->getExprLoc(), *Pack);
2450 getSema().MarkFunctionParmPackReferenced(PackExpr);
2451 return PackExpr;
2452 }
2453
2454 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2455 } else {
2456 TransformedDecl = cast<Decl *>(*Found);
2457 }
2458
2459 // We have either an unexpanded pack or a specific expansion.
2460 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2461}
2462
2464TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2465 NamedDecl *D = E->getDecl();
2466
2467 // Handle references to non-type template parameters and non-type template
2468 // parameter packs.
2469 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2470 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2471 return TransformTemplateParmRefExpr(E, NTTP);
2472
2473 // We have a non-type template parameter that isn't fully substituted;
2474 // FindInstantiatedDecl will find it in the local instantiation scope.
2475 }
2476
2477 // Handle references to function parameter packs.
2478 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2479 if (PD->isParameterPack())
2480 return TransformFunctionParmPackRefExpr(E, PD);
2481
2482 if (BindingDecl *BD = dyn_cast<BindingDecl>(D); BD && BD->isParameterPack()) {
2483 BD = cast_or_null<BindingDecl>(TransformDecl(BD->getLocation(), BD));
2484 if (!BD)
2485 return ExprError();
2486 if (auto *RP =
2487 dyn_cast_if_present<ResolvedUnexpandedPackExpr>(BD->getBinding()))
2488 return TransformResolvedUnexpandedPackExpr(RP);
2489 }
2490
2491 return inherited::TransformDeclRefExpr(E);
2492}
2493
2494ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2496 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2497 getDescribedFunctionTemplate() &&
2498 "Default arg expressions are never formed in dependent cases.");
2500 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2501 E->getParam());
2502}
2503
2504template<typename Fn>
2505QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2507 CXXRecordDecl *ThisContext,
2508 Qualifiers ThisTypeQuals,
2509 Fn TransformExceptionSpec) {
2510 // If this is a lambda or block, the transformation MUST be done in the
2511 // CurrentInstantiationScope since it introduces a mapping of
2512 // the original to the newly created transformed parameters.
2513 //
2514 // In that case, TemplateInstantiator::TransformLambdaExpr will
2515 // have already pushed a scope for this prototype, so don't create
2516 // a second one.
2517 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2518 std::optional<LocalInstantiationScope> Scope;
2519 if (!Current || !Current->isLambdaOrBlock())
2520 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2521
2522 return inherited::TransformFunctionProtoType(
2523 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2524}
2525
2526ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2527 ParmVarDecl *OldParm, int indexAdjustment,
2528 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2529 auto NewParm = SemaRef.SubstParmVarDecl(
2530 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2531 ExpectParameterPack, EvaluateConstraints);
2532 if (NewParm && SemaRef.getLangOpts().OpenCL)
2534 return NewParm;
2535}
2536
2537QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2538 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2539 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2540 TemplateArgument Arg, SourceLocation NameLoc) {
2541 QualType Replacement = Arg.getAsType();
2542
2543 // If the template parameter had ObjC lifetime qualifiers,
2544 // then any such qualifiers on the replacement type are ignored.
2545 if (SuppressObjCLifetime) {
2546 Qualifiers RQs;
2547 RQs = Replacement.getQualifiers();
2548 RQs.removeObjCLifetime();
2549 Replacement =
2550 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2551 }
2552
2553 if (Final) {
2554 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2555 return Replacement;
2556 }
2557 // TODO: only do this uniquing once, at the start of instantiation.
2558 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2559 Replacement, AssociatedDecl, Index, PackIndex);
2562 NewTL.setNameLoc(NameLoc);
2563 return Result;
2564}
2565
2567TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2569 bool SuppressObjCLifetime) {
2570 const TemplateTypeParmType *T = TL.getTypePtr();
2571 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2572 // Replace the template type parameter with its corresponding
2573 // template argument.
2574
2575 // If the corresponding template argument is NULL or doesn't exist, it's
2576 // because we are performing instantiation from explicitly-specified
2577 // template arguments in a function template class, but there were some
2578 // arguments left unspecified.
2579 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2580 IsIncomplete = true;
2581 if (BailOutOnIncomplete)
2582 return QualType();
2583
2586 NewTL.setNameLoc(TL.getNameLoc());
2587 return TL.getType();
2588 }
2589
2590 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2591
2592 if (TemplateArgs.isRewrite()) {
2593 // We're rewriting the template parameter as a reference to another
2594 // template parameter.
2595 if (Arg.getKind() == TemplateArgument::Pack) {
2596 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2597 "unexpected pack arguments in template rewrite");
2598 Arg = Arg.pack_begin()->getPackExpansionPattern();
2599 }
2600 assert(Arg.getKind() == TemplateArgument::Type &&
2601 "unexpected nontype template argument kind in template rewrite");
2602 QualType NewT = Arg.getAsType();
2603 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2604 return NewT;
2605 }
2606
2607 auto [AssociatedDecl, Final] =
2608 TemplateArgs.getAssociatedDecl(T->getDepth());
2609 std::optional<unsigned> PackIndex;
2610 if (T->isParameterPack()) {
2611 assert(Arg.getKind() == TemplateArgument::Pack &&
2612 "Missing argument pack");
2613
2614 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2615 // We have the template argument pack, but we're not expanding the
2616 // enclosing pack expansion yet. Just save the template argument
2617 // pack for later substitution.
2618 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2619 AssociatedDecl, T->getIndex(), Final, Arg);
2622 NewTL.setNameLoc(TL.getNameLoc());
2623 return Result;
2624 }
2625
2626 // PackIndex starts from last element.
2627 PackIndex = getPackIndex(Arg);
2628 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2629 }
2630
2631 assert(Arg.getKind() == TemplateArgument::Type &&
2632 "Template argument kind mismatch");
2633
2634 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2635 AssociatedDecl, T->getIndex(),
2636 PackIndex, Arg, TL.getNameLoc());
2637 }
2638
2639 // The template type parameter comes from an inner template (e.g.,
2640 // the template parameter list of a member template inside the
2641 // template we are instantiating). Create a new template type
2642 // parameter with the template "level" reduced by one.
2643 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2644 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2645 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2646 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2647 QualType Result = getSema().Context.getTemplateTypeParmType(
2648 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2649 T->isParameterPack(), NewTTPDecl);
2651 NewTL.setNameLoc(TL.getNameLoc());
2652 return Result;
2653}
2654
2655ExprResult TemplateInstantiator::TransformResolvedUnexpandedPackExpr(
2657 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2658 assert(static_cast<unsigned>(getSema().ArgumentPackSubstitutionIndex) <
2659 E->getNumExprs() &&
2660 "ArgumentPackSubstitutionIndex is out of range");
2661 return TransformExpr(
2662 E->getExpansion(getSema().ArgumentPackSubstitutionIndex));
2663 }
2664
2665 return inherited::TransformResolvedUnexpandedPackExpr(E);
2666}
2667
2668QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2670 bool SuppressObjCLifetime) {
2672
2673 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2674
2675 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2676 // We aren't expanding the parameter pack, so just return ourselves.
2677 QualType Result = TL.getType();
2678 if (NewReplaced != T->getAssociatedDecl())
2679 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2680 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2683 NewTL.setNameLoc(TL.getNameLoc());
2684 return Result;
2685 }
2686
2687 TemplateArgument Pack = T->getArgumentPack();
2689 return BuildSubstTemplateTypeParmType(
2690 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2691 getPackIndex(Pack), Arg, TL.getNameLoc());
2692}
2693
2696 Sema::EntityPrinter Printer) {
2697 SmallString<128> Message;
2698 SourceLocation ErrorLoc;
2699 if (Info.hasSFINAEDiagnostic()) {
2702 Info.takeSFINAEDiagnostic(PDA);
2703 PDA.second.EmitToString(S.getDiagnostics(), Message);
2704 ErrorLoc = PDA.first;
2705 } else {
2706 ErrorLoc = Info.getLocation();
2707 }
2708 SmallString<128> Entity;
2709 llvm::raw_svector_ostream OS(Entity);
2710 Printer(OS);
2711 const ASTContext &C = S.Context;
2713 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2714}
2715
2718 SmallString<128> Entity;
2719 llvm::raw_svector_ostream OS(Entity);
2720 Printer(OS);
2721 const ASTContext &C = Context;
2723 /*SubstitutedEntity=*/C.backupStr(Entity),
2724 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2725}
2726
2727ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2728 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2731 SmallVectorImpl<ParmVarDecl *> &TransParams,
2733
2734 TemplateDeductionInfo Info(KWLoc);
2735 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2736 RE, Info,
2737 SourceRange{KWLoc, RBraceLoc});
2739
2740 unsigned ErrorIdx;
2741 if (getDerived().TransformFunctionTypeParams(
2742 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2743 &TransParams, PInfos, &ErrorIdx) ||
2744 Trap.hasErrorOccurred()) {
2746 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2747 // Add a 'failed' Requirement to contain the error that caused the failure
2748 // here.
2749 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2750 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2751 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2752 TransParams, RE->getRParenLoc(),
2753 TransReqs, RBraceLoc);
2754 }
2755
2756 return ExprResult{};
2757}
2758
2760TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2761 if (!Req->isDependent() && !AlwaysRebuild())
2762 return Req;
2763 if (Req->isSubstitutionFailure()) {
2764 if (AlwaysRebuild())
2765 return RebuildTypeRequirement(
2767 return Req;
2768 }
2769
2773 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2774 Req->getType()->getTypeLoc().getSourceRange());
2775 if (TypeInst.isInvalid())
2776 return nullptr;
2777 TypeSourceInfo *TransType = TransformType(Req->getType());
2778 if (!TransType || Trap.hasErrorOccurred())
2779 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2780 [&] (llvm::raw_ostream& OS) {
2781 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2782 }));
2783 return RebuildTypeRequirement(TransType);
2784}
2785
2787TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2788 if (!Req->isDependent() && !AlwaysRebuild())
2789 return Req;
2790
2792
2793 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2794 TransExpr;
2795 if (Req->isExprSubstitutionFailure())
2796 TransExpr = Req->getExprSubstitutionDiagnostic();
2797 else {
2798 Expr *E = Req->getExpr();
2800 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2801 E->getSourceRange());
2802 if (ExprInst.isInvalid())
2803 return nullptr;
2804 ExprResult TransExprRes = TransformExpr(E);
2805 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2806 TransExprRes.get()->hasPlaceholderType())
2807 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2808 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2809 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2811 });
2812 else
2813 TransExpr = TransExprRes.get();
2814 }
2815
2816 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2817 const auto &RetReq = Req->getReturnTypeRequirement();
2818 if (RetReq.isEmpty())
2819 TransRetReq.emplace();
2820 else if (RetReq.isSubstitutionFailure())
2821 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2822 else if (RetReq.isTypeConstraint()) {
2823 TemplateParameterList *OrigTPL =
2824 RetReq.getTypeConstraintTemplateParameterList();
2825 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2827 Req, Info, OrigTPL->getSourceRange());
2828 if (TPLInst.isInvalid())
2829 return nullptr;
2830 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2831 if (!TPL || Trap.hasErrorOccurred())
2832 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2833 [&] (llvm::raw_ostream& OS) {
2834 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2835 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2836 }));
2837 else {
2838 TPLInst.Clear();
2839 TransRetReq.emplace(TPL);
2840 }
2841 }
2842 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2843 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2844 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2845 std::move(*TransRetReq));
2846 return RebuildExprRequirement(
2847 cast<concepts::Requirement::SubstitutionDiagnostic *>(TransExpr),
2848 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2849}
2850
2852TemplateInstantiator::TransformNestedRequirement(
2854 if (!Req->isDependent() && !AlwaysRebuild())
2855 return Req;
2856 if (Req->hasInvalidConstraint()) {
2857 if (AlwaysRebuild())
2858 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2860 return Req;
2861 }
2863 Req->getConstraintExpr()->getBeginLoc(), Req,
2866 if (!getEvaluateConstraints()) {
2867 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2868 if (TransConstraint.isInvalid() || !TransConstraint.get())
2869 return nullptr;
2870 if (TransConstraint.get()->isInstantiationDependent())
2871 return new (SemaRef.Context)
2872 concepts::NestedRequirement(TransConstraint.get());
2873 ConstraintSatisfaction Satisfaction;
2875 SemaRef.Context, TransConstraint.get(), Satisfaction);
2876 }
2877
2878 ExprResult TransConstraint;
2879 ConstraintSatisfaction Satisfaction;
2881 {
2886 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2888 if (ConstrInst.isInvalid())
2889 return nullptr;
2892 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2893 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2894 !Result.empty())
2895 TransConstraint = Result[0];
2896 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2897 "by CheckConstraintSatisfaction.");
2898 }
2900 if (TransConstraint.isUsable() &&
2901 TransConstraint.get()->isInstantiationDependent())
2902 return new (C) concepts::NestedRequirement(TransConstraint.get());
2903 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2904 Satisfaction.HasSubstitutionFailure()) {
2905 SmallString<128> Entity;
2906 llvm::raw_svector_ostream OS(Entity);
2907 Req->getConstraintExpr()->printPretty(OS, nullptr,
2909 return new (C) concepts::NestedRequirement(
2910 SemaRef.Context, C.backupStr(Entity), Satisfaction);
2911 }
2912 return new (C)
2913 concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction);
2914}
2915
2919 DeclarationName Entity,
2920 bool AllowDeducedTST) {
2921 assert(!CodeSynthesisContexts.empty() &&
2922 "Cannot perform an instantiation without some context on the "
2923 "instantiation stack");
2924
2925 if (!T->getType()->isInstantiationDependentType() &&
2926 !T->getType()->isVariablyModifiedType())
2927 return T;
2928
2929 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2930 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2931 : Instantiator.TransformType(T);
2932}
2933
2937 DeclarationName Entity) {
2938 assert(!CodeSynthesisContexts.empty() &&
2939 "Cannot perform an instantiation without some context on the "
2940 "instantiation stack");
2941
2942 if (TL.getType().isNull())
2943 return nullptr;
2944
2947 // FIXME: Make a copy of the TypeLoc data here, so that we can
2948 // return a new TypeSourceInfo. Inefficient!
2949 TypeLocBuilder TLB;
2950 TLB.pushFullCopy(TL);
2951 return TLB.getTypeSourceInfo(Context, TL.getType());
2952 }
2953
2954 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2955 TypeLocBuilder TLB;
2956 TLB.reserve(TL.getFullDataSize());
2957 QualType Result = Instantiator.TransformType(TLB, TL);
2958 if (Result.isNull())
2959 return nullptr;
2960
2961 return TLB.getTypeSourceInfo(Context, Result);
2962}
2963
2964/// Deprecated form of the above.
2966 const MultiLevelTemplateArgumentList &TemplateArgs,
2968 bool *IsIncompleteSubstitution) {
2969 assert(!CodeSynthesisContexts.empty() &&
2970 "Cannot perform an instantiation without some context on the "
2971 "instantiation stack");
2972
2973 // If T is not a dependent type or a variably-modified type, there
2974 // is nothing to do.
2976 return T;
2977
2978 TemplateInstantiator Instantiator(
2979 *this, TemplateArgs, Loc, Entity,
2980 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2981 QualType QT = Instantiator.TransformType(T);
2982 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2983 *IsIncompleteSubstitution = true;
2984 return QT;
2985}
2986
2988 if (T->getType()->isInstantiationDependentType() ||
2989 T->getType()->isVariablyModifiedType())
2990 return true;
2991
2992 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2993 if (!TL.getAs<FunctionProtoTypeLoc>())
2994 return false;
2995
2997 for (ParmVarDecl *P : FP.getParams()) {
2998 // This must be synthesized from a typedef.
2999 if (!P) continue;
3000
3001 // If there are any parameters, a new TypeSourceInfo that refers to the
3002 // instantiated parameters must be built.
3003 return true;
3004 }
3005
3006 return false;
3007}
3008
3012 DeclarationName Entity,
3013 CXXRecordDecl *ThisContext,
3014 Qualifiers ThisTypeQuals,
3015 bool EvaluateConstraints) {
3016 assert(!CodeSynthesisContexts.empty() &&
3017 "Cannot perform an instantiation without some context on the "
3018 "instantiation stack");
3019
3021 return T;
3022
3023 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3024 Instantiator.setEvaluateConstraints(EvaluateConstraints);
3025
3026 TypeLocBuilder TLB;
3027
3028 TypeLoc TL = T->getTypeLoc();
3029 TLB.reserve(TL.getFullDataSize());
3030
3032
3033 if (FunctionProtoTypeLoc Proto =
3035 // Instantiate the type, other than its exception specification. The
3036 // exception specification is instantiated in InitFunctionInstantiation
3037 // once we've built the FunctionDecl.
3038 // FIXME: Set the exception specification to EST_Uninstantiated here,
3039 // instead of rebuilding the function type again later.
3040 Result = Instantiator.TransformFunctionProtoType(
3041 TLB, Proto, ThisContext, ThisTypeQuals,
3043 bool &Changed) { return false; });
3044 } else {
3045 Result = Instantiator.TransformType(TLB, TL);
3046 }
3047 // When there are errors resolving types, clang may use IntTy as a fallback,
3048 // breaking our assumption that function declarations have function types.
3049 if (Result.isNull() || !Result->isFunctionType())
3050 return nullptr;
3051
3052 return TLB.getTypeSourceInfo(Context, Result);
3053}
3054
3057 SmallVectorImpl<QualType> &ExceptionStorage,
3058 const MultiLevelTemplateArgumentList &Args) {
3059 bool Changed = false;
3060 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3061 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3062 Changed);
3063}
3064
3066 const MultiLevelTemplateArgumentList &Args) {
3069
3070 SmallVector<QualType, 4> ExceptionStorage;
3072 ESI, ExceptionStorage, Args))
3073 // On error, recover by dropping the exception specification.
3074 ESI.Type = EST_None;
3075
3076 UpdateExceptionSpec(New, ESI);
3077}
3078
3079namespace {
3080
3081 struct GetContainedInventedTypeParmVisitor :
3082 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3083 TemplateTypeParmDecl *> {
3084 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3085 TemplateTypeParmDecl *>::Visit;
3086
3088 if (T.isNull())
3089 return nullptr;
3090 return Visit(T.getTypePtr());
3091 }
3092 // The deduced type itself.
3093 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3094 const TemplateTypeParmType *T) {
3095 if (!T->getDecl() || !T->getDecl()->isImplicit())
3096 return nullptr;
3097 return T->getDecl();
3098 }
3099
3100 // Only these types can contain 'auto' types, and subsequently be replaced
3101 // by references to invented parameters.
3102
3103 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
3104 return Visit(T->getNamedType());
3105 }
3106
3107 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3108 return Visit(T->getPointeeType());
3109 }
3110
3111 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3112 return Visit(T->getPointeeType());
3113 }
3114
3115 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3116 return Visit(T->getPointeeTypeAsWritten());
3117 }
3118
3119 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3120 return Visit(T->getPointeeType());
3121 }
3122
3123 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3124 return Visit(T->getElementType());
3125 }
3126
3127 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3129 return Visit(T->getElementType());
3130 }
3131
3132 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3133 return Visit(T->getElementType());
3134 }
3135
3136 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3137 return VisitFunctionType(T);
3138 }
3139
3140 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3141 return Visit(T->getReturnType());
3142 }
3143
3144 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3145 return Visit(T->getInnerType());
3146 }
3147
3148 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3149 return Visit(T->getModifiedType());
3150 }
3151
3152 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3153 return Visit(T->getUnderlyingType());
3154 }
3155
3156 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3157 return Visit(T->getOriginalType());
3158 }
3159
3160 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3161 return Visit(T->getPattern());
3162 }
3163 };
3164
3165} // namespace
3166
3167namespace {
3168
3169struct ExpandPackedTypeConstraints
3170 : TreeTransform<ExpandPackedTypeConstraints> {
3171
3173
3174 const MultiLevelTemplateArgumentList &TemplateArgs;
3175
3176 ExpandPackedTypeConstraints(
3177 Sema &SemaRef, const MultiLevelTemplateArgumentList &TemplateArgs)
3178 : inherited(SemaRef), TemplateArgs(TemplateArgs) {}
3179
3180 using inherited::TransformTemplateTypeParmType;
3181
3182 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
3183 TemplateTypeParmTypeLoc TL, bool) {
3184 const TemplateTypeParmType *T = TL.getTypePtr();
3185 if (!T->isParameterPack()) {
3188 NewTL.setNameLoc(TL.getNameLoc());
3189 return TL.getType();
3190 }
3191
3192 assert(SemaRef.ArgumentPackSubstitutionIndex != -1);
3193
3194 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
3195
3196 std::optional<unsigned> PackIndex;
3197 if (Arg.getKind() == TemplateArgument::Pack)
3198 PackIndex = Arg.pack_size() - 1 - SemaRef.ArgumentPackSubstitutionIndex;
3199
3201 TL.getType(), T->getDecl(), T->getIndex(), PackIndex,
3202 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace);
3205 NewTL.setNameLoc(TL.getNameLoc());
3206 return Result;
3207 }
3208
3209 QualType TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
3212 if (T->getPackIndex()) {
3215 TypeLoc.setNameLoc(TL.getNameLoc());
3216 return TypeLoc.getType();
3217 }
3218 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
3219 }
3220
3221 bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3223 return inherited::TransformTemplateArguments(Args.begin(), Args.end(), Out);
3224 }
3225};
3226
3227} // namespace
3228
3230 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3231 const MultiLevelTemplateArgumentList &TemplateArgs,
3232 bool EvaluateConstraints) {
3233 const ASTTemplateArgumentListInfo *TemplArgInfo =
3235
3236 if (!EvaluateConstraints) {
3237 bool ShouldExpandExplicitTemplateArgs =
3238 TemplArgInfo && ArgumentPackSubstitutionIndex != -1 &&
3239 llvm::any_of(TemplArgInfo->arguments(), [](auto &Arg) {
3240 return Arg.getArgument().containsUnexpandedParameterPack();
3241 });
3242
3243 // We want to transform the packs into Subst* nodes for type constraints
3244 // inside a pack expansion. For example,
3245 //
3246 // template <class... Ts> void foo() {
3247 // bar([](C<Ts> auto value) {}...);
3248 // }
3249 //
3250 // As we expand Ts in the process of instantiating foo(), and retain
3251 // the original template depths of Ts until the constraint evaluation, we
3252 // would otherwise have no chance to expand Ts by the time of evaluating
3253 // C<auto, Ts>.
3254 //
3255 // So we form a Subst* node for Ts along with a proper substitution index
3256 // here, and substitute the node with a complete MLTAL later in evaluation.
3257 if (ShouldExpandExplicitTemplateArgs) {
3258 TemplateArgumentListInfo InstArgs;
3259 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3260 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3261 if (ExpandPackedTypeConstraints(*this, TemplateArgs)
3262 .SubstTemplateArguments(TemplArgInfo->arguments(), InstArgs))
3263 return true;
3264
3265 // The type of the original parameter.
3266 auto *ConstraintExpr = TC->getImmediatelyDeclaredConstraint();
3267 QualType ConstrainedType;
3268
3269 if (auto *FE = dyn_cast<CXXFoldExpr>(ConstraintExpr)) {
3270 assert(FE->getLHS());
3271 ConstraintExpr = FE->getLHS();
3272 }
3273 auto *CSE = cast<ConceptSpecializationExpr>(ConstraintExpr);
3274 assert(!CSE->getTemplateArguments().empty() &&
3275 "Empty template arguments?");
3276 ConstrainedType = CSE->getTemplateArguments()[0].getAsType();
3277 assert(!ConstrainedType.isNull() &&
3278 "Failed to extract the original ConstrainedType?");
3279
3280 return AttachTypeConstraint(
3282 TC->getNamedConcept(),
3283 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs,
3284 Inst, ConstrainedType,
3285 Inst->isParameterPack()
3286 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3287 ->getEllipsisLoc()
3288 : SourceLocation());
3289 }
3292 return false;
3293 }
3294
3295 TemplateArgumentListInfo InstArgs;
3296
3297 if (TemplArgInfo) {
3298 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3299 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3300 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3301 InstArgs))
3302 return true;
3303 }
3304 return AttachTypeConstraint(
3306 TC->getNamedConcept(),
3307 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3309 Inst->isParameterPack()
3310 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3311 ->getEllipsisLoc()
3312 : SourceLocation());
3313}
3314
3316 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3317 int indexAdjustment, std::optional<unsigned> NumExpansions,
3318 bool ExpectParameterPack, bool EvaluateConstraint) {
3319 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3320 TypeSourceInfo *NewDI = nullptr;
3321
3322 TypeLoc OldTL = OldDI->getTypeLoc();
3323 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3324
3325 // We have a function parameter pack. Substitute into the pattern of the
3326 // expansion.
3327 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3328 OldParm->getLocation(), OldParm->getDeclName());
3329 if (!NewDI)
3330 return nullptr;
3331
3332 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3333 // We still have unexpanded parameter packs, which means that
3334 // our function parameter is still a function parameter pack.
3335 // Therefore, make its type a pack expansion type.
3336 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3337 NumExpansions);
3338 } else if (ExpectParameterPack) {
3339 // We expected to get a parameter pack but didn't (because the type
3340 // itself is not a pack expansion type), so complain. This can occur when
3341 // the substitution goes through an alias template that "loses" the
3342 // pack expansion.
3343 Diag(OldParm->getLocation(),
3344 diag::err_function_parameter_pack_without_parameter_packs)
3345 << NewDI->getType();
3346 return nullptr;
3347 }
3348 } else {
3349 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3350 OldParm->getDeclName());
3351 }
3352
3353 if (!NewDI)
3354 return nullptr;
3355
3356 if (NewDI->getType()->isVoidType()) {
3357 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3358 return nullptr;
3359 }
3360
3361 // In abbreviated templates, TemplateTypeParmDecls with possible
3362 // TypeConstraints are created when the parameter list is originally parsed.
3363 // The TypeConstraints can therefore reference other functions parameters in
3364 // the abbreviated function template, which is why we must instantiate them
3365 // here, when the instantiated versions of those referenced parameters are in
3366 // scope.
3367 if (TemplateTypeParmDecl *TTP =
3368 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3369 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3370 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3371 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3372 // We will first get here when instantiating the abbreviated function
3373 // template's described function, but we might also get here later.
3374 // Make sure we do not instantiate the TypeConstraint more than once.
3375 if (Inst && !Inst->getTypeConstraint()) {
3376 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3377 return nullptr;
3378 }
3379 }
3380 }
3381
3383 OldParm->getInnerLocStart(),
3384 OldParm->getLocation(),
3385 OldParm->getIdentifier(),
3386 NewDI->getType(), NewDI,
3387 OldParm->getStorageClass());
3388 if (!NewParm)
3389 return nullptr;
3390
3391 // Mark the (new) default argument as uninstantiated (if any).
3392 if (OldParm->hasUninstantiatedDefaultArg()) {
3393 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3394 NewParm->setUninstantiatedDefaultArg(Arg);
3395 } else if (OldParm->hasUnparsedDefaultArg()) {
3396 NewParm->setUnparsedDefaultArg();
3397 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3398 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3399 // Default arguments cannot be substituted until the declaration context
3400 // for the associated function or lambda capture class is available.
3401 // This is necessary for cases like the following where construction of
3402 // the lambda capture class for the outer lambda is dependent on the
3403 // parameter types but where the default argument is dependent on the
3404 // outer lambda's declaration context.
3405 // template <typename T>
3406 // auto f() {
3407 // return [](T = []{ return T{}; }()) { return 0; };
3408 // }
3409 NewParm->setUninstantiatedDefaultArg(Arg);
3410 }
3411
3415
3416 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3417 // Add the new parameter to the instantiated parameter pack.
3419 } else {
3420 // Introduce an Old -> New mapping
3422 }
3423
3424 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3425 // can be anything, is this right ?
3426 NewParm->setDeclContext(CurContext);
3427
3428 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3429 OldParm->getFunctionScopeIndex() + indexAdjustment);
3430
3431 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3432
3433 return NewParm;
3434}
3435
3438 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3439 const MultiLevelTemplateArgumentList &TemplateArgs,
3440 SmallVectorImpl<QualType> &ParamTypes,
3442 ExtParameterInfoBuilder &ParamInfos) {
3443 assert(!CodeSynthesisContexts.empty() &&
3444 "Cannot perform an instantiation without some context on the "
3445 "instantiation stack");
3446
3447 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3448 DeclarationName());
3449 return Instantiator.TransformFunctionTypeParams(
3450 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3451}
3452
3455 ParmVarDecl *Param,
3456 const MultiLevelTemplateArgumentList &TemplateArgs,
3457 bool ForCallExpr) {
3458 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3459 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3460
3463
3464 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3465 if (Inst.isInvalid())
3466 return true;
3467 if (Inst.isAlreadyInstantiating()) {
3468 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3469 Param->setInvalidDecl();
3470 return true;
3471 }
3472
3474 {
3475 // C++ [dcl.fct.default]p5:
3476 // The names in the [default argument] expression are bound, and
3477 // the semantic constraints are checked, at the point where the
3478 // default argument expression appears.
3479 ContextRAII SavedContext(*this, FD);
3480 std::unique_ptr<LocalInstantiationScope> LIS;
3481
3482 if (ForCallExpr) {
3483 // When instantiating a default argument due to use in a call expression,
3484 // an instantiation scope that includes the parameters of the callee is
3485 // required to satisfy references from the default argument. For example:
3486 // template<typename T> void f(T a, int = decltype(a)());
3487 // void g() { f(0); }
3488 LIS = std::make_unique<LocalInstantiationScope>(*this);
3490 /*ForDefinition*/ false);
3491 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3492 return true;
3493 }
3494
3496 Result = SubstInitializer(PatternExpr, TemplateArgs,
3497 /*DirectInit*/ false);
3498 });
3499 }
3500 if (Result.isInvalid())
3501 return true;
3502
3503 if (ForCallExpr) {
3504 // Check the expression as an initializer for the parameter.
3505 InitializedEntity Entity
3508 Param->getLocation(),
3509 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3510 Expr *ResultE = Result.getAs<Expr>();
3511
3512 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3513 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3514 if (Result.isInvalid())
3515 return true;
3516
3517 Result =
3519 /*DiscardedValue*/ false);
3520 } else {
3521 // FIXME: Obtain the source location for the '=' token.
3522 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3523 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3524 }
3525 if (Result.isInvalid())
3526 return true;
3527
3528 // Remember the instantiated default argument.
3529 Param->setDefaultArg(Result.getAs<Expr>());
3530
3531 return false;
3532}
3533
3534bool
3536 CXXRecordDecl *Pattern,
3537 const MultiLevelTemplateArgumentList &TemplateArgs) {
3538 bool Invalid = false;
3539 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3540 for (const auto &Base : Pattern->bases()) {
3541 if (!Base.getType()->isDependentType()) {
3542 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3543 if (RD->isInvalidDecl())
3544 Instantiation->setInvalidDecl();
3545 }
3546 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3547 continue;
3548 }
3549
3550 SourceLocation EllipsisLoc;
3551 TypeSourceInfo *BaseTypeLoc;
3552 if (Base.isPackExpansion()) {
3553 // This is a pack expansion. See whether we should expand it now, or
3554 // wait until later.
3556 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3557 Unexpanded);
3558 bool ShouldExpand = false;
3559 bool RetainExpansion = false;
3560 std::optional<unsigned> NumExpansions;
3561 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3562 Base.getSourceRange(),
3563 Unexpanded,
3564 TemplateArgs, ShouldExpand,
3565 RetainExpansion,
3566 NumExpansions)) {
3567 Invalid = true;
3568 continue;
3569 }
3570
3571 // If we should expand this pack expansion now, do so.
3572 if (ShouldExpand) {
3573 for (unsigned I = 0; I != *NumExpansions; ++I) {
3574 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3575
3576 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3577 TemplateArgs,
3578 Base.getSourceRange().getBegin(),
3579 DeclarationName());
3580 if (!BaseTypeLoc) {
3581 Invalid = true;
3582 continue;
3583 }
3584
3585 if (CXXBaseSpecifier *InstantiatedBase
3586 = CheckBaseSpecifier(Instantiation,
3587 Base.getSourceRange(),
3588 Base.isVirtual(),
3589 Base.getAccessSpecifierAsWritten(),
3590 BaseTypeLoc,
3591 SourceLocation()))
3592 InstantiatedBases.push_back(InstantiatedBase);
3593 else
3594 Invalid = true;
3595 }
3596
3597 continue;
3598 }
3599
3600 // The resulting base specifier will (still) be a pack expansion.
3601 EllipsisLoc = Base.getEllipsisLoc();
3602 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3603 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3604 TemplateArgs,
3605 Base.getSourceRange().getBegin(),
3606 DeclarationName());
3607 } else {
3608 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3609 TemplateArgs,
3610 Base.getSourceRange().getBegin(),
3611 DeclarationName());
3612 }
3613
3614 if (!BaseTypeLoc) {
3615 Invalid = true;
3616 continue;
3617 }
3618
3619 if (CXXBaseSpecifier *InstantiatedBase
3620 = CheckBaseSpecifier(Instantiation,
3621 Base.getSourceRange(),
3622 Base.isVirtual(),
3623 Base.getAccessSpecifierAsWritten(),
3624 BaseTypeLoc,
3625 EllipsisLoc))
3626 InstantiatedBases.push_back(InstantiatedBase);
3627 else
3628 Invalid = true;
3629 }
3630
3631 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3632 Invalid = true;
3633
3634 return Invalid;
3635}
3636
3637// Defined via #include from SemaTemplateInstantiateDecl.cpp
3638namespace clang {
3639 namespace sema {
3641 const MultiLevelTemplateArgumentList &TemplateArgs);
3643 const Attr *At, ASTContext &C, Sema &S,
3644 const MultiLevelTemplateArgumentList &TemplateArgs);
3645 }
3646}
3647
3648bool
3650 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3651 const MultiLevelTemplateArgumentList &TemplateArgs,
3653 bool Complain) {
3654 CXXRecordDecl *PatternDef
3655 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3656 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3657 Instantiation->getInstantiatedFromMemberClass(),
3658 Pattern, PatternDef, TSK, Complain))
3659 return true;
3660
3661 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3662 llvm::TimeTraceMetadata M;
3663 llvm::raw_string_ostream OS(M.Detail);
3664 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3665 /*Qualified=*/true);
3666 if (llvm::isTimeTraceVerbose()) {
3667 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3668 M.File = SourceMgr.getFilename(Loc);
3670 }
3671 return M;
3672 });
3673
3674 Pattern = PatternDef;
3675
3676 // Record the point of instantiation.
3677 if (MemberSpecializationInfo *MSInfo
3678 = Instantiation->getMemberSpecializationInfo()) {
3679 MSInfo->setTemplateSpecializationKind(TSK);
3680 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3681 } else if (ClassTemplateSpecializationDecl *Spec
3682 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3683 Spec->setTemplateSpecializationKind(TSK);
3684 Spec->setPointOfInstantiation(PointOfInstantiation);
3685 }
3686
3687 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3688 if (Inst.isInvalid())
3689 return true;
3690 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3691 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3692 "instantiating class definition");
3693
3694 // Enter the scope of this instantiation. We don't use
3695 // PushDeclContext because we don't have a scope.
3696 ContextRAII SavedContext(*this, Instantiation);
3699
3700 // If this is an instantiation of a local class, merge this local
3701 // instantiation scope with the enclosing scope. Otherwise, every
3702 // instantiation of a class has its own local instantiation scope.
3703 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3704 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3705
3706 // Some class state isn't processed immediately but delayed till class
3707 // instantiation completes. We may not be ready to handle any delayed state
3708 // already on the stack as it might correspond to a different class, so save
3709 // it now and put it back later.
3710 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3711
3712 // Pull attributes from the pattern onto the instantiation.
3713 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3714
3715 // Start the definition of this instantiation.
3716 Instantiation->startDefinition();
3717
3718 // The instantiation is visible here, even if it was first declared in an
3719 // unimported module.
3720 Instantiation->setVisibleDespiteOwningModule();
3721
3722 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3723 Instantiation->setTagKind(Pattern->getTagKind());
3724
3725 // Do substitution on the base class specifiers.
3726 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3727 Instantiation->setInvalidDecl();
3728
3729 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3730 Instantiator.setEvaluateConstraints(false);
3731 SmallVector<Decl*, 4> Fields;
3732 // Delay instantiation of late parsed attributes.
3733 LateInstantiatedAttrVec LateAttrs;
3734 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3735
3736 bool MightHaveConstexprVirtualFunctions = false;
3737 for (auto *Member : Pattern->decls()) {
3738 // Don't instantiate members not belonging in this semantic context.
3739 // e.g. for:
3740 // @code
3741 // template <int i> class A {
3742 // class B *g;
3743 // };
3744 // @endcode
3745 // 'class B' has the template as lexical context but semantically it is
3746 // introduced in namespace scope.
3747 if (Member->getDeclContext() != Pattern)
3748 continue;
3749
3750 // BlockDecls can appear in a default-member-initializer. They must be the
3751 // child of a BlockExpr, so we only know how to instantiate them from there.
3752 // Similarly, lambda closure types are recreated when instantiating the
3753 // corresponding LambdaExpr.
3754 if (isa<BlockDecl>(Member) ||
3755 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3756 continue;
3757
3758 if (Member->isInvalidDecl()) {
3759 Instantiation->setInvalidDecl();
3760 continue;
3761 }
3762
3763 Decl *NewMember = Instantiator.Visit(Member);
3764 if (NewMember) {
3765 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3766 Fields.push_back(Field);
3767 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3768 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3769 // specialization causes the implicit instantiation of the definitions
3770 // of unscoped member enumerations.
3771 // Record a point of instantiation for this implicit instantiation.
3772 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3773 Enum->isCompleteDefinition()) {
3774 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3775 assert(MSInfo && "no spec info for member enum specialization");
3777 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3778 }
3779 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3780 if (SA->isFailed()) {
3781 // A static_assert failed. Bail out; instantiating this
3782 // class is probably not meaningful.
3783 Instantiation->setInvalidDecl();
3784 break;
3785 }
3786 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3787 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3788 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3789 MightHaveConstexprVirtualFunctions = true;
3790 }
3791
3792 if (NewMember->isInvalidDecl())
3793 Instantiation->setInvalidDecl();
3794 } else {
3795 // FIXME: Eventually, a NULL return will mean that one of the
3796 // instantiations was a semantic disaster, and we'll want to mark the
3797 // declaration invalid.
3798 // For now, we expect to skip some members that we can't yet handle.
3799 }
3800 }
3801
3802 // Finish checking fields.
3803 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3805 CheckCompletedCXXClass(nullptr, Instantiation);
3806
3807 // Default arguments are parsed, if not instantiated. We can go instantiate
3808 // default arg exprs for default constructors if necessary now. Unless we're
3809 // parsing a class, in which case wait until that's finished.
3810 if (ParsingClassDepth == 0)
3812
3813 // Instantiate late parsed attributes, and attach them to their decls.
3814 // See Sema::InstantiateAttrs
3815 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3816 E = LateAttrs.end(); I != E; ++I) {
3817 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3818 CurrentInstantiationScope = I->Scope;
3819
3820 // Allow 'this' within late-parsed attributes.
3821 auto *ND = cast<NamedDecl>(I->NewDecl);
3822 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3823 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3824 ND->isCXXInstanceMember());
3825
3826 Attr *NewAttr =
3827 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3828 if (NewAttr)
3829 I->NewDecl->addAttr(NewAttr);
3831 Instantiator.getStartingScope());
3832 }
3833 Instantiator.disableLateAttributeInstantiation();
3834 LateAttrs.clear();
3835
3837
3838 // FIXME: We should do something similar for explicit instantiations so they
3839 // end up in the right module.
3840 if (TSK == TSK_ImplicitInstantiation) {
3841 Instantiation->setLocation(Pattern->getLocation());
3842 Instantiation->setLocStart(Pattern->getInnerLocStart());
3843 Instantiation->setBraceRange(Pattern->getBraceRange());
3844 }
3845
3846 if (!Instantiation->isInvalidDecl()) {
3847 // Perform any dependent diagnostics from the pattern.
3848 if (Pattern->isDependentContext())
3849 PerformDependentDiagnostics(Pattern, TemplateArgs);
3850
3851 // Instantiate any out-of-line class template partial
3852 // specializations now.
3854 P = Instantiator.delayed_partial_spec_begin(),
3855 PEnd = Instantiator.delayed_partial_spec_end();
3856 P != PEnd; ++P) {
3858 P->first, P->second)) {
3859 Instantiation->setInvalidDecl();
3860 break;
3861 }
3862 }
3863
3864 // Instantiate any out-of-line variable template partial
3865 // specializations now.
3867 P = Instantiator.delayed_var_partial_spec_begin(),
3868 PEnd = Instantiator.delayed_var_partial_spec_end();
3869 P != PEnd; ++P) {
3871 P->first, P->second)) {
3872 Instantiation->setInvalidDecl();
3873 break;
3874 }
3875 }
3876 }
3877
3878 // Exit the scope of this instantiation.
3879 SavedContext.pop();
3880
3881 if (!Instantiation->isInvalidDecl()) {
3882 // Always emit the vtable for an explicit instantiation definition
3883 // of a polymorphic class template specialization. Otherwise, eagerly
3884 // instantiate only constexpr virtual functions in preparation for their use
3885 // in constant evaluation.
3887 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3888 else if (MightHaveConstexprVirtualFunctions)
3889 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3890 /*ConstexprOnly*/ true);
3891 }
3892
3893 Consumer.HandleTagDeclDefinition(Instantiation);
3894
3895 return Instantiation->isInvalidDecl();
3896}
3897
3898bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3899 EnumDecl *Instantiation, EnumDecl *Pattern,
3900 const MultiLevelTemplateArgumentList &TemplateArgs,
3902 EnumDecl *PatternDef = Pattern->getDefinition();
3903 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3904 Instantiation->getInstantiatedFromMemberEnum(),
3905 Pattern, PatternDef, TSK,/*Complain*/true))
3906 return true;
3907 Pattern = PatternDef;
3908
3909 // Record the point of instantiation.
3910 if (MemberSpecializationInfo *MSInfo
3911 = Instantiation->getMemberSpecializationInfo()) {
3912 MSInfo->setTemplateSpecializationKind(TSK);
3913 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3914 }
3915
3916 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3917 if (Inst.isInvalid())
3918 return true;
3919 if (Inst.isAlreadyInstantiating())
3920 return false;
3921 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3922 "instantiating enum definition");
3923
3924 // The instantiation is visible here, even if it was first declared in an
3925 // unimported module.
3926 Instantiation->setVisibleDespiteOwningModule();
3927
3928 // Enter the scope of this instantiation. We don't use
3929 // PushDeclContext because we don't have a scope.
3930 ContextRAII SavedContext(*this, Instantiation);
3933
3934 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3935
3936 // Pull attributes from the pattern onto the instantiation.
3937 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3938
3939 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3940 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3941
3942 // Exit the scope of this instantiation.
3943 SavedContext.pop();
3944
3945 return Instantiation->isInvalidDecl();
3946}
3947
3949 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3950 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3951 // If there is no initializer, we don't need to do anything.
3952 if (!Pattern->hasInClassInitializer())
3953 return false;
3954
3955 assert(Instantiation->getInClassInitStyle() ==
3956 Pattern->getInClassInitStyle() &&
3957 "pattern and instantiation disagree about init style");
3958
3959 // Error out if we haven't parsed the initializer of the pattern yet because
3960 // we are waiting for the closing brace of the outer class.
3961 Expr *OldInit = Pattern->getInClassInitializer();
3962 if (!OldInit) {
3963 RecordDecl *PatternRD = Pattern->getParent();
3964 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3965 Diag(PointOfInstantiation,
3966 diag::err_default_member_initializer_not_yet_parsed)
3967 << OutermostClass << Pattern;
3968 Diag(Pattern->getEndLoc(),
3969 diag::note_default_member_initializer_not_yet_parsed);
3970 Instantiation->setInvalidDecl();
3971 return true;
3972 }
3973
3974 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3975 if (Inst.isInvalid())
3976 return true;
3977 if (Inst.isAlreadyInstantiating()) {
3978 // Error out if we hit an instantiation cycle for this initializer.
3979 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3980 << Instantiation;
3981 return true;
3982 }
3983 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3984 "instantiating default member init");
3985
3986 // Enter the scope of this instantiation. We don't use PushDeclContext because
3987 // we don't have a scope.
3988 ContextRAII SavedContext(*this, Instantiation->getParent());
3991 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3992 PointOfInstantiation, Instantiation, CurContext};
3993
3994 LocalInstantiationScope Scope(*this, true);
3995
3996 // Instantiate the initializer.
3998 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3999
4000 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
4001 /*CXXDirectInit=*/false);
4002 Expr *Init = NewInit.get();
4003 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
4005 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
4006
4007 if (auto *L = getASTMutationListener())
4008 L->DefaultMemberInitializerInstantiated(Instantiation);
4009
4010 // Return true if the in-class initializer is still missing.
4011 return !Instantiation->getInClassInitializer();
4012}
4013
4014namespace {
4015 /// A partial specialization whose template arguments have matched
4016 /// a given template-id.
4017 struct PartialSpecMatchResult {
4020 };
4021}
4022
4025 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
4027 return true;
4028
4030 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
4031 CTD->getPartialSpecializations(PartialSpecs);
4032 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
4033 // C++ [temp.spec.partial.member]p2:
4034 // If the primary member template is explicitly specialized for a given
4035 // (implicit) specialization of the enclosing class template, the partial
4036 // specializations of the member template are ignored for this
4037 // specialization of the enclosing class template. If a partial
4038 // specialization of the member template is explicitly specialized for a
4039 // given (implicit) specialization of the enclosing class template, the
4040 // primary member template and its other partial specializations are still
4041 // considered for this specialization of the enclosing class template.
4043 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
4044 continue;
4045
4047 if (DeduceTemplateArguments(CTPSD,
4048 ClassTemplateSpec->getTemplateArgs().asArray(),
4050 return true;
4051 }
4052
4053 return false;
4054}
4055
4056/// Get the instantiation pattern to use to instantiate the definition of a
4057/// given ClassTemplateSpecializationDecl (either the pattern of the primary
4058/// template or of a partial specialization).
4060 Sema &S, SourceLocation PointOfInstantiation,
4061 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4063 bool PrimaryHasMatchedPackOnParmToNonPackOnArg) {
4064 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
4065 if (Inst.isInvalid())
4066 return {/*Invalid=*/true};
4067 if (Inst.isAlreadyInstantiating())
4068 return {/*Invalid=*/false};
4069
4070 llvm::PointerUnion<ClassTemplateDecl *,
4072 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4073 if (!isa<ClassTemplatePartialSpecializationDecl *>(Specialized)) {
4074 // Find best matching specialization.
4075 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4076
4077 // C++ [temp.class.spec.match]p1:
4078 // When a class template is used in a context that requires an
4079 // instantiation of the class, it is necessary to determine
4080 // whether the instantiation is to be generated using the primary
4081 // template or one of the partial specializations. This is done by
4082 // matching the template arguments of the class template
4083 // specialization with the template argument lists of the partial
4084 // specializations.
4085 typedef PartialSpecMatchResult MatchResult;
4086 SmallVector<MatchResult, 4> Matched, ExtraMatched;
4088 Template->getPartialSpecializations(PartialSpecs);
4089 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4090 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4091 // C++ [temp.spec.partial.member]p2:
4092 // If the primary member template is explicitly specialized for a given
4093 // (implicit) specialization of the enclosing class template, the
4094 // partial specializations of the member template are ignored for this
4095 // specialization of the enclosing class template. If a partial
4096 // specialization of the member template is explicitly specialized for a
4097 // given (implicit) specialization of the enclosing class template, the
4098 // primary member template and its other partial specializations are
4099 // still considered for this specialization of the enclosing class
4100 // template.
4101 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4102 !Partial->getMostRecentDecl()->isMemberSpecialization())
4103 continue;
4104
4105 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4107 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4109 // Store the failed-deduction information for use in diagnostics, later.
4110 // TODO: Actually use the failed-deduction info?
4111 FailedCandidates.addCandidate().set(
4112 DeclAccessPair::make(Template, AS_public), Partial,
4114 (void)Result;
4115 } else {
4116 auto &List =
4117 Info.hasMatchedPackOnParmToNonPackOnArg() ? ExtraMatched : Matched;
4118 List.push_back(MatchResult{Partial, Info.takeCanonical()});
4119 }
4120 }
4121 if (Matched.empty() && PrimaryHasMatchedPackOnParmToNonPackOnArg)
4122 Matched = std::move(ExtraMatched);
4123
4124 // If we're dealing with a member template where the template parameters
4125 // have been instantiated, this provides the original template parameters
4126 // from which the member template's parameters were instantiated.
4127
4128 if (Matched.size() >= 1) {
4129 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4130 if (Matched.size() == 1) {
4131 // -- If exactly one matching specialization is found, the
4132 // instantiation is generated from that specialization.
4133 // We don't need to do anything for this.
4134 } else {
4135 // -- If more than one matching specialization is found, the
4136 // partial order rules (14.5.4.2) are used to determine
4137 // whether one of the specializations is more specialized
4138 // than the others. If none of the specializations is more
4139 // specialized than all of the other matching
4140 // specializations, then the use of the class template is
4141 // ambiguous and the program is ill-formed.
4143 PEnd = Matched.end();
4144 P != PEnd; ++P) {
4146 P->Partial, Best->Partial, PointOfInstantiation) ==
4147 P->Partial)
4148 Best = P;
4149 }
4150
4151 // Determine if the best partial specialization is more specialized than
4152 // the others.
4153 bool Ambiguous = false;
4154 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4155 PEnd = Matched.end();
4156 P != PEnd; ++P) {
4158 P->Partial, Best->Partial,
4159 PointOfInstantiation) != Best->Partial) {
4160 Ambiguous = true;
4161 break;
4162 }
4163 }
4164
4165 if (Ambiguous) {
4166 // Partial ordering did not produce a clear winner. Complain.
4167 Inst.Clear();
4168 ClassTemplateSpec->setInvalidDecl();
4169 S.Diag(PointOfInstantiation,
4170 diag::err_partial_spec_ordering_ambiguous)
4171 << ClassTemplateSpec;
4172
4173 // Print the matching partial specializations.
4174 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4175 PEnd = Matched.end();
4176 P != PEnd; ++P)
4177 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4179 P->Partial->getTemplateParameters(), *P->Args);
4180
4181 return {/*Invalid=*/true};
4182 }
4183 }
4184
4185 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4186 } else {
4187 // -- If no matches are found, the instantiation is generated
4188 // from the primary template.
4189 }
4190 }
4191
4192 CXXRecordDecl *Pattern = nullptr;
4193 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4194 if (auto *PartialSpec =
4195 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4196 // Instantiate using the best class template partial specialization.
4197 while (PartialSpec->getInstantiatedFromMember()) {
4198 // If we've found an explicit specialization of this class template,
4199 // stop here and use that as the pattern.
4200 if (PartialSpec->isMemberSpecialization())
4201 break;
4202
4203 PartialSpec = PartialSpec->getInstantiatedFromMember();
4204 }
4205 Pattern = PartialSpec;
4206 } else {
4207 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4208 while (Template->getInstantiatedFromMemberTemplate()) {
4209 // If we've found an explicit specialization of this class template,
4210 // stop here and use that as the pattern.
4211 if (Template->isMemberSpecialization())
4212 break;
4213
4214 Template = Template->getInstantiatedFromMemberTemplate();
4215 }
4216 Pattern = Template->getTemplatedDecl();
4217 }
4218
4219 return Pattern;
4220}
4221
4223 SourceLocation PointOfInstantiation,
4224 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4225 TemplateSpecializationKind TSK, bool Complain,
4226 bool PrimaryHasMatchedPackOnParmToNonPackOnArg) {
4227 // Perform the actual instantiation on the canonical declaration.
4228 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4229 ClassTemplateSpec->getCanonicalDecl());
4230 if (ClassTemplateSpec->isInvalidDecl())
4231 return true;
4232
4235 *this, PointOfInstantiation, ClassTemplateSpec, TSK,
4236 PrimaryHasMatchedPackOnParmToNonPackOnArg);
4237 if (!Pattern.isUsable())
4238 return Pattern.isInvalid();
4239
4240 return InstantiateClass(
4241 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4242 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4243}
4244
4245void
4247 CXXRecordDecl *Instantiation,
4248 const MultiLevelTemplateArgumentList &TemplateArgs,
4250 // FIXME: We need to notify the ASTMutationListener that we did all of these
4251 // things, in case we have an explicit instantiation definition in a PCM, a
4252 // module, or preamble, and the declaration is in an imported AST.
4253 assert(
4256 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4257 "Unexpected template specialization kind!");
4258 for (auto *D : Instantiation->decls()) {
4259 bool SuppressNew = false;
4260 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4261 if (FunctionDecl *Pattern =
4262 Function->getInstantiatedFromMemberFunction()) {
4263
4264 if (Function->isIneligibleOrNotSelected())
4265 continue;
4266
4267 if (Function->getTrailingRequiresClause()) {
4268 ConstraintSatisfaction Satisfaction;
4269 if (CheckFunctionConstraints(Function, Satisfaction) ||
4270 !Satisfaction.IsSatisfied) {
4271 continue;
4272 }
4273 }
4274
4275 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4276 continue;
4277
4279 Function->getTemplateSpecializationKind();
4280 if (PrevTSK == TSK_ExplicitSpecialization)
4281 continue;
4282
4284 PointOfInstantiation, TSK, Function, PrevTSK,
4285 Function->getPointOfInstantiation(), SuppressNew) ||
4286 SuppressNew)
4287 continue;
4288
4289 // C++11 [temp.explicit]p8:
4290 // An explicit instantiation definition that names a class template
4291 // specialization explicitly instantiates the class template
4292 // specialization and is only an explicit instantiation definition
4293 // of members whose definition is visible at the point of
4294 // instantiation.
4295 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4296 continue;
4297
4298 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4299
4300 if (Function->isDefined()) {
4301 // Let the ASTConsumer know that this function has been explicitly
4302 // instantiated now, and its linkage might have changed.
4304 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4305 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4306 } else if (TSK == TSK_ImplicitInstantiation) {
4308 std::make_pair(Function, PointOfInstantiation));
4309 }
4310 }
4311 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4312 if (isa<VarTemplateSpecializationDecl>(Var))
4313 continue;
4314
4315 if (Var->isStaticDataMember()) {
4316 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4317 continue;
4318
4320 assert(MSInfo && "No member specialization information?");
4321 if (MSInfo->getTemplateSpecializationKind()
4323 continue;
4324
4325 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4326 Var,
4328 MSInfo->getPointOfInstantiation(),
4329 SuppressNew) ||
4330 SuppressNew)
4331 continue;
4332
4334 // C++0x [temp.explicit]p8:
4335 // An explicit instantiation definition that names a class template
4336 // specialization explicitly instantiates the class template
4337 // specialization and is only an explicit instantiation definition
4338 // of members whose definition is visible at the point of
4339 // instantiation.
4341 continue;
4342
4343 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4344 InstantiateVariableDefinition(PointOfInstantiation, Var);
4345 } else {
4346 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4347 }
4348 }
4349 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4350 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4351 continue;
4352
4353 // Always skip the injected-class-name, along with any
4354 // redeclarations of nested classes, since both would cause us
4355 // to try to instantiate the members of a class twice.
4356 // Skip closure types; they'll get instantiated when we instantiate
4357 // the corresponding lambda-expression.
4358 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4359 Record->isLambda())
4360 continue;
4361
4362 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4363 assert(MSInfo && "No member specialization information?");
4364
4365 if (MSInfo->getTemplateSpecializationKind()
4367 continue;
4368
4369 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4371 // On Windows, explicit instantiation decl of the outer class doesn't
4372 // affect the inner class. Typically extern template declarations are
4373 // used in combination with dll import/export annotations, but those
4374 // are not propagated from the outer class templates to inner classes.
4375 // Therefore, do not instantiate inner classes on this platform, so
4376 // that users don't end up with undefined symbols during linking.
4377 continue;
4378 }
4379
4380 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4381 Record,
4383 MSInfo->getPointOfInstantiation(),
4384 SuppressNew) ||
4385 SuppressNew)
4386 continue;
4387
4389 assert(Pattern && "Missing instantiated-from-template information");
4390
4391 if (!Record->getDefinition()) {
4392 if (!Pattern->getDefinition()) {
4393 // C++0x [temp.explicit]p8:
4394 // An explicit instantiation definition that names a class template
4395 // specialization explicitly instantiates the class template
4396 // specialization and is only an explicit instantiation definition
4397 // of members whose definition is visible at the point of
4398 // instantiation.
4400 MSInfo->setTemplateSpecializationKind(TSK);
4401 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4402 }
4403
4404 continue;
4405 }
4406
4407 InstantiateClass(PointOfInstantiation, Record, Pattern,
4408 TemplateArgs,
4409 TSK);
4410 } else {
4412 Record->getTemplateSpecializationKind() ==
4414 Record->setTemplateSpecializationKind(TSK);
4415 MarkVTableUsed(PointOfInstantiation, Record, true);
4416 }
4417 }
4418
4419 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4420 if (Pattern)
4421 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4422 TSK);
4423 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4424 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4425 assert(MSInfo && "No member specialization information?");
4426
4427 if (MSInfo->getTemplateSpecializationKind()
4429 continue;
4430
4432 PointOfInstantiation, TSK, Enum,
4434 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4435 SuppressNew)
4436 continue;
4437
4438 if (Enum->getDefinition())
4439 continue;
4440
4441 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4442 assert(Pattern && "Missing instantiated-from-template information");
4443
4445 if (!Pattern->getDefinition())
4446 continue;
4447
4448 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4449 } else {
4450 MSInfo->setTemplateSpecializationKind(TSK);
4451 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4452 }
4453 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4454 // No need to instantiate in-class initializers during explicit
4455 // instantiation.
4456 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4457 CXXRecordDecl *ClassPattern =
4458 Instantiation->getTemplateInstantiationPattern();
4460 ClassPattern->lookup(Field->getDeclName());
4461 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4462 assert(Pattern);
4463 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4464 TemplateArgs);
4465 }
4466 }
4467 }
4468}
4469
4470void
4472 SourceLocation PointOfInstantiation,
4473 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4475 // C++0x [temp.explicit]p7:
4476 // An explicit instantiation that names a class template
4477 // specialization is an explicit instantion of the same kind
4478 // (declaration or definition) of each of its members (not
4479 // including members inherited from base classes) that has not
4480 // been previously explicitly specialized in the translation unit
4481 // containing the explicit instantiation, except as described
4482 // below.
4483 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4484 getTemplateInstantiationArgs(ClassTemplateSpec),
4485 TSK);
4486}
4487
4490 if (!S)
4491 return S;
4492
4493 TemplateInstantiator Instantiator(*this, TemplateArgs,
4495 DeclarationName());
4496 return Instantiator.TransformStmt(S);
4497}
4498
4500 const TemplateArgumentLoc &Input,
4501 const MultiLevelTemplateArgumentList &TemplateArgs,
4503 const DeclarationName &Entity) {
4504 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4505 return Instantiator.TransformTemplateArgument(Input, Output);
4506}
4507
4510 const MultiLevelTemplateArgumentList &TemplateArgs,
4512 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4513 DeclarationName());
4514 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4515}
4516
4519 if (!E)
4520 return E;
4521
4522 TemplateInstantiator Instantiator(*this, TemplateArgs,
4524 DeclarationName());
4525 return Instantiator.TransformExpr(E);
4526}
4527
4530 const MultiLevelTemplateArgumentList &TemplateArgs) {
4531 // FIXME: should call SubstExpr directly if this function is equivalent or
4532 // should it be different?
4533 return SubstExpr(E, TemplateArgs);
4534}
4535
4537 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4538 if (!E)
4539 return E;
4540
4541 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4542 DeclarationName());
4543 Instantiator.setEvaluateConstraints(false);
4544 return Instantiator.TransformExpr(E);
4545}
4546
4548 const MultiLevelTemplateArgumentList &TemplateArgs,
4549 bool CXXDirectInit) {
4550 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4551 DeclarationName());
4552 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4553}
4554
4555bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4556 const MultiLevelTemplateArgumentList &TemplateArgs,
4557 SmallVectorImpl<Expr *> &Outputs) {
4558 if (Exprs.empty())
4559 return false;
4560
4561 TemplateInstantiator Instantiator(*this, TemplateArgs,
4563 DeclarationName());
4564 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4565 IsCall, Outputs);
4566}
4567
4570 const MultiLevelTemplateArgumentList &TemplateArgs) {
4571 if (!NNS)
4572 return NestedNameSpecifierLoc();
4573
4574 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4575 DeclarationName());
4576 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4577}
4578
4581 const MultiLevelTemplateArgumentList &TemplateArgs) {
4582 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4583 NameInfo.getName());
4584 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4585}
4586
4590 const MultiLevelTemplateArgumentList &TemplateArgs) {
4591 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4592 DeclarationName());
4593 CXXScopeSpec SS;
4594 SS.Adopt(QualifierLoc);
4595 return Instantiator.TransformTemplateName(SS, Name, Loc);
4596}
4597
4598static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4599 // When storing ParmVarDecls in the local instantiation scope, we always
4600 // want to use the ParmVarDecl from the canonical function declaration,
4601 // since the map is then valid for any redeclaration or definition of that
4602 // function.
4603 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4604 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4605 unsigned i = PV->getFunctionScopeIndex();
4606 // This parameter might be from a freestanding function type within the
4607 // function and isn't necessarily referring to one of FD's parameters.
4608 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4609 return FD->getCanonicalDecl()->getParamDecl(i);
4610 }
4611 }
4612 return D;
4613}
4614
4615
4616llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4619 for (LocalInstantiationScope *Current = this; Current;
4620 Current = Current->Outer) {
4621
4622 // Check if we found something within this scope.
4623 const Decl *CheckD = D;
4624 do {
4625 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4626 if (Found != Current->LocalDecls.end())
4627 return &Found->second;
4628
4629 // If this is a tag declaration, it's possible that we need to look for
4630 // a previous declaration.
4631 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4632 CheckD = Tag->getPreviousDecl();
4633 else
4634 CheckD = nullptr;
4635 } while (CheckD);
4636
4637 // If we aren't combined with our outer scope, we're done.
4638 if (!Current->CombineWithOuterScope)
4639 break;
4640 }
4641
4642 // If we're performing a partial substitution during template argument
4643 // deduction, we may not have values for template parameters yet.
4644 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4645 isa<TemplateTemplateParmDecl>(D))
4646 return nullptr;
4647
4648 // Local types referenced prior to definition may require instantiation.
4649 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4650 if (RD->isLocalClass())
4651 return nullptr;
4652
4653 // Enumeration types referenced prior to definition may appear as a result of
4654 // error recovery.
4655 if (isa<EnumDecl>(D))
4656 return nullptr;
4657
4658 // Materialized typedefs/type alias for implicit deduction guides may require
4659 // instantiation.
4660 if (isa<TypedefNameDecl>(D) &&
4661 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4662 return nullptr;
4663
4664 // If we didn't find the decl, then we either have a sema bug, or we have a
4665 // forward reference to a label declaration. Return null to indicate that
4666 // we have an uninstantiated label.
4667 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4668 return nullptr;
4669}
4670
4673 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4674 if (Stored.isNull()) {
4675#ifndef NDEBUG
4676 // It should not be present in any surrounding scope either.
4677 LocalInstantiationScope *Current = this;
4678 while (Current->CombineWithOuterScope && Current->Outer) {
4679 Current = Current->Outer;
4680 assert(!Current->LocalDecls.contains(D) &&
4681 "Instantiated local in inner and outer scopes");
4682 }
4683#endif
4684 Stored = Inst;
4685 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4686 Pack->push_back(cast<VarDecl>(Inst));
4687 } else {
4688 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4689 }
4690}
4691
4693 VarDecl *Inst) {
4695 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4696 Pack->push_back(Inst);
4697}
4698
4700#ifndef NDEBUG
4701 // This should be the first time we've been told about this decl.
4702 for (LocalInstantiationScope *Current = this;
4703 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4704 assert(!Current->LocalDecls.contains(D) &&
4705 "Creating local pack after instantiation of local");
4706#endif
4707
4709 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4711 Stored = Pack;
4712 ArgumentPacks.push_back(Pack);
4713}
4714
4716 for (DeclArgumentPack *Pack : ArgumentPacks)
4717 if (llvm::is_contained(*Pack, D))
4718 return true;
4719 return false;
4720}
4721
4723 const TemplateArgument *ExplicitArgs,
4724 unsigned NumExplicitArgs) {
4725 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4726 "Already have a partially-substituted pack");
4727 assert((!PartiallySubstitutedPack
4728 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4729 "Wrong number of arguments in partially-substituted pack");
4730 PartiallySubstitutedPack = Pack;
4731 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4732 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4733}
4734
4736 const TemplateArgument **ExplicitArgs,
4737 unsigned *NumExplicitArgs) const {
4738 if (ExplicitArgs)
4739 *ExplicitArgs = nullptr;
4740 if (NumExplicitArgs)
4741 *NumExplicitArgs = 0;
4742
4743 for (const LocalInstantiationScope *Current = this; Current;
4744 Current = Current->Outer) {
4745 if (Current->PartiallySubstitutedPack) {
4746 if (ExplicitArgs)
4747 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4748 if (NumExplicitArgs)
4749 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4750
4751 return Current->PartiallySubstitutedPack;
4752 }
4753
4754 if (!Current->CombineWithOuterScope)
4755 break;
4756 }
4757
4758 return nullptr;
4759}
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:1125
SourceLocation Loc
Definition: SemaObjC.cpp:759
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static ActionResult< CXXRecordDecl * > getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool PrimaryHasMatchedPackOnParmToNonPackOnArg)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, Sema::EntityPrinter Printer)
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:2739
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:2296
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:3358
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3578
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:6133
A binding in a decomposition declaration.
Definition: DeclCXX.h:4169
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3409
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:2117
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:1791
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:1982
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:2037
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:2012
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:2004
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1989
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1700
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:2023
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
Declaration of a class template.
ClassTemplateDecl * getMostRecentDecl()
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isClassScopeExplicitSpecialization() const
Is this an explicit specialization at class scope (within the class that owns the primary template)?...
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate members of the class templa...
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
NamedDecl * getFoundDecl() const
Definition: ASTConcept.h:195
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1375
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1442
bool isFileContext() const
Definition: DeclBase.h:2178
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1347
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1868
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2038
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2367
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:266
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1219
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:247
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
bool isFileContextDecl() const
Definition: DeclBase.cpp:435
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1047
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:301
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1228
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
void setLocation(SourceLocation L)
Definition: DeclBase.h:443
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:942
DeclContext * getDeclContext()
Definition: DeclBase.h:451
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:363
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:863
The name of a declaration.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:796
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:781
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2039
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:790
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:768
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1904
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3961
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1497
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:875
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:656
Recursive AST visitor that supports extension via dynamic dispatch.
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6949
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3861
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4120
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For an enumeration member that was instantiated from a member enumeration of a templated class,...
Definition: Decl.cpp:4952
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4978
EnumDecl * getDefinition() const
Definition: Decl.h:3964
This represents one expression.
Definition: Expr.h:110
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
ExprDependence getDependence() const
Definition: Expr.h:162
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4595
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3208
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3202
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:138
Represents a function declaration or definition.
Definition: Decl.h:1935
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4134
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4183
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2279
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4652
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4686
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl * > Params)
Definition: ExprCXX.cpp:1796
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5108
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5372
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1523
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4348
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4322
QualType getReturnType() const
Definition: Type.h:4649
One of these records is kept for each identifier that is lexed.
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:515
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
Describes the sequence of initializations required to initialize a given object or reference with a s...
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:706
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6799
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all outer scopes, down to the given outermost scope.
Definition: Template.h:505
void InstantiatedLocal(const Decl *D, Decl *Inst)
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5771
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3520
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:619
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:650
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:641
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:659
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:664
Describes a module or submodule.
Definition: Module.h:115
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
bool hasTemplateArgument(unsigned Depth, unsigned Index) const
Determine whether there is a non-NULL template argument at the given depth and index.
Definition: Template.h:175
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
std::pair< Decl *, bool > getAssociatedDecl(unsigned Depth) const
A template-like entity which owns the whole pattern being substituted.
Definition: Template.h:164
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:123
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
unsigned getNewDepth(unsigned OldDepth) const
Determine how many of the OldDepth outermost template parameter lists would be removed by substitutin...
Definition: Template.h:145
void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg)
Clear out a specific template argument.
Definition: Template.h:197
bool isRewrite() const
Determine whether we are rewriting template parameters rather than substituting for them.
Definition: Template.h:117
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:1818
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1660
A C++ nested-name-specifier augmented with source location information.
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isInstantiationDependent() const
Whether this nested name specifier involves a template parameter.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Represents a pack expansion of types.
Definition: Type.h:7147
Sugar for parentheses used when specifying types.
Definition: Type.h:3173
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2983
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1821
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1866
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1854
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3008
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
bool hasInheritedDefaultArg() const
Definition: Decl.h:1870
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition: Decl.h:1817
Expr * getDefaultArg()
Definition: Decl.cpp:2971
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3013
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1775
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1874
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3199
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:929
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3519
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8140
The collection of all-type qualifiers we support.
Definition: Type.h:324
void removeObjCLifetime()
Definition: Type.h:544
Represents a struct/union/class.
Definition: Decl.h:4162
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:858
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3440
Represents the body of a requires-expression.
Definition: DeclCXX.h:2086
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:502
SourceLocation getLParenLoc() const
Definition: ExprConcepts.h:570
SourceLocation getRParenLoc() const
Definition: ExprConcepts.h:571
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
Sema & SemaRef
Definition: SemaBase.h:40
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13243
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8062
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3013
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5894
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5926
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5923
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12646
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12116
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:466
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:13193
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13177
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12675
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, std::optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, std::optional< unsigned > NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
void ActOnFinishCXXNonNestedClass()
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:13180
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6870
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition: Sema.h:13538
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
concepts::Requirement::SubstitutionDiagnostic * createSubstDiagAt(SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using ASTConte...
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11656
bool SubstExprs(ArrayRef< Expr * > Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr * > &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTContext & Context
Definition: Sema.h:911
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:13204
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:531
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTContext & getASTContext() const
Definition: Sema.h:534
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:819
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:16982
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition: Sema.h:527
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, QualType ConstrainedType, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14426
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition: Sema.h:13229
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true, bool PrimaryHasMatchedPackOnParmToNonPackOnArg=false)
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3651
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:12687
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:13237
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1046
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13587
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15216
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20995
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:13213
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5501
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
ExprResult SubstConstraintExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTConsumer & Consumer
Definition: Sema.h:912
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1686
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition: Sema.h:13221
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19026
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:7781
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7931
SourceManager & SourceMgr
Definition: Sema.h:914
DiagnosticsEngine & Diags
Definition: Sema.h:913
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition: Sema.h:13188
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:564
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21192
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Perform substitution on the base class specifiers of the given class template specialization.
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:590
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8282
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Encodes a location in the source.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void warnOnStackNearlyExhausted(SourceLocation Loc)
Check to see if we're low on stack space and produce a warning if we're low on stack space (Currently...
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4120
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4488
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4573
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:149
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:865
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6470
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:858
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6389
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
void setTagKind(TagKind TK)
Definition: Decl.h:3777
SourceRange getBraceRange() const
Definition: Decl.h:3657
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3662
StringRef getKindName() const
Definition: Decl.h:3769
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4777
TagKind getTagKind() const
Definition: Decl.h:3773
void setBraceRange(SourceRange R)
Definition: Decl.h:3658
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1263
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:444
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:418
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:298
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA)
Definition: Template.h:661
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition: Template.h:700
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations,...
Definition: Template.h:684
void setEvaluateConstraints(bool B)
Definition: Template.h:602
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition: Template.h:678
LocalInstantiationScope * getStartingScope() const
Definition: Template.h:672
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition: Template.h:675
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
delayed_partial_spec_iterator delayed_partial_spec_end()
Return an iterator to the end of the set of "delayed" partial specializations, which must be passed t...
Definition: Template.h:696
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition: Template.h:688
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:398
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isNull() const
Determine whether this template name is NULL.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6667
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
bool isParameterPack() const
Returns whether this is a parameter pack.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint)
Wrapper for template type parameters.
Definition: TypeLoc.h:759
bool isParameterPack() const
Definition: Type.h:6350
unsigned getIndex() const
Definition: Type.h:6349
unsigned getDepth() const
Definition: Type.h:6348
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Declaration of an alias template.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:260
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:242
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition: ASTConcept.h:270
const DeclarationNameInfo & getConceptNameInfo() const
Definition: ASTConcept.h:274
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:246
void setLocStart(SourceLocation L)
Definition: Decl.h:3413
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
void pushTrivial(ASTContext &Context, QualType T, SourceLocation Loc)
Pushes 'T' with all locations pointing to 'Loc'.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1257
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:164
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7908
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7919
SourceLocation getNameLoc() const
Definition: TypeLoc.h:536
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:540
An operation on a type.
Definition: TypeVisitor.h:64
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition: Type.cpp:3211
The base class of the type hierarchy.
Definition: Type.h:1828
bool isVoidType() const
Definition: Type.h:8516
bool isReferenceType() const
Definition: Type.h:8210
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2715
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2707
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2725
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8741
bool isRecordType() const
Definition: Type.h:8292
QualType getUnderlyingType() const
Definition: Decl.h:3482
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition: Decl.cpp:5419
Represents a variable declaration or definition.
Definition: Decl.h:886
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1238
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2744
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2879
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1123
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2870
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Represents a GCC generic vector type.
Definition: Type.h:4035
A requires-expression requirement which queries the validity and properties of an expression ('simple...
Definition: ExprConcepts.h:280
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
Definition: ExprConcepts.h:408
const ReturnTypeRequirement & getReturnTypeRequirement() const
Definition: ExprConcepts.h:398
SourceLocation getNoexceptLoc() const
Definition: ExprConcepts.h:390
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:429
const ASTConstraintSatisfaction & getConstraintSatisfaction() const
Definition: ExprConcepts.h:484
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:168
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:225
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
Definition: ExprConcepts.h:260
TypeSourceInfo * getType() const
Definition: ExprConcepts.h:267
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:37
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeCanonical()
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
The JSON file list parser is used to communicate input to InstallAPI.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
NamedDecl * getAsNamedDecl(TemplateParameter P)
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition: ASTLambda.h:89
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
@ Result
The result type of a method or function.
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
TagTypeKind
The kind of a tag type.
Definition: Type.h:6877
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:367
@ Success
Template argument deduction was successful.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6852
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ AS_public
Definition: Specifiers.h:124
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
#define false
Definition: stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:691
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:688
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
Holds information about the various types of exception specification.
Definition: Type.h:5165
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5167
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5200
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12692
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:12856
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:12825
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:12851
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition: Sema.h:12820
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12812
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:12694
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12786
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition: Sema.h:12704
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12713
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:12732
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12783
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:12740
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:12747
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:12790
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:12758
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:12796
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition: Sema.h:12723
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition: Sema.h:12802
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12799
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition: Sema.h:12805
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12720
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:12728
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12736
@ TemplateInstantiation
We are instantiating a template declaration.
Definition: Sema.h:12697
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12750
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12754
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12709
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12780
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition: Sema.h:12743
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12815
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
A stack object to be created when performing template instantiation.
Definition: Sema.h:12880
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13040
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange=SourceRange())
Note that we are instantiating a class template, function template, variable template,...
void Clear()
Note that we have finished instantiating this template.
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:13044
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
Contains all information for a given match.