clang 20.0.0git
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/DeclBase.h"
21#include "clang/AST/Expr.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Sema.h"
35#include "clang/Sema/Template.h"
38#include "llvm/ADT/STLForwardCompat.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/SaveAndRestore.h"
42#include "llvm/Support/TimeProfiler.h"
43#include <optional>
44
45using namespace clang;
46using namespace sema;
47
48//===----------------------------------------------------------------------===/
49// Template Instantiation Support
50//===----------------------------------------------------------------------===/
51
52namespace {
54struct Response {
55 const Decl *NextDecl = nullptr;
56 bool IsDone = false;
57 bool ClearRelativeToPrimary = true;
58 static Response Done() {
59 Response R;
60 R.IsDone = true;
61 return R;
62 }
63 static Response ChangeDecl(const Decl *ND) {
64 Response R;
65 R.NextDecl = ND;
66 return R;
67 }
68 static Response ChangeDecl(const DeclContext *Ctx) {
69 Response R;
70 R.NextDecl = Decl::castFromDeclContext(Ctx);
71 return R;
72 }
73
74 static Response UseNextDecl(const Decl *CurDecl) {
75 return ChangeDecl(CurDecl->getDeclContext());
76 }
77
78 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
79 Response R = Response::UseNextDecl(CurDecl);
80 R.ClearRelativeToPrimary = false;
81 return R;
82 }
83};
84
85// Retrieve the primary template for a lambda call operator. It's
86// unfortunate that we only have the mappings of call operators rather
87// than lambda classes.
88const FunctionDecl *
89getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
90 if (!isLambdaCallOperator(LambdaCallOperator))
91 return LambdaCallOperator;
92 while (true) {
93 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
94 LambdaCallOperator->getDescribedTemplate());
95 FTD && FTD->getInstantiatedFromMemberTemplate()) {
96 LambdaCallOperator =
97 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
98 } else if (LambdaCallOperator->getPrimaryTemplate()) {
99 // Cases where the lambda operator is instantiated in
100 // TemplateDeclInstantiator::VisitCXXMethodDecl.
101 LambdaCallOperator =
102 LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
103 } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)
104 ->getInstantiatedFromMemberFunction())
105 LambdaCallOperator = Prev;
106 else
107 break;
108 }
109 return LambdaCallOperator;
110}
111
112struct EnclosingTypeAliasTemplateDetails {
113 TypeAliasTemplateDecl *Template = nullptr;
114 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
115 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
116
117 explicit operator bool() noexcept { return Template; }
118};
119
120// Find the enclosing type alias template Decl from CodeSynthesisContexts, as
121// well as its primary template and instantiating template arguments.
122EnclosingTypeAliasTemplateDetails
123getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
124 for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
126 TypeAliasTemplateInstantiation)
127 continue;
128 EnclosingTypeAliasTemplateDetails Result;
129 auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),
130 *Next = TATD->getInstantiatedFromMemberTemplate();
131 Result = {
132 /*Template=*/TATD,
133 /*PrimaryTypeAliasDecl=*/TATD,
134 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
135 };
136 while (Next) {
137 Result.PrimaryTypeAliasDecl = Next;
138 Next = Next->getInstantiatedFromMemberTemplate();
139 }
140 return Result;
141 }
142 return {};
143}
144
145// Check if we are currently inside of a lambda expression that is
146// surrounded by a using alias declaration. e.g.
147// template <class> using type = decltype([](auto) { ^ }());
148// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
149// a DeclContext, nor does it have an associated specialization Decl from which
150// we could collect these template arguments.
151bool isLambdaEnclosedByTypeAliasDecl(
152 const FunctionDecl *LambdaCallOperator,
153 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
154 struct Visitor : DynamicRecursiveASTVisitor {
155 Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
156 bool VisitLambdaExpr(LambdaExpr *LE) override {
157 // Return true to bail out of the traversal, implying the Decl contains
158 // the lambda.
159 return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=
160 CallOperator;
161 }
162 const FunctionDecl *CallOperator;
163 };
164
165 QualType Underlying =
166 PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
167
168 return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
169 .TraverseType(Underlying);
170}
171
172// Add template arguments from a variable template instantiation.
173Response
174HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
176 bool SkipForSpecialization) {
177 // For a class-scope explicit specialization, there are no template arguments
178 // at this level, but there may be enclosing template arguments.
179 if (VarTemplSpec->isClassScopeExplicitSpecialization())
180 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
181
182 // We're done when we hit an explicit specialization.
183 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
184 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
185 return Response::Done();
186
187 // If this variable template specialization was instantiated from a
188 // specialized member that is a variable template, we're done.
189 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
190 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
191 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
193 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
194 if (!SkipForSpecialization)
195 Result.addOuterTemplateArguments(
196 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
197 /*Final=*/false);
198 if (Partial->isMemberSpecialization())
199 return Response::Done();
200 } else {
201 VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Specialized);
202 if (!SkipForSpecialization)
203 Result.addOuterTemplateArguments(
204 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
205 /*Final=*/false);
206 if (Tmpl->isMemberSpecialization())
207 return Response::Done();
208 }
209 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
210}
211
212// If we have a template template parameter with translation unit context,
213// then we're performing substitution into a default template argument of
214// this template template parameter before we've constructed the template
215// that will own this template template parameter. In this case, we
216// use empty template parameter lists for all of the outer templates
217// to avoid performing any substitutions.
218Response
219HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
221 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
222 Result.addOuterTemplateArguments(std::nullopt);
223 return Response::Done();
224}
225
226Response HandlePartialClassTemplateSpec(
227 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
228 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
229 if (!SkipForSpecialization)
230 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
231 return Response::Done();
232}
233
234// Add template arguments from a class template instantiation.
235Response
236HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
238 bool SkipForSpecialization) {
239 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
240 // We're done when we hit an explicit specialization.
241 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
242 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
243 return Response::Done();
244
245 if (!SkipForSpecialization)
246 Result.addOuterTemplateArguments(
247 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
248 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
249 /*Final=*/false);
250
251 // If this class template specialization was instantiated from a
252 // specialized member that is a class template, we're done.
253 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
254 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
255 return Response::Done();
256
257 // If this was instantiated from a partial template specialization, we need
258 // to get the next level of declaration context from the partial
259 // specialization, as the ClassTemplateSpecializationDecl's
260 // DeclContext/LexicalDeclContext will be for the primary template.
261 if (auto *InstFromPartialTempl =
262 ClassTemplSpec->getSpecializedTemplateOrPartial()
264 return Response::ChangeDecl(
265 InstFromPartialTempl->getLexicalDeclContext());
266 }
267 return Response::UseNextDecl(ClassTemplSpec);
268}
269
270Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
272 const FunctionDecl *Pattern, bool RelativeToPrimary,
273 bool ForConstraintInstantiation,
274 bool ForDefaultArgumentSubstitution) {
275 // Add template arguments from a function template specialization.
276 if (!RelativeToPrimary &&
277 Function->getTemplateSpecializationKindForInstantiation() ==
279 return Response::Done();
280
281 if (!RelativeToPrimary &&
282 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
283 // This is an implicit instantiation of an explicit specialization. We
284 // don't get any template arguments from this function but might get
285 // some from an enclosing template.
286 return Response::UseNextDecl(Function);
287 } else if (const TemplateArgumentList *TemplateArgs =
288 Function->getTemplateSpecializationArgs()) {
289 // Add the template arguments for this specialization.
290 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
291 TemplateArgs->asArray(),
292 /*Final=*/false);
293
294 if (RelativeToPrimary &&
295 (Function->getTemplateSpecializationKind() ==
297 (Function->getFriendObjectKind() &&
298 !Function->getPrimaryTemplate()->getFriendObjectKind())))
299 return Response::UseNextDecl(Function);
300
301 // If this function was instantiated from a specialized member that is
302 // a function template, we're done.
303 assert(Function->getPrimaryTemplate() && "No function template?");
304 if (!ForDefaultArgumentSubstitution &&
305 Function->getPrimaryTemplate()->isMemberSpecialization())
306 return Response::Done();
307
308 // If this function is a generic lambda specialization, we are done.
309 if (!ForConstraintInstantiation &&
311 return Response::Done();
312
313 } else if (Function->getDescribedFunctionTemplate()) {
314 assert(
315 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
316 "Outer template not instantiated?");
317 }
318 // If this is a friend or local declaration and it declares an entity at
319 // namespace scope, take arguments from its lexical parent
320 // instead of its semantic parent, unless of course the pattern we're
321 // instantiating actually comes from the file's context!
322 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
323 Function->getNonTransparentDeclContext()->isFileContext() &&
324 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
325 return Response::ChangeDecl(Function->getLexicalDeclContext());
326 }
327
328 if (ForConstraintInstantiation && Function->getFriendObjectKind())
329 return Response::ChangeDecl(Function->getLexicalDeclContext());
330 return Response::UseNextDecl(Function);
331}
332
333Response HandleFunctionTemplateDecl(Sema &SemaRef,
334 const FunctionTemplateDecl *FTD,
336 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
337 Result.addOuterTemplateArguments(
338 const_cast<FunctionTemplateDecl *>(FTD),
339 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(
340 SemaRef.Context),
341 /*Final=*/false);
342
344
345 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
346 if (NNS->isInstantiationDependent()) {
347 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
348 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
349 // Prefer template arguments from the injected-class-type if possible.
350 // For example,
351 // ```cpp
352 // template <class... Pack> struct S {
353 // template <class T> void foo();
354 // };
355 // template <class... Pack> template <class T>
356 // ^^^^^^^^^^^^^ InjectedTemplateArgs
357 // They're of kind TemplateArgument::Pack, not of
358 // TemplateArgument::Type.
359 // void S<Pack...>::foo() {}
360 // ^^^^^^^
361 // TSTy->template_arguments() (which are of PackExpansionType)
362 // ```
363 // This meets the contract in
364 // TreeTransform::TryExpandParameterPacks that the template arguments
365 // for unexpanded parameters should be of a Pack kind.
366 if (TSTy->isCurrentInstantiation()) {
367 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
368 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
369 Arguments = CTD->getInjectedTemplateArgs(SemaRef.Context);
370 else if (auto *Specialization =
371 dyn_cast<ClassTemplateSpecializationDecl>(RD))
372 Arguments =
373 Specialization->getTemplateInstantiationArgs().asArray();
374 }
375 Result.addOuterTemplateArguments(
376 TSTy->getTemplateName().getAsTemplateDecl(), Arguments,
377 /*Final=*/false);
378 }
379 }
380
381 NNS = NNS->getPrefix();
382 }
383 }
384
385 return Response::ChangeDecl(FTD->getLexicalDeclContext());
386}
387
388Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
390 ASTContext &Context,
391 bool ForConstraintInstantiation) {
392 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
393 assert(
394 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
395 "Outer template not instantiated?");
396 if (ClassTemplate->isMemberSpecialization())
397 return Response::Done();
398 if (ForConstraintInstantiation)
399 Result.addOuterTemplateArguments(
400 const_cast<CXXRecordDecl *>(Rec),
401 ClassTemplate->getInjectedTemplateArgs(SemaRef.Context),
402 /*Final=*/false);
403 }
404
405 if (const MemberSpecializationInfo *MSInfo =
407 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
408 return Response::Done();
409
410 bool IsFriend = Rec->getFriendObjectKind() ||
413 if (ForConstraintInstantiation && IsFriend &&
415 return Response::ChangeDecl(Rec->getLexicalDeclContext());
416 }
417
418 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
419 // TypeAliasTemplateDecl that this lambda is defined inside of.
420 if (Rec->isLambda()) {
421 if (const Decl *LCD = Rec->getLambdaContextDecl())
422 return Response::ChangeDecl(LCD);
423 // Retrieve the template arguments for a using alias declaration.
424 // This is necessary for constraint checking, since we always keep
425 // constraints relative to the primary template.
426 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);
427 ForConstraintInstantiation && TypeAlias) {
428 if (isLambdaEnclosedByTypeAliasDecl(Rec->getLambdaCallOperator(),
429 TypeAlias.PrimaryTypeAliasDecl)) {
430 Result.addOuterTemplateArguments(TypeAlias.Template,
431 TypeAlias.AssociatedTemplateArguments,
432 /*Final=*/false);
433 // Visit the parent of the current type alias declaration rather than
434 // the lambda thereof.
435 // E.g., in the following example:
436 // struct S {
437 // template <class> using T = decltype([]<Concept> {} ());
438 // };
439 // void foo() {
440 // S::T var;
441 // }
442 // The instantiated lambda expression (which we're visiting at 'var')
443 // has a function DeclContext 'foo' rather than the Record DeclContext
444 // S. This seems to be an oversight to me that we may want to set a
445 // Sema Context from the CXXScopeSpec before substituting into T.
446 return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
447 }
448 }
449 }
450
451 return Response::UseNextDecl(Rec);
452}
453
454Response HandleImplicitConceptSpecializationDecl(
457 Result.addOuterTemplateArguments(
458 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
460 /*Final=*/false);
461 return Response::UseNextDecl(CSD);
462}
463
464Response HandleGenericDeclContext(const Decl *CurDecl) {
465 return Response::UseNextDecl(CurDecl);
466}
467} // namespace TemplateInstArgsHelpers
468} // namespace
469
471 const NamedDecl *ND, const DeclContext *DC, bool Final,
472 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
473 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
474 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
475 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
476 // Accumulate the set of template argument lists in this structure.
478
479 using namespace TemplateInstArgsHelpers;
480 const Decl *CurDecl = ND;
481
482 if (!CurDecl)
483 CurDecl = Decl::castFromDeclContext(DC);
484
485 if (Innermost) {
486 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
487 Final);
488 // Populate placeholder template arguments for TemplateTemplateParmDecls.
489 // This is essential for the case e.g.
490 //
491 // template <class> concept Concept = false;
492 // template <template <Concept C> class T> void foo(T<int>)
493 //
494 // where parameter C has a depth of 1 but the substituting argument `int`
495 // has a depth of 0.
496 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
497 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
498 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
499 }
500
501 while (!CurDecl->isFileContextDecl()) {
502 Response R;
503 if (const auto *VarTemplSpec =
504 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
505 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
506 } else if (const auto *PartialClassTemplSpec =
507 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
508 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
509 SkipForSpecialization);
510 } else if (const auto *ClassTemplSpec =
511 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
512 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
513 SkipForSpecialization);
514 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
515 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
516 ForConstraintInstantiation,
517 ForDefaultArgumentSubstitution);
518 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
519 R = HandleRecordDecl(*this, Rec, Result, Context,
520 ForConstraintInstantiation);
521 } else if (const auto *CSD =
522 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
523 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
524 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
525 R = HandleFunctionTemplateDecl(*this, FTD, Result);
526 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
527 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
528 } else if (!isa<DeclContext>(CurDecl)) {
529 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
530 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
531 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
532 }
533 } else {
534 R = HandleGenericDeclContext(CurDecl);
535 }
536
537 if (R.IsDone)
538 return Result;
539 if (R.ClearRelativeToPrimary)
540 RelativeToPrimary = false;
541 assert(R.NextDecl);
542 CurDecl = R.NextDecl;
543 }
544
545 return Result;
546}
547
549 switch (Kind) {
557 case ConstraintsCheck:
559 return true;
560
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 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1589 // Call the base version; it will forward to our overridden version below.
1590 return inherited::TransformFunctionProtoType(TLB, TL);
1591 }
1592
1593 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1595 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1596 // Special case for transforming a deduction guide, we return a
1597 // transformed TemplateSpecializationType.
1598 if (Type.isNull() &&
1599 SemaRef.CodeSynthesisContexts.back().Kind ==
1601 // Return a TemplateSpecializationType for transforming a deduction
1602 // guide.
1603 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1604 auto Type =
1605 inherited::TransformType(ICT->getInjectedSpecializationType());
1606 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1607 return Type;
1608 }
1609 }
1610 return Type;
1611 }
1612 // Override the default version to handle a rewrite-template-arg-pack case
1613 // for building a deduction guide.
1614 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1615 TemplateArgumentLoc &Output,
1616 bool Uneval = false) {
1617 const TemplateArgument &Arg = Input.getArgument();
1618 std::vector<TemplateArgument> TArgs;
1619 switch (Arg.getKind()) {
1621 // Literally rewrite the template argument pack, instead of unpacking
1622 // it.
1623 for (auto &pack : Arg.getPackAsArray()) {
1625 pack, QualType(), SourceLocation{});
1626 TemplateArgumentLoc Output;
1627 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1628 return true; // fails
1629 TArgs.push_back(Output.getArgument());
1630 }
1631 Output = SemaRef.getTrivialTemplateArgumentLoc(
1632 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1634 return false;
1635 default:
1636 break;
1637 }
1638 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1639 }
1640
1641 template<typename Fn>
1642 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1644 CXXRecordDecl *ThisContext,
1645 Qualifiers ThisTypeQuals,
1646 Fn TransformExceptionSpec);
1647
1648 ParmVarDecl *
1649 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1650 std::optional<unsigned> NumExpansions,
1651 bool ExpectParameterPack);
1652
1653 using inherited::TransformTemplateTypeParmType;
1654 /// Transforms a template type parameter type by performing
1655 /// substitution of the corresponding template type argument.
1656 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1658 bool SuppressObjCLifetime);
1659
1660 QualType BuildSubstTemplateTypeParmType(
1661 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1662 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1663 TemplateArgument Arg, SourceLocation NameLoc);
1664
1665 /// Transforms an already-substituted template type parameter pack
1666 /// into either itself (if we aren't substituting into its pack expansion)
1667 /// or the appropriate substituted argument.
1668 using inherited::TransformSubstTemplateTypeParmPackType;
1669 QualType
1670 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1672 bool SuppressObjCLifetime);
1673
1674 QualType
1675 TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
1678 if (Type->getSubstitutionFlag() !=
1679 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace)
1680 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1681
1682 assert(Type->getPackIndex());
1683 TemplateArgument TA = TemplateArgs(
1684 Type->getReplacedParameter()->getDepth(), Type->getIndex());
1685 assert(*Type->getPackIndex() + 1 <= TA.pack_size());
1687 SemaRef, TA.pack_size() - 1 - *Type->getPackIndex());
1688
1689 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1690 }
1691
1693 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1694 if (auto TypeAlias =
1695 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1696 getSema());
1697 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1698 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1699 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1700 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1701 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1702 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1703 if (TA.isDependent())
1704 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1705 }
1706 return inherited::ComputeLambdaDependency(LSI);
1707 }
1708
1709 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1710 // Do not rebuild lambdas to avoid creating a new type.
1711 // Lambdas have already been processed inside their eval contexts.
1713 return E;
1714 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1715 /*InstantiatingLambdaOrBlock=*/true);
1717
1718 return inherited::TransformLambdaExpr(E);
1719 }
1720
1721 ExprResult TransformBlockExpr(BlockExpr *E) {
1722 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1723 /*InstantiatingLambdaOrBlock=*/true);
1724 return inherited::TransformBlockExpr(E);
1725 }
1726
1727 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1728 LambdaScopeInfo *LSI) {
1729 CXXMethodDecl *MD = LSI->CallOperator;
1730 for (ParmVarDecl *PVD : MD->parameters()) {
1731 assert(PVD && "null in a parameter list");
1732 if (!PVD->hasDefaultArg())
1733 continue;
1734 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1735 // FIXME: Obtain the source location for the '=' token.
1736 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1737 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1738 // If substitution fails, the default argument is set to a
1739 // RecoveryExpr that wraps the uninstantiated default argument so
1740 // that downstream diagnostics are omitted.
1741 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1742 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1743 UninstExpr->getType());
1744 if (ErrorResult.isUsable())
1745 PVD->setDefaultArg(ErrorResult.get());
1746 }
1747 }
1748 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1749 }
1750
1751 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1752 // Currently, we instantiate the body when instantiating the lambda
1753 // expression. However, `EvaluateConstraints` is disabled during the
1754 // instantiation of the lambda expression, causing the instantiation
1755 // failure of the return type requirement in the body. If p0588r1 is fully
1756 // implemented, the body will be lazily instantiated, and this problem
1757 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1758 // `true` to temporarily fix this issue.
1759 // FIXME: This temporary fix can be removed after fully implementing
1760 // p0588r1.
1761 llvm::SaveAndRestore _(EvaluateConstraints, true);
1762 return inherited::TransformLambdaBody(E, Body);
1763 }
1764
1765 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1766 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1767 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1768 if (TransReq.isInvalid())
1769 return TransReq;
1770 assert(TransReq.get() != E &&
1771 "Do not change value of isSatisfied for the existing expression. "
1772 "Create a new expression instead.");
1773 if (E->getBody()->isDependentContext()) {
1774 Sema::SFINAETrap Trap(SemaRef);
1775 // We recreate the RequiresExpr body, but not by instantiating it.
1776 // Produce pending diagnostics for dependent access check.
1777 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1778 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1779 if (Trap.hasErrorOccurred())
1780 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1781 }
1782 return TransReq;
1783 }
1784
1785 bool TransformRequiresExprRequirements(
1788 bool SatisfactionDetermined = false;
1789 for (concepts::Requirement *Req : Reqs) {
1790 concepts::Requirement *TransReq = nullptr;
1791 if (!SatisfactionDetermined) {
1792 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1793 TransReq = TransformTypeRequirement(TypeReq);
1794 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1795 TransReq = TransformExprRequirement(ExprReq);
1796 else
1797 TransReq = TransformNestedRequirement(
1798 cast<concepts::NestedRequirement>(Req));
1799 if (!TransReq)
1800 return true;
1801 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1802 // [expr.prim.req]p6
1803 // [...] The substitution and semantic constraint checking
1804 // proceeds in lexical order and stops when a condition that
1805 // determines the result of the requires-expression is
1806 // encountered. [..]
1807 SatisfactionDetermined = true;
1808 } else
1809 TransReq = Req;
1810 Transformed.push_back(TransReq);
1811 }
1812 return false;
1813 }
1814
1815 TemplateParameterList *TransformTemplateParameterList(
1816 TemplateParameterList *OrigTPL) {
1817 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1818
1819 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1820 TemplateDeclInstantiator DeclInstantiator(getSema(),
1821 /* DeclContext *Owner */ Owner, TemplateArgs);
1822 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1823 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1824 }
1825
1827 TransformTypeRequirement(concepts::TypeRequirement *Req);
1829 TransformExprRequirement(concepts::ExprRequirement *Req);
1831 TransformNestedRequirement(concepts::NestedRequirement *Req);
1832 ExprResult TransformRequiresTypeParams(
1833 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1836 SmallVectorImpl<ParmVarDecl *> &TransParams,
1838
1839 private:
1841 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1842 const NonTypeTemplateParmDecl *parm,
1844 std::optional<unsigned> PackIndex);
1845 };
1846}
1847
1848bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1849 if (T.isNull())
1850 return true;
1851
1853 return false;
1854
1855 getSema().MarkDeclarationsReferencedInType(Loc, T);
1856 return true;
1857}
1858
1859static TemplateArgument
1861 assert(S.ArgumentPackSubstitutionIndex >= 0);
1862 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1864 if (Arg.isPackExpansion())
1865 Arg = Arg.getPackExpansionPattern();
1866 return Arg;
1867}
1868
1869Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1870 if (!D)
1871 return nullptr;
1872
1873 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1874 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1875 // If the corresponding template argument is NULL or non-existent, it's
1876 // because we are performing instantiation from explicitly-specified
1877 // template arguments in a function template, but there were some
1878 // arguments left unspecified.
1879 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1880 TTP->getPosition())) {
1881 IsIncomplete = true;
1882 return BailOutOnIncomplete ? nullptr : D;
1883 }
1884
1885 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1886
1887 if (TTP->isParameterPack()) {
1888 assert(Arg.getKind() == TemplateArgument::Pack &&
1889 "Missing argument pack");
1890 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1891 }
1892
1893 TemplateName Template = Arg.getAsTemplate();
1894 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1895 "Wrong kind of template template argument");
1896 return Template.getAsTemplateDecl();
1897 }
1898
1899 // Fall through to find the instantiated declaration for this template
1900 // template parameter.
1901 }
1902
1903 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1904}
1905
1906Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1907 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1908 if (!Inst)
1909 return nullptr;
1910
1911 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1912 return Inst;
1913}
1914
1915bool TemplateInstantiator::TransformExceptionSpec(
1917 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1918 if (ESI.Type == EST_Uninstantiated) {
1919 ESI.instantiate();
1920 Changed = true;
1921 }
1922 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1923}
1924
1925NamedDecl *
1926TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1928 // If the first part of the nested-name-specifier was a template type
1929 // parameter, instantiate that type parameter down to a tag type.
1930 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1931 const TemplateTypeParmType *TTP
1932 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1933
1934 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1935 // FIXME: This needs testing w/ member access expressions.
1936 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1937
1938 if (TTP->isParameterPack()) {
1939 assert(Arg.getKind() == TemplateArgument::Pack &&
1940 "Missing argument pack");
1941
1942 if (getSema().ArgumentPackSubstitutionIndex == -1)
1943 return nullptr;
1944
1945 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1946 }
1947
1948 QualType T = Arg.getAsType();
1949 if (T.isNull())
1950 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1951
1952 if (const TagType *Tag = T->getAs<TagType>())
1953 return Tag->getDecl();
1954
1955 // The resulting type is not a tag; complain.
1956 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1957 return nullptr;
1958 }
1959 }
1960
1961 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1962}
1963
1964VarDecl *
1965TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1967 SourceLocation StartLoc,
1968 SourceLocation NameLoc,
1969 IdentifierInfo *Name) {
1970 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1971 StartLoc, NameLoc, Name);
1972 if (Var)
1973 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1974 return Var;
1975}
1976
1977VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1978 TypeSourceInfo *TSInfo,
1979 QualType T) {
1980 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1981 if (Var)
1982 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1983 return Var;
1984}
1985
1987TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1988 ElaboratedTypeKeyword Keyword,
1989 NestedNameSpecifierLoc QualifierLoc,
1990 QualType T) {
1991 if (const TagType *TT = T->getAs<TagType>()) {
1992 TagDecl* TD = TT->getDecl();
1993
1994 SourceLocation TagLocation = KeywordLoc;
1995
1997
1998 // TODO: should we even warn on struct/class mismatches for this? Seems
1999 // like it's likely to produce a lot of spurious errors.
2000 if (Id && Keyword != ElaboratedTypeKeyword::None &&
2003 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
2004 TagLocation, Id)) {
2005 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
2006 << Id
2008 TD->getKindName());
2009 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
2010 }
2011 }
2012 }
2013
2014 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
2015}
2016
2017TemplateName TemplateInstantiator::TransformTemplateName(
2018 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
2019 QualType ObjectType, NamedDecl *FirstQualifierInScope,
2020 bool AllowInjectedClassName) {
2022 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
2023 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2024 // If the corresponding template argument is NULL or non-existent, it's
2025 // because we are performing instantiation from explicitly-specified
2026 // template arguments in a function template, but there were some
2027 // arguments left unspecified.
2028 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2029 TTP->getPosition())) {
2030 IsIncomplete = true;
2031 return BailOutOnIncomplete ? TemplateName() : Name;
2032 }
2033
2034 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2035
2036 if (TemplateArgs.isRewrite()) {
2037 // We're rewriting the template parameter as a reference to another
2038 // template parameter.
2039 if (Arg.getKind() == TemplateArgument::Pack) {
2040 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2041 "unexpected pack arguments in template rewrite");
2042 Arg = Arg.pack_begin()->getPackExpansionPattern();
2043 }
2044 assert(Arg.getKind() == TemplateArgument::Template &&
2045 "unexpected nontype template argument kind in template rewrite");
2046 return Arg.getAsTemplate();
2047 }
2048
2049 auto [AssociatedDecl, Final] =
2050 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2051 std::optional<unsigned> PackIndex;
2052 if (TTP->isParameterPack()) {
2053 assert(Arg.getKind() == TemplateArgument::Pack &&
2054 "Missing argument pack");
2055
2056 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2057 // We have the template argument pack to substitute, but we're not
2058 // actually expanding the enclosing pack expansion yet. So, just
2059 // keep the entire argument pack.
2060 return getSema().Context.getSubstTemplateTemplateParmPack(
2061 Arg, AssociatedDecl, TTP->getIndex(), Final);
2062 }
2063
2064 PackIndex = getPackIndex(Arg);
2065 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2066 }
2067
2068 TemplateName Template = Arg.getAsTemplate();
2069 assert(!Template.isNull() && "Null template template argument");
2070
2071 if (Final)
2072 return Template;
2073 return getSema().Context.getSubstTemplateTemplateParm(
2074 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2075 }
2076 }
2077
2079 = Name.getAsSubstTemplateTemplateParmPack()) {
2080 if (getSema().ArgumentPackSubstitutionIndex == -1)
2081 return Name;
2082
2083 TemplateArgument Pack = SubstPack->getArgumentPack();
2084 TemplateName Template =
2086 if (SubstPack->getFinal())
2087 return Template;
2088 return getSema().Context.getSubstTemplateTemplateParm(
2089 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2090 getPackIndex(Pack));
2091 }
2092
2093 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2094 FirstQualifierInScope,
2095 AllowInjectedClassName);
2096}
2097
2099TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2100 if (!E->isTypeDependent())
2101 return E;
2102
2103 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2104}
2105
2107TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2109 // If the corresponding template argument is NULL or non-existent, it's
2110 // because we are performing instantiation from explicitly-specified
2111 // template arguments in a function template, but there were some
2112 // arguments left unspecified.
2113 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2114 NTTP->getPosition())) {
2115 IsIncomplete = true;
2116 return BailOutOnIncomplete ? ExprError() : E;
2117 }
2118
2119 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2120
2121 if (TemplateArgs.isRewrite()) {
2122 // We're rewriting the template parameter as a reference to another
2123 // template parameter.
2124 if (Arg.getKind() == TemplateArgument::Pack) {
2125 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2126 "unexpected pack arguments in template rewrite");
2127 Arg = Arg.pack_begin()->getPackExpansionPattern();
2128 }
2129 assert(Arg.getKind() == TemplateArgument::Expression &&
2130 "unexpected nontype template argument kind in template rewrite");
2131 // FIXME: This can lead to the same subexpression appearing multiple times
2132 // in a complete expression.
2133 return Arg.getAsExpr();
2134 }
2135
2136 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2137 std::optional<unsigned> PackIndex;
2138 if (NTTP->isParameterPack()) {
2139 assert(Arg.getKind() == TemplateArgument::Pack &&
2140 "Missing argument pack");
2141
2142 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2143 // We have an argument pack, but we can't select a particular argument
2144 // out of it yet. Therefore, we'll build an expression to hold on to that
2145 // argument pack.
2146 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2147 E->getLocation(),
2148 NTTP->getDeclName());
2149 if (TargetType.isNull())
2150 return ExprError();
2151
2152 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2153 if (TargetType->isRecordType())
2154 ExprType.addConst();
2155 // FIXME: Pass in Final.
2157 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2158 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2159 }
2160 PackIndex = getPackIndex(Arg);
2161 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2162 }
2163 // FIXME: Don't put subst node on Final replacement.
2164 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2165 Arg, PackIndex);
2166}
2167
2168const AnnotateAttr *
2169TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2171 for (Expr *Arg : AA->args()) {
2172 ExprResult Res = getDerived().TransformExpr(Arg);
2173 if (Res.isUsable())
2174 Args.push_back(Res.get());
2175 }
2176 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2177 Args.data(), Args.size(), AA->getRange());
2178}
2179
2180const CXXAssumeAttr *
2181TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2182 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2183 if (!Res.isUsable())
2184 return AA;
2185
2186 Res = getSema().ActOnFinishFullExpr(Res.get(),
2187 /*DiscardedValue=*/false);
2188 if (!Res.isUsable())
2189 return AA;
2190
2191 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2192 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2193 AA->getRange());
2194 if (!Res.isUsable())
2195 return AA;
2196 }
2197
2198 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2199 AA->getRange());
2200}
2201
2202const LoopHintAttr *
2203TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2204 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2205
2206 if (TransformedExpr == LH->getValue())
2207 return LH;
2208
2209 // Generate error if there is a problem with the value.
2210 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2211 LH->getSemanticSpelling() ==
2212 LoopHintAttr::Pragma_unroll))
2213 return LH;
2214
2215 LoopHintAttr::OptionType Option = LH->getOption();
2216 LoopHintAttr::LoopHintState State = LH->getState();
2217
2218 llvm::APSInt ValueAPS =
2219 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2220 // The values of 0 and 1 block any unrolling of the loop.
2221 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2222 Option = LoopHintAttr::Unroll;
2223 State = LoopHintAttr::Disable;
2224 }
2225
2226 // Create new LoopHintValueAttr with integral expression in place of the
2227 // non-type template parameter.
2228 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2229 TransformedExpr, *LH);
2230}
2231const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2232 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2233 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2234 return nullptr;
2235
2236 return A;
2237}
2238const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2239 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2240 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2241 return nullptr;
2242
2243 return A;
2244}
2245
2246const CodeAlignAttr *
2247TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2248 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2249 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2250}
2251
2252ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2253 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2255 std::optional<unsigned> PackIndex) {
2256 ExprResult result;
2257
2258 // Determine the substituted parameter type. We can usually infer this from
2259 // the template argument, but not always.
2260 auto SubstParamType = [&] {
2261 QualType T;
2262 if (parm->isExpandedParameterPack())
2264 else
2265 T = parm->getType();
2266 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2267 T = cast<PackExpansionType>(T)->getPattern();
2268 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2269 };
2270
2271 bool refParam = false;
2272
2273 // The template argument itself might be an expression, in which case we just
2274 // return that expression. This happens when substituting into an alias
2275 // template.
2276 if (arg.getKind() == TemplateArgument::Expression) {
2277 Expr *argExpr = arg.getAsExpr();
2278 result = argExpr;
2279 if (argExpr->isLValue()) {
2280 if (argExpr->getType()->isRecordType()) {
2281 // Check whether the parameter was actually a reference.
2282 QualType paramType = SubstParamType();
2283 if (paramType.isNull())
2284 return ExprError();
2285 refParam = paramType->isReferenceType();
2286 } else {
2287 refParam = true;
2288 }
2289 }
2290 } else if (arg.getKind() == TemplateArgument::Declaration ||
2291 arg.getKind() == TemplateArgument::NullPtr) {
2292 if (arg.getKind() == TemplateArgument::Declaration) {
2293 ValueDecl *VD = arg.getAsDecl();
2294
2295 // Find the instantiation of the template argument. This is
2296 // required for nested templates.
2297 VD = cast_or_null<ValueDecl>(
2298 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2299 if (!VD)
2300 return ExprError();
2301 }
2302
2303 QualType paramType = arg.getNonTypeTemplateArgumentType();
2304 assert(!paramType.isNull() && "type substitution failed for param type");
2305 assert(!paramType->isDependentType() && "param type still dependent");
2306 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2307 refParam = paramType->isReferenceType();
2308 } else {
2309 QualType paramType = arg.getNonTypeTemplateArgumentType();
2311 refParam = paramType->isReferenceType();
2312 assert(result.isInvalid() ||
2314 paramType.getNonReferenceType()));
2315 }
2316
2317 if (result.isInvalid())
2318 return ExprError();
2319
2320 Expr *resultExpr = result.get();
2321 // FIXME: Don't put subst node on final replacement.
2323 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2324 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2325}
2326
2328TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2330 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2331 // We aren't expanding the parameter pack, so just return ourselves.
2332 return E;
2333 }
2334
2335 TemplateArgument Pack = E->getArgumentPack();
2337 // FIXME: Don't put subst node on final replacement.
2338 return transformNonTypeTemplateParmRef(
2339 E->getAssociatedDecl(), E->getParameterPack(),
2340 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2341}
2342
2344TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2346 ExprResult SubstReplacement = E->getReplacement();
2347 if (!isa<ConstantExpr>(SubstReplacement.get()))
2348 SubstReplacement = TransformExpr(E->getReplacement());
2349 if (SubstReplacement.isInvalid())
2350 return true;
2351 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2352 if (SubstType.isNull())
2353 return true;
2354 // The type may have been previously dependent and not now, which means we
2355 // might have to implicit cast the argument to the new type, for example:
2356 // template<auto T, decltype(T) U>
2357 // concept C = sizeof(U) == 4;
2358 // void foo() requires C<2, 'a'> { }
2359 // When normalizing foo(), we first form the normalized constraints of C:
2360 // AtomicExpr(sizeof(U) == 4,
2361 // U=SubstNonTypeTemplateParmExpr(Param=U,
2362 // Expr=DeclRef(U),
2363 // Type=decltype(T)))
2364 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2365 // produce:
2366 // AtomicExpr(sizeof(U) == 4,
2367 // U=SubstNonTypeTemplateParmExpr(Param=U,
2368 // Expr=ImpCast(
2369 // decltype(2),
2370 // SubstNTTPE(Param=U, Expr='a',
2371 // Type=char)),
2372 // Type=decltype(2)))
2373 // The call to CheckTemplateArgument here produces the ImpCast.
2374 TemplateArgument SugaredConverted, CanonicalConverted;
2375 if (SemaRef
2376 .CheckTemplateArgument(E->getParameter(), SubstType,
2377 SubstReplacement.get(), SugaredConverted,
2378 CanonicalConverted, Sema::CTAK_Specified)
2379 .isInvalid())
2380 return true;
2381 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2382 E->getParameter(), E->getExprLoc(),
2383 SugaredConverted, E->getPackIndex());
2384}
2385
2386ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2388 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2389 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2390}
2391
2393TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2394 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2395 // We can expand this parameter pack now.
2396 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
2397 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2398 if (!VD)
2399 return ExprError();
2400 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2401 }
2402
2403 QualType T = TransformType(E->getType());
2404 if (T.isNull())
2405 return ExprError();
2406
2407 // Transform each of the parameter expansions into the corresponding
2408 // parameters in the instantiation of the function decl.
2410 Vars.reserve(E->getNumExpansions());
2411 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2412 I != End; ++I) {
2413 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2414 if (!D)
2415 return ExprError();
2416 Vars.push_back(D);
2417 }
2418
2419 auto *PackExpr =
2420 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
2421 E->getParameterPackLocation(), Vars);
2422 getSema().MarkFunctionParmPackReferenced(PackExpr);
2423 return PackExpr;
2424}
2425
2427TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2428 VarDecl *PD) {
2429 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2430 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2431 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2432 assert(Found && "no instantiation for parameter pack");
2433
2434 Decl *TransformedDecl;
2435 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2436 // If this is a reference to a function parameter pack which we can
2437 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2438 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2439 QualType T = TransformType(E->getType());
2440 if (T.isNull())
2441 return ExprError();
2442 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2443 E->getExprLoc(), *Pack);
2444 getSema().MarkFunctionParmPackReferenced(PackExpr);
2445 return PackExpr;
2446 }
2447
2448 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2449 } else {
2450 TransformedDecl = cast<Decl *>(*Found);
2451 }
2452
2453 // We have either an unexpanded pack or a specific expansion.
2454 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2455}
2456
2458TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2459 NamedDecl *D = E->getDecl();
2460
2461 // Handle references to non-type template parameters and non-type template
2462 // parameter packs.
2463 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2464 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2465 return TransformTemplateParmRefExpr(E, NTTP);
2466
2467 // We have a non-type template parameter that isn't fully substituted;
2468 // FindInstantiatedDecl will find it in the local instantiation scope.
2469 }
2470
2471 // Handle references to function parameter packs.
2472 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2473 if (PD->isParameterPack())
2474 return TransformFunctionParmPackRefExpr(E, PD);
2475
2476 return inherited::TransformDeclRefExpr(E);
2477}
2478
2479ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2481 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2482 getDescribedFunctionTemplate() &&
2483 "Default arg expressions are never formed in dependent cases.");
2485 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2486 E->getParam());
2487}
2488
2489template<typename Fn>
2490QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2492 CXXRecordDecl *ThisContext,
2493 Qualifiers ThisTypeQuals,
2494 Fn TransformExceptionSpec) {
2495 // If this is a lambda or block, the transformation MUST be done in the
2496 // CurrentInstantiationScope since it introduces a mapping of
2497 // the original to the newly created transformed parameters.
2498 //
2499 // In that case, TemplateInstantiator::TransformLambdaExpr will
2500 // have already pushed a scope for this prototype, so don't create
2501 // a second one.
2502 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2503 std::optional<LocalInstantiationScope> Scope;
2504 if (!Current || !Current->isLambdaOrBlock())
2505 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2506
2507 return inherited::TransformFunctionProtoType(
2508 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2509}
2510
2511ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2512 ParmVarDecl *OldParm, int indexAdjustment,
2513 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2514 auto NewParm = SemaRef.SubstParmVarDecl(
2515 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2516 ExpectParameterPack, EvaluateConstraints);
2517 if (NewParm && SemaRef.getLangOpts().OpenCL)
2519 return NewParm;
2520}
2521
2522QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2523 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2524 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2525 TemplateArgument Arg, SourceLocation NameLoc) {
2526 QualType Replacement = Arg.getAsType();
2527
2528 // If the template parameter had ObjC lifetime qualifiers,
2529 // then any such qualifiers on the replacement type are ignored.
2530 if (SuppressObjCLifetime) {
2531 Qualifiers RQs;
2532 RQs = Replacement.getQualifiers();
2533 RQs.removeObjCLifetime();
2534 Replacement =
2535 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2536 }
2537
2538 if (Final) {
2539 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2540 return Replacement;
2541 }
2542 // TODO: only do this uniquing once, at the start of instantiation.
2543 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2544 Replacement, AssociatedDecl, Index, PackIndex);
2547 NewTL.setNameLoc(NameLoc);
2548 return Result;
2549}
2550
2552TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2554 bool SuppressObjCLifetime) {
2555 const TemplateTypeParmType *T = TL.getTypePtr();
2556 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2557 // Replace the template type parameter with its corresponding
2558 // template argument.
2559
2560 // If the corresponding template argument is NULL or doesn't exist, it's
2561 // because we are performing instantiation from explicitly-specified
2562 // template arguments in a function template class, but there were some
2563 // arguments left unspecified.
2564 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2565 IsIncomplete = true;
2566 if (BailOutOnIncomplete)
2567 return QualType();
2568
2571 NewTL.setNameLoc(TL.getNameLoc());
2572 return TL.getType();
2573 }
2574
2575 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2576
2577 if (TemplateArgs.isRewrite()) {
2578 // We're rewriting the template parameter as a reference to another
2579 // template parameter.
2580 if (Arg.getKind() == TemplateArgument::Pack) {
2581 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2582 "unexpected pack arguments in template rewrite");
2583 Arg = Arg.pack_begin()->getPackExpansionPattern();
2584 }
2585 assert(Arg.getKind() == TemplateArgument::Type &&
2586 "unexpected nontype template argument kind in template rewrite");
2587 QualType NewT = Arg.getAsType();
2588 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2589 return NewT;
2590 }
2591
2592 auto [AssociatedDecl, Final] =
2593 TemplateArgs.getAssociatedDecl(T->getDepth());
2594 std::optional<unsigned> PackIndex;
2595 if (T->isParameterPack()) {
2596 assert(Arg.getKind() == TemplateArgument::Pack &&
2597 "Missing argument pack");
2598
2599 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2600 // We have the template argument pack, but we're not expanding the
2601 // enclosing pack expansion yet. Just save the template argument
2602 // pack for later substitution.
2603 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2604 AssociatedDecl, T->getIndex(), Final, Arg);
2607 NewTL.setNameLoc(TL.getNameLoc());
2608 return Result;
2609 }
2610
2611 // PackIndex starts from last element.
2612 PackIndex = getPackIndex(Arg);
2613 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2614 }
2615
2616 assert(Arg.getKind() == TemplateArgument::Type &&
2617 "Template argument kind mismatch");
2618
2619 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2620 AssociatedDecl, T->getIndex(),
2621 PackIndex, Arg, TL.getNameLoc());
2622 }
2623
2624 // The template type parameter comes from an inner template (e.g.,
2625 // the template parameter list of a member template inside the
2626 // template we are instantiating). Create a new template type
2627 // parameter with the template "level" reduced by one.
2628 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2629 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2630 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2631 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2632 QualType Result = getSema().Context.getTemplateTypeParmType(
2633 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2634 T->isParameterPack(), NewTTPDecl);
2636 NewTL.setNameLoc(TL.getNameLoc());
2637 return Result;
2638}
2639
2640QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2642 bool SuppressObjCLifetime) {
2644
2645 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2646
2647 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2648 // We aren't expanding the parameter pack, so just return ourselves.
2649 QualType Result = TL.getType();
2650 if (NewReplaced != T->getAssociatedDecl())
2651 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2652 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2655 NewTL.setNameLoc(TL.getNameLoc());
2656 return Result;
2657 }
2658
2659 TemplateArgument Pack = T->getArgumentPack();
2661 return BuildSubstTemplateTypeParmType(
2662 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2663 getPackIndex(Pack), Arg, TL.getNameLoc());
2664}
2665
2668 Sema::EntityPrinter Printer) {
2669 SmallString<128> Message;
2670 SourceLocation ErrorLoc;
2671 if (Info.hasSFINAEDiagnostic()) {
2674 Info.takeSFINAEDiagnostic(PDA);
2675 PDA.second.EmitToString(S.getDiagnostics(), Message);
2676 ErrorLoc = PDA.first;
2677 } else {
2678 ErrorLoc = Info.getLocation();
2679 }
2680 SmallString<128> Entity;
2681 llvm::raw_svector_ostream OS(Entity);
2682 Printer(OS);
2683 const ASTContext &C = S.Context;
2685 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2686}
2687
2690 SmallString<128> Entity;
2691 llvm::raw_svector_ostream OS(Entity);
2692 Printer(OS);
2693 const ASTContext &C = Context;
2695 /*SubstitutedEntity=*/C.backupStr(Entity),
2696 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2697}
2698
2699ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2700 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2703 SmallVectorImpl<ParmVarDecl *> &TransParams,
2705
2706 TemplateDeductionInfo Info(KWLoc);
2707 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2708 RE, Info,
2709 SourceRange{KWLoc, RBraceLoc});
2711
2712 unsigned ErrorIdx;
2713 if (getDerived().TransformFunctionTypeParams(
2714 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2715 &TransParams, PInfos, &ErrorIdx) ||
2716 Trap.hasErrorOccurred()) {
2718 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2719 // Add a 'failed' Requirement to contain the error that caused the failure
2720 // here.
2721 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2722 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2723 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2724 TransParams, RE->getRParenLoc(),
2725 TransReqs, RBraceLoc);
2726 }
2727
2728 return ExprResult{};
2729}
2730
2732TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2733 if (!Req->isDependent() && !AlwaysRebuild())
2734 return Req;
2735 if (Req->isSubstitutionFailure()) {
2736 if (AlwaysRebuild())
2737 return RebuildTypeRequirement(
2739 return Req;
2740 }
2741
2745 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2746 Req->getType()->getTypeLoc().getSourceRange());
2747 if (TypeInst.isInvalid())
2748 return nullptr;
2749 TypeSourceInfo *TransType = TransformType(Req->getType());
2750 if (!TransType || Trap.hasErrorOccurred())
2751 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2752 [&] (llvm::raw_ostream& OS) {
2753 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2754 }));
2755 return RebuildTypeRequirement(TransType);
2756}
2757
2759TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2760 if (!Req->isDependent() && !AlwaysRebuild())
2761 return Req;
2762
2764
2765 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2766 TransExpr;
2767 if (Req->isExprSubstitutionFailure())
2768 TransExpr = Req->getExprSubstitutionDiagnostic();
2769 else {
2770 Expr *E = Req->getExpr();
2772 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2773 E->getSourceRange());
2774 if (ExprInst.isInvalid())
2775 return nullptr;
2776 ExprResult TransExprRes = TransformExpr(E);
2777 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2778 TransExprRes.get()->hasPlaceholderType())
2779 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2780 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2781 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2783 });
2784 else
2785 TransExpr = TransExprRes.get();
2786 }
2787
2788 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2789 const auto &RetReq = Req->getReturnTypeRequirement();
2790 if (RetReq.isEmpty())
2791 TransRetReq.emplace();
2792 else if (RetReq.isSubstitutionFailure())
2793 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2794 else if (RetReq.isTypeConstraint()) {
2795 TemplateParameterList *OrigTPL =
2796 RetReq.getTypeConstraintTemplateParameterList();
2797 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2799 Req, Info, OrigTPL->getSourceRange());
2800 if (TPLInst.isInvalid())
2801 return nullptr;
2802 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2803 if (!TPL || Trap.hasErrorOccurred())
2804 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2805 [&] (llvm::raw_ostream& OS) {
2806 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2807 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2808 }));
2809 else {
2810 TPLInst.Clear();
2811 TransRetReq.emplace(TPL);
2812 }
2813 }
2814 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2815 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2816 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2817 std::move(*TransRetReq));
2818 return RebuildExprRequirement(
2819 cast<concepts::Requirement::SubstitutionDiagnostic *>(TransExpr),
2820 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2821}
2822
2824TemplateInstantiator::TransformNestedRequirement(
2826 if (!Req->isDependent() && !AlwaysRebuild())
2827 return Req;
2828 if (Req->hasInvalidConstraint()) {
2829 if (AlwaysRebuild())
2830 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2832 return Req;
2833 }
2835 Req->getConstraintExpr()->getBeginLoc(), Req,
2838 if (!getEvaluateConstraints()) {
2839 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2840 if (TransConstraint.isInvalid() || !TransConstraint.get())
2841 return nullptr;
2842 if (TransConstraint.get()->isInstantiationDependent())
2843 return new (SemaRef.Context)
2844 concepts::NestedRequirement(TransConstraint.get());
2845 ConstraintSatisfaction Satisfaction;
2847 SemaRef.Context, TransConstraint.get(), Satisfaction);
2848 }
2849
2850 ExprResult TransConstraint;
2851 ConstraintSatisfaction Satisfaction;
2853 {
2858 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2860 if (ConstrInst.isInvalid())
2861 return nullptr;
2864 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2865 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2866 !Result.empty())
2867 TransConstraint = Result[0];
2868 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2869 "by CheckConstraintSatisfaction.");
2870 }
2872 if (TransConstraint.isUsable() &&
2873 TransConstraint.get()->isInstantiationDependent())
2874 return new (C) concepts::NestedRequirement(TransConstraint.get());
2875 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2876 Satisfaction.HasSubstitutionFailure()) {
2877 SmallString<128> Entity;
2878 llvm::raw_svector_ostream OS(Entity);
2879 Req->getConstraintExpr()->printPretty(OS, nullptr,
2881 return new (C) concepts::NestedRequirement(
2882 SemaRef.Context, C.backupStr(Entity), Satisfaction);
2883 }
2884 return new (C)
2885 concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction);
2886}
2887
2891 DeclarationName Entity,
2892 bool AllowDeducedTST) {
2893 assert(!CodeSynthesisContexts.empty() &&
2894 "Cannot perform an instantiation without some context on the "
2895 "instantiation stack");
2896
2897 if (!T->getType()->isInstantiationDependentType() &&
2898 !T->getType()->isVariablyModifiedType())
2899 return T;
2900
2901 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2902 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2903 : Instantiator.TransformType(T);
2904}
2905
2909 DeclarationName Entity) {
2910 assert(!CodeSynthesisContexts.empty() &&
2911 "Cannot perform an instantiation without some context on the "
2912 "instantiation stack");
2913
2914 if (TL.getType().isNull())
2915 return nullptr;
2916
2919 // FIXME: Make a copy of the TypeLoc data here, so that we can
2920 // return a new TypeSourceInfo. Inefficient!
2921 TypeLocBuilder TLB;
2922 TLB.pushFullCopy(TL);
2923 return TLB.getTypeSourceInfo(Context, TL.getType());
2924 }
2925
2926 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2927 TypeLocBuilder TLB;
2928 TLB.reserve(TL.getFullDataSize());
2929 QualType Result = Instantiator.TransformType(TLB, TL);
2930 if (Result.isNull())
2931 return nullptr;
2932
2933 return TLB.getTypeSourceInfo(Context, Result);
2934}
2935
2936/// Deprecated form of the above.
2938 const MultiLevelTemplateArgumentList &TemplateArgs,
2940 bool *IsIncompleteSubstitution) {
2941 assert(!CodeSynthesisContexts.empty() &&
2942 "Cannot perform an instantiation without some context on the "
2943 "instantiation stack");
2944
2945 // If T is not a dependent type or a variably-modified type, there
2946 // is nothing to do.
2948 return T;
2949
2950 TemplateInstantiator Instantiator(
2951 *this, TemplateArgs, Loc, Entity,
2952 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2953 QualType QT = Instantiator.TransformType(T);
2954 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2955 *IsIncompleteSubstitution = true;
2956 return QT;
2957}
2958
2960 if (T->getType()->isInstantiationDependentType() ||
2961 T->getType()->isVariablyModifiedType())
2962 return true;
2963
2964 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2965 if (!TL.getAs<FunctionProtoTypeLoc>())
2966 return false;
2967
2969 for (ParmVarDecl *P : FP.getParams()) {
2970 // This must be synthesized from a typedef.
2971 if (!P) continue;
2972
2973 // If there are any parameters, a new TypeSourceInfo that refers to the
2974 // instantiated parameters must be built.
2975 return true;
2976 }
2977
2978 return false;
2979}
2980
2984 DeclarationName Entity,
2985 CXXRecordDecl *ThisContext,
2986 Qualifiers ThisTypeQuals,
2987 bool EvaluateConstraints) {
2988 assert(!CodeSynthesisContexts.empty() &&
2989 "Cannot perform an instantiation without some context on the "
2990 "instantiation stack");
2991
2993 return T;
2994
2995 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2996 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2997
2998 TypeLocBuilder TLB;
2999
3000 TypeLoc TL = T->getTypeLoc();
3001 TLB.reserve(TL.getFullDataSize());
3002
3004
3005 if (FunctionProtoTypeLoc Proto =
3007 // Instantiate the type, other than its exception specification. The
3008 // exception specification is instantiated in InitFunctionInstantiation
3009 // once we've built the FunctionDecl.
3010 // FIXME: Set the exception specification to EST_Uninstantiated here,
3011 // instead of rebuilding the function type again later.
3012 Result = Instantiator.TransformFunctionProtoType(
3013 TLB, Proto, ThisContext, ThisTypeQuals,
3015 bool &Changed) { return false; });
3016 } else {
3017 Result = Instantiator.TransformType(TLB, TL);
3018 }
3019 // When there are errors resolving types, clang may use IntTy as a fallback,
3020 // breaking our assumption that function declarations have function types.
3021 if (Result.isNull() || !Result->isFunctionType())
3022 return nullptr;
3023
3024 return TLB.getTypeSourceInfo(Context, Result);
3025}
3026
3029 SmallVectorImpl<QualType> &ExceptionStorage,
3030 const MultiLevelTemplateArgumentList &Args) {
3031 bool Changed = false;
3032 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3033 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3034 Changed);
3035}
3036
3038 const MultiLevelTemplateArgumentList &Args) {
3041
3042 SmallVector<QualType, 4> ExceptionStorage;
3044 ESI, ExceptionStorage, Args))
3045 // On error, recover by dropping the exception specification.
3046 ESI.Type = EST_None;
3047
3048 UpdateExceptionSpec(New, ESI);
3049}
3050
3051namespace {
3052
3053 struct GetContainedInventedTypeParmVisitor :
3054 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3055 TemplateTypeParmDecl *> {
3056 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3057 TemplateTypeParmDecl *>::Visit;
3058
3060 if (T.isNull())
3061 return nullptr;
3062 return Visit(T.getTypePtr());
3063 }
3064 // The deduced type itself.
3065 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3066 const TemplateTypeParmType *T) {
3067 if (!T->getDecl() || !T->getDecl()->isImplicit())
3068 return nullptr;
3069 return T->getDecl();
3070 }
3071
3072 // Only these types can contain 'auto' types, and subsequently be replaced
3073 // by references to invented parameters.
3074
3075 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
3076 return Visit(T->getNamedType());
3077 }
3078
3079 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3080 return Visit(T->getPointeeType());
3081 }
3082
3083 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3084 return Visit(T->getPointeeType());
3085 }
3086
3087 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3088 return Visit(T->getPointeeTypeAsWritten());
3089 }
3090
3091 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3092 return Visit(T->getPointeeType());
3093 }
3094
3095 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3096 return Visit(T->getElementType());
3097 }
3098
3099 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3101 return Visit(T->getElementType());
3102 }
3103
3104 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3105 return Visit(T->getElementType());
3106 }
3107
3108 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3109 return VisitFunctionType(T);
3110 }
3111
3112 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3113 return Visit(T->getReturnType());
3114 }
3115
3116 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3117 return Visit(T->getInnerType());
3118 }
3119
3120 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3121 return Visit(T->getModifiedType());
3122 }
3123
3124 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3125 return Visit(T->getUnderlyingType());
3126 }
3127
3128 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3129 return Visit(T->getOriginalType());
3130 }
3131
3132 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3133 return Visit(T->getPattern());
3134 }
3135 };
3136
3137} // namespace
3138
3139namespace {
3140
3141struct ExpandPackedTypeConstraints
3142 : TreeTransform<ExpandPackedTypeConstraints> {
3143
3145
3146 const MultiLevelTemplateArgumentList &TemplateArgs;
3147
3148 ExpandPackedTypeConstraints(
3149 Sema &SemaRef, const MultiLevelTemplateArgumentList &TemplateArgs)
3150 : inherited(SemaRef), TemplateArgs(TemplateArgs) {}
3151
3152 using inherited::TransformTemplateTypeParmType;
3153
3154 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
3155 TemplateTypeParmTypeLoc TL, bool) {
3156 const TemplateTypeParmType *T = TL.getTypePtr();
3157 if (!T->isParameterPack()) {
3160 NewTL.setNameLoc(TL.getNameLoc());
3161 return TL.getType();
3162 }
3163
3164 assert(SemaRef.ArgumentPackSubstitutionIndex != -1);
3165
3166 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
3167
3168 std::optional<unsigned> PackIndex;
3169 if (Arg.getKind() == TemplateArgument::Pack)
3170 PackIndex = Arg.pack_size() - 1 - SemaRef.ArgumentPackSubstitutionIndex;
3171
3173 TL.getType(), T->getDecl(), T->getIndex(), PackIndex,
3174 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace);
3177 NewTL.setNameLoc(TL.getNameLoc());
3178 return Result;
3179 }
3180
3181 QualType TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
3184 if (T->getPackIndex()) {
3187 TypeLoc.setNameLoc(TL.getNameLoc());
3188 return TypeLoc.getType();
3189 }
3190 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
3191 }
3192
3193 bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3195 return inherited::TransformTemplateArguments(Args.begin(), Args.end(), Out);
3196 }
3197};
3198
3199} // namespace
3200
3202 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3203 const MultiLevelTemplateArgumentList &TemplateArgs,
3204 bool EvaluateConstraints) {
3205 const ASTTemplateArgumentListInfo *TemplArgInfo =
3207
3208 if (!EvaluateConstraints) {
3209 bool ShouldExpandExplicitTemplateArgs =
3210 TemplArgInfo && ArgumentPackSubstitutionIndex != -1 &&
3211 llvm::any_of(TemplArgInfo->arguments(), [](auto &Arg) {
3212 return Arg.getArgument().containsUnexpandedParameterPack();
3213 });
3214
3215 // We want to transform the packs into Subst* nodes for type constraints
3216 // inside a pack expansion. For example,
3217 //
3218 // template <class... Ts> void foo() {
3219 // bar([](C<Ts> auto value) {}...);
3220 // }
3221 //
3222 // As we expand Ts in the process of instantiating foo(), and retain
3223 // the original template depths of Ts until the constraint evaluation, we
3224 // would otherwise have no chance to expand Ts by the time of evaluating
3225 // C<auto, Ts>.
3226 //
3227 // So we form a Subst* node for Ts along with a proper substitution index
3228 // here, and substitute the node with a complete MLTAL later in evaluation.
3229 if (ShouldExpandExplicitTemplateArgs) {
3230 TemplateArgumentListInfo InstArgs;
3231 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3232 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3233 if (ExpandPackedTypeConstraints(*this, TemplateArgs)
3234 .SubstTemplateArguments(TemplArgInfo->arguments(), InstArgs))
3235 return true;
3236
3237 // The type of the original parameter.
3238 auto *ConstraintExpr = TC->getImmediatelyDeclaredConstraint();
3239 QualType ConstrainedType;
3240
3241 if (auto *FE = dyn_cast<CXXFoldExpr>(ConstraintExpr)) {
3242 assert(FE->getLHS());
3243 ConstraintExpr = FE->getLHS();
3244 }
3245 auto *CSE = cast<ConceptSpecializationExpr>(ConstraintExpr);
3246 assert(!CSE->getTemplateArguments().empty() &&
3247 "Empty template arguments?");
3248 ConstrainedType = CSE->getTemplateArguments()[0].getAsType();
3249 assert(!ConstrainedType.isNull() &&
3250 "Failed to extract the original ConstrainedType?");
3251
3252 return AttachTypeConstraint(
3254 TC->getNamedConcept(),
3255 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs,
3256 Inst, ConstrainedType,
3257 Inst->isParameterPack()
3258 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3259 ->getEllipsisLoc()
3260 : SourceLocation());
3261 }
3264 return false;
3265 }
3266
3267 TemplateArgumentListInfo InstArgs;
3268
3269 if (TemplArgInfo) {
3270 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3271 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3272 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3273 InstArgs))
3274 return true;
3275 }
3276 return AttachTypeConstraint(
3278 TC->getNamedConcept(),
3279 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3281 Inst->isParameterPack()
3282 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3283 ->getEllipsisLoc()
3284 : SourceLocation());
3285}
3286
3288 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3289 int indexAdjustment, std::optional<unsigned> NumExpansions,
3290 bool ExpectParameterPack, bool EvaluateConstraint) {
3291 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3292 TypeSourceInfo *NewDI = nullptr;
3293
3294 TypeLoc OldTL = OldDI->getTypeLoc();
3295 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3296
3297 // We have a function parameter pack. Substitute into the pattern of the
3298 // expansion.
3299 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3300 OldParm->getLocation(), OldParm->getDeclName());
3301 if (!NewDI)
3302 return nullptr;
3303
3304 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3305 // We still have unexpanded parameter packs, which means that
3306 // our function parameter is still a function parameter pack.
3307 // Therefore, make its type a pack expansion type.
3308 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3309 NumExpansions);
3310 } else if (ExpectParameterPack) {
3311 // We expected to get a parameter pack but didn't (because the type
3312 // itself is not a pack expansion type), so complain. This can occur when
3313 // the substitution goes through an alias template that "loses" the
3314 // pack expansion.
3315 Diag(OldParm->getLocation(),
3316 diag::err_function_parameter_pack_without_parameter_packs)
3317 << NewDI->getType();
3318 return nullptr;
3319 }
3320 } else {
3321 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3322 OldParm->getDeclName());
3323 }
3324
3325 if (!NewDI)
3326 return nullptr;
3327
3328 if (NewDI->getType()->isVoidType()) {
3329 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3330 return nullptr;
3331 }
3332
3333 // In abbreviated templates, TemplateTypeParmDecls with possible
3334 // TypeConstraints are created when the parameter list is originally parsed.
3335 // The TypeConstraints can therefore reference other functions parameters in
3336 // the abbreviated function template, which is why we must instantiate them
3337 // here, when the instantiated versions of those referenced parameters are in
3338 // scope.
3339 if (TemplateTypeParmDecl *TTP =
3340 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3341 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3342 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3343 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3344 // We will first get here when instantiating the abbreviated function
3345 // template's described function, but we might also get here later.
3346 // Make sure we do not instantiate the TypeConstraint more than once.
3347 if (Inst && !Inst->getTypeConstraint()) {
3348 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3349 return nullptr;
3350 }
3351 }
3352 }
3353
3355 OldParm->getInnerLocStart(),
3356 OldParm->getLocation(),
3357 OldParm->getIdentifier(),
3358 NewDI->getType(), NewDI,
3359 OldParm->getStorageClass());
3360 if (!NewParm)
3361 return nullptr;
3362
3363 // Mark the (new) default argument as uninstantiated (if any).
3364 if (OldParm->hasUninstantiatedDefaultArg()) {
3365 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3366 NewParm->setUninstantiatedDefaultArg(Arg);
3367 } else if (OldParm->hasUnparsedDefaultArg()) {
3368 NewParm->setUnparsedDefaultArg();
3369 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3370 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3371 // Default arguments cannot be substituted until the declaration context
3372 // for the associated function or lambda capture class is available.
3373 // This is necessary for cases like the following where construction of
3374 // the lambda capture class for the outer lambda is dependent on the
3375 // parameter types but where the default argument is dependent on the
3376 // outer lambda's declaration context.
3377 // template <typename T>
3378 // auto f() {
3379 // return [](T = []{ return T{}; }()) { return 0; };
3380 // }
3381 NewParm->setUninstantiatedDefaultArg(Arg);
3382 }
3383
3387
3388 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3389 // Add the new parameter to the instantiated parameter pack.
3391 } else {
3392 // Introduce an Old -> New mapping
3394 }
3395
3396 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3397 // can be anything, is this right ?
3398 NewParm->setDeclContext(CurContext);
3399
3400 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3401 OldParm->getFunctionScopeIndex() + indexAdjustment);
3402
3403 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3404
3405 return NewParm;
3406}
3407
3410 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3411 const MultiLevelTemplateArgumentList &TemplateArgs,
3412 SmallVectorImpl<QualType> &ParamTypes,
3414 ExtParameterInfoBuilder &ParamInfos) {
3415 assert(!CodeSynthesisContexts.empty() &&
3416 "Cannot perform an instantiation without some context on the "
3417 "instantiation stack");
3418
3419 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3420 DeclarationName());
3421 return Instantiator.TransformFunctionTypeParams(
3422 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3423}
3424
3427 ParmVarDecl *Param,
3428 const MultiLevelTemplateArgumentList &TemplateArgs,
3429 bool ForCallExpr) {
3430 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3431 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3432
3435
3436 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3437 if (Inst.isInvalid())
3438 return true;
3439 if (Inst.isAlreadyInstantiating()) {
3440 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3441 Param->setInvalidDecl();
3442 return true;
3443 }
3444
3446 {
3447 // C++ [dcl.fct.default]p5:
3448 // The names in the [default argument] expression are bound, and
3449 // the semantic constraints are checked, at the point where the
3450 // default argument expression appears.
3451 ContextRAII SavedContext(*this, FD);
3452 std::unique_ptr<LocalInstantiationScope> LIS;
3453
3454 if (ForCallExpr) {
3455 // When instantiating a default argument due to use in a call expression,
3456 // an instantiation scope that includes the parameters of the callee is
3457 // required to satisfy references from the default argument. For example:
3458 // template<typename T> void f(T a, int = decltype(a)());
3459 // void g() { f(0); }
3460 LIS = std::make_unique<LocalInstantiationScope>(*this);
3462 /*ForDefinition*/ false);
3463 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3464 return true;
3465 }
3466
3468 Result = SubstInitializer(PatternExpr, TemplateArgs,
3469 /*DirectInit*/ false);
3470 });
3471 }
3472 if (Result.isInvalid())
3473 return true;
3474
3475 if (ForCallExpr) {
3476 // Check the expression as an initializer for the parameter.
3477 InitializedEntity Entity
3480 Param->getLocation(),
3481 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3482 Expr *ResultE = Result.getAs<Expr>();
3483
3484 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3485 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3486 if (Result.isInvalid())
3487 return true;
3488
3489 Result =
3491 /*DiscardedValue*/ false);
3492 } else {
3493 // FIXME: Obtain the source location for the '=' token.
3494 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3495 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3496 }
3497 if (Result.isInvalid())
3498 return true;
3499
3500 // Remember the instantiated default argument.
3501 Param->setDefaultArg(Result.getAs<Expr>());
3502
3503 return false;
3504}
3505
3506bool
3508 CXXRecordDecl *Pattern,
3509 const MultiLevelTemplateArgumentList &TemplateArgs) {
3510 bool Invalid = false;
3511 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3512 for (const auto &Base : Pattern->bases()) {
3513 if (!Base.getType()->isDependentType()) {
3514 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3515 if (RD->isInvalidDecl())
3516 Instantiation->setInvalidDecl();
3517 }
3518 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3519 continue;
3520 }
3521
3522 SourceLocation EllipsisLoc;
3523 TypeSourceInfo *BaseTypeLoc;
3524 if (Base.isPackExpansion()) {
3525 // This is a pack expansion. See whether we should expand it now, or
3526 // wait until later.
3528 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3529 Unexpanded);
3530 bool ShouldExpand = false;
3531 bool RetainExpansion = false;
3532 std::optional<unsigned> NumExpansions;
3533 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3534 Base.getSourceRange(),
3535 Unexpanded,
3536 TemplateArgs, ShouldExpand,
3537 RetainExpansion,
3538 NumExpansions)) {
3539 Invalid = true;
3540 continue;
3541 }
3542
3543 // If we should expand this pack expansion now, do so.
3544 if (ShouldExpand) {
3545 for (unsigned I = 0; I != *NumExpansions; ++I) {
3546 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3547
3548 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3549 TemplateArgs,
3550 Base.getSourceRange().getBegin(),
3551 DeclarationName());
3552 if (!BaseTypeLoc) {
3553 Invalid = true;
3554 continue;
3555 }
3556
3557 if (CXXBaseSpecifier *InstantiatedBase
3558 = CheckBaseSpecifier(Instantiation,
3559 Base.getSourceRange(),
3560 Base.isVirtual(),
3561 Base.getAccessSpecifierAsWritten(),
3562 BaseTypeLoc,
3563 SourceLocation()))
3564 InstantiatedBases.push_back(InstantiatedBase);
3565 else
3566 Invalid = true;
3567 }
3568
3569 continue;
3570 }
3571
3572 // The resulting base specifier will (still) be a pack expansion.
3573 EllipsisLoc = Base.getEllipsisLoc();
3574 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3575 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3576 TemplateArgs,
3577 Base.getSourceRange().getBegin(),
3578 DeclarationName());
3579 } else {
3580 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3581 TemplateArgs,
3582 Base.getSourceRange().getBegin(),
3583 DeclarationName());
3584 }
3585
3586 if (!BaseTypeLoc) {
3587 Invalid = true;
3588 continue;
3589 }
3590
3591 if (CXXBaseSpecifier *InstantiatedBase
3592 = CheckBaseSpecifier(Instantiation,
3593 Base.getSourceRange(),
3594 Base.isVirtual(),
3595 Base.getAccessSpecifierAsWritten(),
3596 BaseTypeLoc,
3597 EllipsisLoc))
3598 InstantiatedBases.push_back(InstantiatedBase);
3599 else
3600 Invalid = true;
3601 }
3602
3603 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3604 Invalid = true;
3605
3606 return Invalid;
3607}
3608
3609// Defined via #include from SemaTemplateInstantiateDecl.cpp
3610namespace clang {
3611 namespace sema {
3613 const MultiLevelTemplateArgumentList &TemplateArgs);
3615 const Attr *At, ASTContext &C, Sema &S,
3616 const MultiLevelTemplateArgumentList &TemplateArgs);
3617 }
3618}
3619
3620bool
3622 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3623 const MultiLevelTemplateArgumentList &TemplateArgs,
3625 bool Complain) {
3626 CXXRecordDecl *PatternDef
3627 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3628 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3629 Instantiation->getInstantiatedFromMemberClass(),
3630 Pattern, PatternDef, TSK, Complain))
3631 return true;
3632
3633 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3634 llvm::TimeTraceMetadata M;
3635 llvm::raw_string_ostream OS(M.Detail);
3636 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3637 /*Qualified=*/true);
3638 if (llvm::isTimeTraceVerbose()) {
3639 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3640 M.File = SourceMgr.getFilename(Loc);
3642 }
3643 return M;
3644 });
3645
3646 Pattern = PatternDef;
3647
3648 // Record the point of instantiation.
3649 if (MemberSpecializationInfo *MSInfo
3650 = Instantiation->getMemberSpecializationInfo()) {
3651 MSInfo->setTemplateSpecializationKind(TSK);
3652 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3653 } else if (ClassTemplateSpecializationDecl *Spec
3654 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3655 Spec->setTemplateSpecializationKind(TSK);
3656 Spec->setPointOfInstantiation(PointOfInstantiation);
3657 }
3658
3659 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3660 if (Inst.isInvalid())
3661 return true;
3662 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3663 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3664 "instantiating class definition");
3665
3666 // Enter the scope of this instantiation. We don't use
3667 // PushDeclContext because we don't have a scope.
3668 ContextRAII SavedContext(*this, Instantiation);
3671
3672 // If this is an instantiation of a local class, merge this local
3673 // instantiation scope with the enclosing scope. Otherwise, every
3674 // instantiation of a class has its own local instantiation scope.
3675 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3676 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3677
3678 // Some class state isn't processed immediately but delayed till class
3679 // instantiation completes. We may not be ready to handle any delayed state
3680 // already on the stack as it might correspond to a different class, so save
3681 // it now and put it back later.
3682 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3683
3684 // Pull attributes from the pattern onto the instantiation.
3685 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3686
3687 // Start the definition of this instantiation.
3688 Instantiation->startDefinition();
3689
3690 // The instantiation is visible here, even if it was first declared in an
3691 // unimported module.
3692 Instantiation->setVisibleDespiteOwningModule();
3693
3694 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3695 Instantiation->setTagKind(Pattern->getTagKind());
3696
3697 // Do substitution on the base class specifiers.
3698 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3699 Instantiation->setInvalidDecl();
3700
3701 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3702 Instantiator.setEvaluateConstraints(false);
3703 SmallVector<Decl*, 4> Fields;
3704 // Delay instantiation of late parsed attributes.
3705 LateInstantiatedAttrVec LateAttrs;
3706 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3707
3708 bool MightHaveConstexprVirtualFunctions = false;
3709 for (auto *Member : Pattern->decls()) {
3710 // Don't instantiate members not belonging in this semantic context.
3711 // e.g. for:
3712 // @code
3713 // template <int i> class A {
3714 // class B *g;
3715 // };
3716 // @endcode
3717 // 'class B' has the template as lexical context but semantically it is
3718 // introduced in namespace scope.
3719 if (Member->getDeclContext() != Pattern)
3720 continue;
3721
3722 // BlockDecls can appear in a default-member-initializer. They must be the
3723 // child of a BlockExpr, so we only know how to instantiate them from there.
3724 // Similarly, lambda closure types are recreated when instantiating the
3725 // corresponding LambdaExpr.
3726 if (isa<BlockDecl>(Member) ||
3727 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3728 continue;
3729
3730 if (Member->isInvalidDecl()) {
3731 Instantiation->setInvalidDecl();
3732 continue;
3733 }
3734
3735 Decl *NewMember = Instantiator.Visit(Member);
3736 if (NewMember) {
3737 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3738 Fields.push_back(Field);
3739 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3740 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3741 // specialization causes the implicit instantiation of the definitions
3742 // of unscoped member enumerations.
3743 // Record a point of instantiation for this implicit instantiation.
3744 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3745 Enum->isCompleteDefinition()) {
3746 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3747 assert(MSInfo && "no spec info for member enum specialization");
3749 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3750 }
3751 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3752 if (SA->isFailed()) {
3753 // A static_assert failed. Bail out; instantiating this
3754 // class is probably not meaningful.
3755 Instantiation->setInvalidDecl();
3756 break;
3757 }
3758 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3759 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3760 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3761 MightHaveConstexprVirtualFunctions = true;
3762 }
3763
3764 if (NewMember->isInvalidDecl())
3765 Instantiation->setInvalidDecl();
3766 } else {
3767 // FIXME: Eventually, a NULL return will mean that one of the
3768 // instantiations was a semantic disaster, and we'll want to mark the
3769 // declaration invalid.
3770 // For now, we expect to skip some members that we can't yet handle.
3771 }
3772 }
3773
3774 // Finish checking fields.
3775 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3777 CheckCompletedCXXClass(nullptr, Instantiation);
3778
3779 // Default arguments are parsed, if not instantiated. We can go instantiate
3780 // default arg exprs for default constructors if necessary now. Unless we're
3781 // parsing a class, in which case wait until that's finished.
3782 if (ParsingClassDepth == 0)
3784
3785 // Instantiate late parsed attributes, and attach them to their decls.
3786 // See Sema::InstantiateAttrs
3787 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3788 E = LateAttrs.end(); I != E; ++I) {
3789 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3790 CurrentInstantiationScope = I->Scope;
3791
3792 // Allow 'this' within late-parsed attributes.
3793 auto *ND = cast<NamedDecl>(I->NewDecl);
3794 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3795 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3796 ND->isCXXInstanceMember());
3797
3798 Attr *NewAttr =
3799 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3800 if (NewAttr)
3801 I->NewDecl->addAttr(NewAttr);
3803 Instantiator.getStartingScope());
3804 }
3805 Instantiator.disableLateAttributeInstantiation();
3806 LateAttrs.clear();
3807
3809
3810 // FIXME: We should do something similar for explicit instantiations so they
3811 // end up in the right module.
3812 if (TSK == TSK_ImplicitInstantiation) {
3813 Instantiation->setLocation(Pattern->getLocation());
3814 Instantiation->setLocStart(Pattern->getInnerLocStart());
3815 Instantiation->setBraceRange(Pattern->getBraceRange());
3816 }
3817
3818 if (!Instantiation->isInvalidDecl()) {
3819 // Perform any dependent diagnostics from the pattern.
3820 if (Pattern->isDependentContext())
3821 PerformDependentDiagnostics(Pattern, TemplateArgs);
3822
3823 // Instantiate any out-of-line class template partial
3824 // specializations now.
3826 P = Instantiator.delayed_partial_spec_begin(),
3827 PEnd = Instantiator.delayed_partial_spec_end();
3828 P != PEnd; ++P) {
3830 P->first, P->second)) {
3831 Instantiation->setInvalidDecl();
3832 break;
3833 }
3834 }
3835
3836 // Instantiate any out-of-line variable template partial
3837 // specializations now.
3839 P = Instantiator.delayed_var_partial_spec_begin(),
3840 PEnd = Instantiator.delayed_var_partial_spec_end();
3841 P != PEnd; ++P) {
3843 P->first, P->second)) {
3844 Instantiation->setInvalidDecl();
3845 break;
3846 }
3847 }
3848 }
3849
3850 // Exit the scope of this instantiation.
3851 SavedContext.pop();
3852
3853 if (!Instantiation->isInvalidDecl()) {
3854 // Always emit the vtable for an explicit instantiation definition
3855 // of a polymorphic class template specialization. Otherwise, eagerly
3856 // instantiate only constexpr virtual functions in preparation for their use
3857 // in constant evaluation.
3859 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3860 else if (MightHaveConstexprVirtualFunctions)
3861 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3862 /*ConstexprOnly*/ true);
3863 }
3864
3865 Consumer.HandleTagDeclDefinition(Instantiation);
3866
3867 return Instantiation->isInvalidDecl();
3868}
3869
3870bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3871 EnumDecl *Instantiation, EnumDecl *Pattern,
3872 const MultiLevelTemplateArgumentList &TemplateArgs,
3874 EnumDecl *PatternDef = Pattern->getDefinition();
3875 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3876 Instantiation->getInstantiatedFromMemberEnum(),
3877 Pattern, PatternDef, TSK,/*Complain*/true))
3878 return true;
3879 Pattern = PatternDef;
3880
3881 // Record the point of instantiation.
3882 if (MemberSpecializationInfo *MSInfo
3883 = Instantiation->getMemberSpecializationInfo()) {
3884 MSInfo->setTemplateSpecializationKind(TSK);
3885 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3886 }
3887
3888 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3889 if (Inst.isInvalid())
3890 return true;
3891 if (Inst.isAlreadyInstantiating())
3892 return false;
3893 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3894 "instantiating enum definition");
3895
3896 // The instantiation is visible here, even if it was first declared in an
3897 // unimported module.
3898 Instantiation->setVisibleDespiteOwningModule();
3899
3900 // Enter the scope of this instantiation. We don't use
3901 // PushDeclContext because we don't have a scope.
3902 ContextRAII SavedContext(*this, Instantiation);
3905
3906 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3907
3908 // Pull attributes from the pattern onto the instantiation.
3909 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3910
3911 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3912 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3913
3914 // Exit the scope of this instantiation.
3915 SavedContext.pop();
3916
3917 return Instantiation->isInvalidDecl();
3918}
3919
3921 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3922 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3923 // If there is no initializer, we don't need to do anything.
3924 if (!Pattern->hasInClassInitializer())
3925 return false;
3926
3927 assert(Instantiation->getInClassInitStyle() ==
3928 Pattern->getInClassInitStyle() &&
3929 "pattern and instantiation disagree about init style");
3930
3931 // Error out if we haven't parsed the initializer of the pattern yet because
3932 // we are waiting for the closing brace of the outer class.
3933 Expr *OldInit = Pattern->getInClassInitializer();
3934 if (!OldInit) {
3935 RecordDecl *PatternRD = Pattern->getParent();
3936 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3937 Diag(PointOfInstantiation,
3938 diag::err_default_member_initializer_not_yet_parsed)
3939 << OutermostClass << Pattern;
3940 Diag(Pattern->getEndLoc(),
3941 diag::note_default_member_initializer_not_yet_parsed);
3942 Instantiation->setInvalidDecl();
3943 return true;
3944 }
3945
3946 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3947 if (Inst.isInvalid())
3948 return true;
3949 if (Inst.isAlreadyInstantiating()) {
3950 // Error out if we hit an instantiation cycle for this initializer.
3951 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3952 << Instantiation;
3953 return true;
3954 }
3955 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3956 "instantiating default member init");
3957
3958 // Enter the scope of this instantiation. We don't use PushDeclContext because
3959 // we don't have a scope.
3960 ContextRAII SavedContext(*this, Instantiation->getParent());
3963 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3964 PointOfInstantiation, Instantiation, CurContext};
3965
3966 LocalInstantiationScope Scope(*this, true);
3967
3968 // Instantiate the initializer.
3970 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3971
3972 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3973 /*CXXDirectInit=*/false);
3974 Expr *Init = NewInit.get();
3975 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3977 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3978
3979 if (auto *L = getASTMutationListener())
3980 L->DefaultMemberInitializerInstantiated(Instantiation);
3981
3982 // Return true if the in-class initializer is still missing.
3983 return !Instantiation->getInClassInitializer();
3984}
3985
3986namespace {
3987 /// A partial specialization whose template arguments have matched
3988 /// a given template-id.
3989 struct PartialSpecMatchResult {
3992 };
3993}
3994
3997 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3999 return true;
4000
4002 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
4003 CTD->getPartialSpecializations(PartialSpecs);
4004 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
4005 // C++ [temp.spec.partial.member]p2:
4006 // If the primary member template is explicitly specialized for a given
4007 // (implicit) specialization of the enclosing class template, the partial
4008 // specializations of the member template are ignored for this
4009 // specialization of the enclosing class template. If a partial
4010 // specialization of the member template is explicitly specialized for a
4011 // given (implicit) specialization of the enclosing class template, the
4012 // primary member template and its other partial specializations are still
4013 // considered for this specialization of the enclosing class template.
4015 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
4016 continue;
4017
4019 if (DeduceTemplateArguments(CTPSD,
4020 ClassTemplateSpec->getTemplateArgs().asArray(),
4022 return true;
4023 }
4024
4025 return false;
4026}
4027
4028/// Get the instantiation pattern to use to instantiate the definition of a
4029/// given ClassTemplateSpecializationDecl (either the pattern of the primary
4030/// template or of a partial specialization).
4032 Sema &S, SourceLocation PointOfInstantiation,
4033 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4035 bool PrimaryHasMatchedPackOnParmToNonPackOnArg) {
4036 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
4037 if (Inst.isInvalid())
4038 return {/*Invalid=*/true};
4039 if (Inst.isAlreadyInstantiating())
4040 return {/*Invalid=*/false};
4041
4042 llvm::PointerUnion<ClassTemplateDecl *,
4044 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4045 if (!isa<ClassTemplatePartialSpecializationDecl *>(Specialized)) {
4046 // Find best matching specialization.
4047 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4048
4049 // C++ [temp.class.spec.match]p1:
4050 // When a class template is used in a context that requires an
4051 // instantiation of the class, it is necessary to determine
4052 // whether the instantiation is to be generated using the primary
4053 // template or one of the partial specializations. This is done by
4054 // matching the template arguments of the class template
4055 // specialization with the template argument lists of the partial
4056 // specializations.
4057 typedef PartialSpecMatchResult MatchResult;
4058 SmallVector<MatchResult, 4> Matched, ExtraMatched;
4060 Template->getPartialSpecializations(PartialSpecs);
4061 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4062 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4063 // C++ [temp.spec.partial.member]p2:
4064 // If the primary member template is explicitly specialized for a given
4065 // (implicit) specialization of the enclosing class template, the
4066 // partial specializations of the member template are ignored for this
4067 // specialization of the enclosing class template. If a partial
4068 // specialization of the member template is explicitly specialized for a
4069 // given (implicit) specialization of the enclosing class template, the
4070 // primary member template and its other partial specializations are
4071 // still considered for this specialization of the enclosing class
4072 // template.
4073 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4074 !Partial->getMostRecentDecl()->isMemberSpecialization())
4075 continue;
4076
4077 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4079 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4081 // Store the failed-deduction information for use in diagnostics, later.
4082 // TODO: Actually use the failed-deduction info?
4083 FailedCandidates.addCandidate().set(
4084 DeclAccessPair::make(Template, AS_public), Partial,
4086 (void)Result;
4087 } else {
4088 auto &List =
4089 Info.hasMatchedPackOnParmToNonPackOnArg() ? ExtraMatched : Matched;
4090 List.push_back(MatchResult{Partial, Info.takeCanonical()});
4091 }
4092 }
4093 if (Matched.empty() && PrimaryHasMatchedPackOnParmToNonPackOnArg)
4094 Matched = std::move(ExtraMatched);
4095
4096 // If we're dealing with a member template where the template parameters
4097 // have been instantiated, this provides the original template parameters
4098 // from which the member template's parameters were instantiated.
4099
4100 if (Matched.size() >= 1) {
4101 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4102 if (Matched.size() == 1) {
4103 // -- If exactly one matching specialization is found, the
4104 // instantiation is generated from that specialization.
4105 // We don't need to do anything for this.
4106 } else {
4107 // -- If more than one matching specialization is found, the
4108 // partial order rules (14.5.4.2) are used to determine
4109 // whether one of the specializations is more specialized
4110 // than the others. If none of the specializations is more
4111 // specialized than all of the other matching
4112 // specializations, then the use of the class template is
4113 // ambiguous and the program is ill-formed.
4115 PEnd = Matched.end();
4116 P != PEnd; ++P) {
4118 P->Partial, Best->Partial, PointOfInstantiation) ==
4119 P->Partial)
4120 Best = P;
4121 }
4122
4123 // Determine if the best partial specialization is more specialized than
4124 // the others.
4125 bool Ambiguous = false;
4126 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4127 PEnd = Matched.end();
4128 P != PEnd; ++P) {
4130 P->Partial, Best->Partial,
4131 PointOfInstantiation) != Best->Partial) {
4132 Ambiguous = true;
4133 break;
4134 }
4135 }
4136
4137 if (Ambiguous) {
4138 // Partial ordering did not produce a clear winner. Complain.
4139 Inst.Clear();
4140 ClassTemplateSpec->setInvalidDecl();
4141 S.Diag(PointOfInstantiation,
4142 diag::err_partial_spec_ordering_ambiguous)
4143 << ClassTemplateSpec;
4144
4145 // Print the matching partial specializations.
4146 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4147 PEnd = Matched.end();
4148 P != PEnd; ++P)
4149 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4151 P->Partial->getTemplateParameters(), *P->Args);
4152
4153 return {/*Invalid=*/true};
4154 }
4155 }
4156
4157 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4158 } else {
4159 // -- If no matches are found, the instantiation is generated
4160 // from the primary template.
4161 }
4162 }
4163
4164 CXXRecordDecl *Pattern = nullptr;
4165 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4166 if (auto *PartialSpec =
4167 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4168 // Instantiate using the best class template partial specialization.
4169 while (PartialSpec->getInstantiatedFromMember()) {
4170 // If we've found an explicit specialization of this class template,
4171 // stop here and use that as the pattern.
4172 if (PartialSpec->isMemberSpecialization())
4173 break;
4174
4175 PartialSpec = PartialSpec->getInstantiatedFromMember();
4176 }
4177 Pattern = PartialSpec;
4178 } else {
4179 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4180 while (Template->getInstantiatedFromMemberTemplate()) {
4181 // If we've found an explicit specialization of this class template,
4182 // stop here and use that as the pattern.
4183 if (Template->isMemberSpecialization())
4184 break;
4185
4186 Template = Template->getInstantiatedFromMemberTemplate();
4187 }
4188 Pattern = Template->getTemplatedDecl();
4189 }
4190
4191 return Pattern;
4192}
4193
4195 SourceLocation PointOfInstantiation,
4196 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4197 TemplateSpecializationKind TSK, bool Complain,
4198 bool PrimaryHasMatchedPackOnParmToNonPackOnArg) {
4199 // Perform the actual instantiation on the canonical declaration.
4200 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4201 ClassTemplateSpec->getCanonicalDecl());
4202 if (ClassTemplateSpec->isInvalidDecl())
4203 return true;
4204
4207 *this, PointOfInstantiation, ClassTemplateSpec, TSK,
4208 PrimaryHasMatchedPackOnParmToNonPackOnArg);
4209 if (!Pattern.isUsable())
4210 return Pattern.isInvalid();
4211
4212 return InstantiateClass(
4213 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4214 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4215}
4216
4217void
4219 CXXRecordDecl *Instantiation,
4220 const MultiLevelTemplateArgumentList &TemplateArgs,
4222 // FIXME: We need to notify the ASTMutationListener that we did all of these
4223 // things, in case we have an explicit instantiation definition in a PCM, a
4224 // module, or preamble, and the declaration is in an imported AST.
4225 assert(
4228 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4229 "Unexpected template specialization kind!");
4230 for (auto *D : Instantiation->decls()) {
4231 bool SuppressNew = false;
4232 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4233 if (FunctionDecl *Pattern =
4234 Function->getInstantiatedFromMemberFunction()) {
4235
4236 if (Function->isIneligibleOrNotSelected())
4237 continue;
4238
4239 if (Function->getTrailingRequiresClause()) {
4240 ConstraintSatisfaction Satisfaction;
4241 if (CheckFunctionConstraints(Function, Satisfaction) ||
4242 !Satisfaction.IsSatisfied) {
4243 continue;
4244 }
4245 }
4246
4247 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4248 continue;
4249
4251 Function->getTemplateSpecializationKind();
4252 if (PrevTSK == TSK_ExplicitSpecialization)
4253 continue;
4254
4256 PointOfInstantiation, TSK, Function, PrevTSK,
4257 Function->getPointOfInstantiation(), SuppressNew) ||
4258 SuppressNew)
4259 continue;
4260
4261 // C++11 [temp.explicit]p8:
4262 // An explicit instantiation definition that names a class template
4263 // specialization explicitly instantiates the class template
4264 // specialization and is only an explicit instantiation definition
4265 // of members whose definition is visible at the point of
4266 // instantiation.
4267 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4268 continue;
4269
4270 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4271
4272 if (Function->isDefined()) {
4273 // Let the ASTConsumer know that this function has been explicitly
4274 // instantiated now, and its linkage might have changed.
4276 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4277 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4278 } else if (TSK == TSK_ImplicitInstantiation) {
4280 std::make_pair(Function, PointOfInstantiation));
4281 }
4282 }
4283 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4284 if (isa<VarTemplateSpecializationDecl>(Var))
4285 continue;
4286
4287 if (Var->isStaticDataMember()) {
4288 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4289 continue;
4290
4292 assert(MSInfo && "No member specialization information?");
4293 if (MSInfo->getTemplateSpecializationKind()
4295 continue;
4296
4297 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4298 Var,
4300 MSInfo->getPointOfInstantiation(),
4301 SuppressNew) ||
4302 SuppressNew)
4303 continue;
4304
4306 // C++0x [temp.explicit]p8:
4307 // An explicit instantiation definition that names a class template
4308 // specialization explicitly instantiates the class template
4309 // specialization and is only an explicit instantiation definition
4310 // of members whose definition is visible at the point of
4311 // instantiation.
4313 continue;
4314
4315 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4316 InstantiateVariableDefinition(PointOfInstantiation, Var);
4317 } else {
4318 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4319 }
4320 }
4321 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4322 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4323 continue;
4324
4325 // Always skip the injected-class-name, along with any
4326 // redeclarations of nested classes, since both would cause us
4327 // to try to instantiate the members of a class twice.
4328 // Skip closure types; they'll get instantiated when we instantiate
4329 // the corresponding lambda-expression.
4330 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4331 Record->isLambda())
4332 continue;
4333
4334 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4335 assert(MSInfo && "No member specialization information?");
4336
4337 if (MSInfo->getTemplateSpecializationKind()
4339 continue;
4340
4341 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4343 // On Windows, explicit instantiation decl of the outer class doesn't
4344 // affect the inner class. Typically extern template declarations are
4345 // used in combination with dll import/export annotations, but those
4346 // are not propagated from the outer class templates to inner classes.
4347 // Therefore, do not instantiate inner classes on this platform, so
4348 // that users don't end up with undefined symbols during linking.
4349 continue;
4350 }
4351
4352 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4353 Record,
4355 MSInfo->getPointOfInstantiation(),
4356 SuppressNew) ||
4357 SuppressNew)
4358 continue;
4359
4361 assert(Pattern && "Missing instantiated-from-template information");
4362
4363 if (!Record->getDefinition()) {
4364 if (!Pattern->getDefinition()) {
4365 // C++0x [temp.explicit]p8:
4366 // An explicit instantiation definition that names a class template
4367 // specialization explicitly instantiates the class template
4368 // specialization and is only an explicit instantiation definition
4369 // of members whose definition is visible at the point of
4370 // instantiation.
4372 MSInfo->setTemplateSpecializationKind(TSK);
4373 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4374 }
4375
4376 continue;
4377 }
4378
4379 InstantiateClass(PointOfInstantiation, Record, Pattern,
4380 TemplateArgs,
4381 TSK);
4382 } else {
4384 Record->getTemplateSpecializationKind() ==
4386 Record->setTemplateSpecializationKind(TSK);
4387 MarkVTableUsed(PointOfInstantiation, Record, true);
4388 }
4389 }
4390
4391 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4392 if (Pattern)
4393 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4394 TSK);
4395 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4396 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4397 assert(MSInfo && "No member specialization information?");
4398
4399 if (MSInfo->getTemplateSpecializationKind()
4401 continue;
4402
4404 PointOfInstantiation, TSK, Enum,
4406 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4407 SuppressNew)
4408 continue;
4409
4410 if (Enum->getDefinition())
4411 continue;
4412
4413 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4414 assert(Pattern && "Missing instantiated-from-template information");
4415
4417 if (!Pattern->getDefinition())
4418 continue;
4419
4420 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4421 } else {
4422 MSInfo->setTemplateSpecializationKind(TSK);
4423 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4424 }
4425 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4426 // No need to instantiate in-class initializers during explicit
4427 // instantiation.
4428 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4429 CXXRecordDecl *ClassPattern =
4430 Instantiation->getTemplateInstantiationPattern();
4432 ClassPattern->lookup(Field->getDeclName());
4433 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4434 assert(Pattern);
4435 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4436 TemplateArgs);
4437 }
4438 }
4439 }
4440}
4441
4442void
4444 SourceLocation PointOfInstantiation,
4445 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4447 // C++0x [temp.explicit]p7:
4448 // An explicit instantiation that names a class template
4449 // specialization is an explicit instantion of the same kind
4450 // (declaration or definition) of each of its members (not
4451 // including members inherited from base classes) that has not
4452 // been previously explicitly specialized in the translation unit
4453 // containing the explicit instantiation, except as described
4454 // below.
4455 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4456 getTemplateInstantiationArgs(ClassTemplateSpec),
4457 TSK);
4458}
4459
4462 if (!S)
4463 return S;
4464
4465 TemplateInstantiator Instantiator(*this, TemplateArgs,
4467 DeclarationName());
4468 return Instantiator.TransformStmt(S);
4469}
4470
4472 const TemplateArgumentLoc &Input,
4473 const MultiLevelTemplateArgumentList &TemplateArgs,
4475 const DeclarationName &Entity) {
4476 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4477 return Instantiator.TransformTemplateArgument(Input, Output);
4478}
4479
4482 const MultiLevelTemplateArgumentList &TemplateArgs,
4484 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4485 DeclarationName());
4486 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4487}
4488
4491 if (!E)
4492 return E;
4493
4494 TemplateInstantiator Instantiator(*this, TemplateArgs,
4496 DeclarationName());
4497 return Instantiator.TransformExpr(E);
4498}
4499
4502 const MultiLevelTemplateArgumentList &TemplateArgs) {
4503 // FIXME: should call SubstExpr directly if this function is equivalent or
4504 // should it be different?
4505 return SubstExpr(E, TemplateArgs);
4506}
4507
4509 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4510 if (!E)
4511 return E;
4512
4513 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4514 DeclarationName());
4515 Instantiator.setEvaluateConstraints(false);
4516 return Instantiator.TransformExpr(E);
4517}
4518
4520 const MultiLevelTemplateArgumentList &TemplateArgs,
4521 bool CXXDirectInit) {
4522 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4523 DeclarationName());
4524 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4525}
4526
4527bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4528 const MultiLevelTemplateArgumentList &TemplateArgs,
4529 SmallVectorImpl<Expr *> &Outputs) {
4530 if (Exprs.empty())
4531 return false;
4532
4533 TemplateInstantiator Instantiator(*this, TemplateArgs,
4535 DeclarationName());
4536 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4537 IsCall, Outputs);
4538}
4539
4542 const MultiLevelTemplateArgumentList &TemplateArgs) {
4543 if (!NNS)
4544 return NestedNameSpecifierLoc();
4545
4546 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4547 DeclarationName());
4548 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4549}
4550
4553 const MultiLevelTemplateArgumentList &TemplateArgs) {
4554 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4555 NameInfo.getName());
4556 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4557}
4558
4562 const MultiLevelTemplateArgumentList &TemplateArgs) {
4563 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4564 DeclarationName());
4565 CXXScopeSpec SS;
4566 SS.Adopt(QualifierLoc);
4567 return Instantiator.TransformTemplateName(SS, Name, Loc);
4568}
4569
4570static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4571 // When storing ParmVarDecls in the local instantiation scope, we always
4572 // want to use the ParmVarDecl from the canonical function declaration,
4573 // since the map is then valid for any redeclaration or definition of that
4574 // function.
4575 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4576 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4577 unsigned i = PV->getFunctionScopeIndex();
4578 // This parameter might be from a freestanding function type within the
4579 // function and isn't necessarily referring to one of FD's parameters.
4580 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4581 return FD->getCanonicalDecl()->getParamDecl(i);
4582 }
4583 }
4584 return D;
4585}
4586
4587
4588llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4591 for (LocalInstantiationScope *Current = this; Current;
4592 Current = Current->Outer) {
4593
4594 // Check if we found something within this scope.
4595 const Decl *CheckD = D;
4596 do {
4597 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4598 if (Found != Current->LocalDecls.end())
4599 return &Found->second;
4600
4601 // If this is a tag declaration, it's possible that we need to look for
4602 // a previous declaration.
4603 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4604 CheckD = Tag->getPreviousDecl();
4605 else
4606 CheckD = nullptr;
4607 } while (CheckD);
4608
4609 // If we aren't combined with our outer scope, we're done.
4610 if (!Current->CombineWithOuterScope)
4611 break;
4612 }
4613
4614 // If we're performing a partial substitution during template argument
4615 // deduction, we may not have values for template parameters yet.
4616 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4617 isa<TemplateTemplateParmDecl>(D))
4618 return nullptr;
4619
4620 // Local types referenced prior to definition may require instantiation.
4621 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4622 if (RD->isLocalClass())
4623 return nullptr;
4624
4625 // Enumeration types referenced prior to definition may appear as a result of
4626 // error recovery.
4627 if (isa<EnumDecl>(D))
4628 return nullptr;
4629
4630 // Materialized typedefs/type alias for implicit deduction guides may require
4631 // instantiation.
4632 if (isa<TypedefNameDecl>(D) &&
4633 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4634 return nullptr;
4635
4636 // If we didn't find the decl, then we either have a sema bug, or we have a
4637 // forward reference to a label declaration. Return null to indicate that
4638 // we have an uninstantiated label.
4639 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4640 return nullptr;
4641}
4642
4645 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4646 if (Stored.isNull()) {
4647#ifndef NDEBUG
4648 // It should not be present in any surrounding scope either.
4649 LocalInstantiationScope *Current = this;
4650 while (Current->CombineWithOuterScope && Current->Outer) {
4651 Current = Current->Outer;
4652 assert(!Current->LocalDecls.contains(D) &&
4653 "Instantiated local in inner and outer scopes");
4654 }
4655#endif
4656 Stored = Inst;
4657 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4658 Pack->push_back(cast<VarDecl>(Inst));
4659 } else {
4660 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4661 }
4662}
4663
4665 VarDecl *Inst) {
4667 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4668 Pack->push_back(Inst);
4669}
4670
4672#ifndef NDEBUG
4673 // This should be the first time we've been told about this decl.
4674 for (LocalInstantiationScope *Current = this;
4675 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4676 assert(!Current->LocalDecls.contains(D) &&
4677 "Creating local pack after instantiation of local");
4678#endif
4679
4681 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4683 Stored = Pack;
4684 ArgumentPacks.push_back(Pack);
4685}
4686
4688 for (DeclArgumentPack *Pack : ArgumentPacks)
4689 if (llvm::is_contained(*Pack, D))
4690 return true;
4691 return false;
4692}
4693
4695 const TemplateArgument *ExplicitArgs,
4696 unsigned NumExplicitArgs) {
4697 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4698 "Already have a partially-substituted pack");
4699 assert((!PartiallySubstitutedPack
4700 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4701 "Wrong number of arguments in partially-substituted pack");
4702 PartiallySubstitutedPack = Pack;
4703 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4704 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4705}
4706
4708 const TemplateArgument **ExplicitArgs,
4709 unsigned *NumExplicitArgs) const {
4710 if (ExplicitArgs)
4711 *ExplicitArgs = nullptr;
4712 if (NumExplicitArgs)
4713 *NumExplicitArgs = 0;
4714
4715 for (const LocalInstantiationScope *Current = this; Current;
4716 Current = Current->Outer) {
4717 if (Current->PartiallySubstitutedPack) {
4718 if (ExplicitArgs)
4719 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4720 if (NumExplicitArgs)
4721 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4722
4723 return Current->PartiallySubstitutedPack;
4724 }
4725
4726 if (!Current->CombineWithOuterScope)
4727 break;
4728 }
4729
4730 return nullptr;
4731}
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:1136
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
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:1372
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
bool isFileContext() const
Definition: DeclBase.h:2175
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1866
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2036
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2364
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:1226
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:792
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:777
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:786
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
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:1493
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:873
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:654
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:4956
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4982
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:4599
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:4138
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4187
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:2987
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:3012
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:2975
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3017
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:13221
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8049
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3011
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5892
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5924
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5921
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12624
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12094
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:465
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:13171
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:13155
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12653
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)
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK, bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg)
Check that the given template argument corresponds to the given template parameter.
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:13158
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6867
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition: Sema.h:13516
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:11642
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:910
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:13182
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:530
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:533
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:818
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:16977
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition: Sema.h:526
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:14404
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:13207
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:3638
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:12665
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:13215
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1045
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:13565
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15213
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:20982
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:13191
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:5488
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:911
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:13199
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:19021
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:7768
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:7918
SourceManager & SourceMgr
Definition: Sema.h:913
DiagnosticsEngine & Diags
Definition: Sema.h:912
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:13166
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:21179
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:8269
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:4781
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:1262
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
Represents a variable declaration or definition.
Definition: Decl.h:882
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
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:2748
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:2883
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2662
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2874
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:366
@ 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:12670
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:12834
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:12803
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:12829
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition: Sema.h:12798
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12790
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:12672
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12764
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition: Sema.h:12682
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12691
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:12710
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12761
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:12718
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:12725
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:12768
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:12736
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:12774
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition: Sema.h:12701
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition: Sema.h:12780
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12777
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition: Sema.h:12783
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12698
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:12706
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12714
@ TemplateInstantiation
We are instantiating a template declaration.
Definition: Sema.h:12675
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12728
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12732
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12687
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12758
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition: Sema.h:12721
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12793
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:12858
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13018
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:13022
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
Contains all information for a given match.