clang 20.0.0git
SemaTemplateDeductionGuide.cpp
Go to the documentation of this file.
1//===- SemaTemplateDeductionGude.cpp - Template Argument Deduction---------===//
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//
9// This file implements deduction guides for C++ class template argument
10// deduction.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/Basic/LLVM.h"
36#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/Overload.h"
41#include "clang/Sema/Scope.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/SmallVector.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/ErrorHandling.h"
50#include <cassert>
51#include <optional>
52#include <utility>
53
54using namespace clang;
55using namespace sema;
56
57namespace {
58/// Tree transform to "extract" a transformed type from a class template's
59/// constructor to a deduction guide.
60class ExtractTypeForDeductionGuide
61 : public TreeTransform<ExtractTypeForDeductionGuide> {
62 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
63 ClassTemplateDecl *NestedPattern;
64 const MultiLevelTemplateArgumentList *OuterInstantiationArgs;
65 std::optional<TemplateDeclInstantiator> TypedefNameInstantiator;
66
67public:
69 ExtractTypeForDeductionGuide(
70 Sema &SemaRef,
71 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs,
72 ClassTemplateDecl *NestedPattern = nullptr,
73 const MultiLevelTemplateArgumentList *OuterInstantiationArgs = nullptr)
74 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs),
75 NestedPattern(NestedPattern),
76 OuterInstantiationArgs(OuterInstantiationArgs) {
77 if (OuterInstantiationArgs)
78 TypedefNameInstantiator.emplace(
79 SemaRef, SemaRef.getASTContext().getTranslationUnitDecl(),
80 *OuterInstantiationArgs);
81 }
82
83 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
84
85 /// Returns true if it's safe to substitute \p Typedef with
86 /// \p OuterInstantiationArgs.
87 bool mightReferToOuterTemplateParameters(TypedefNameDecl *Typedef) {
88 if (!NestedPattern)
89 return false;
90
91 static auto WalkUp = [](DeclContext *DC, DeclContext *TargetDC) {
92 if (DC->Equals(TargetDC))
93 return true;
94 while (DC->isRecord()) {
95 if (DC->Equals(TargetDC))
96 return true;
97 DC = DC->getParent();
98 }
99 return false;
100 };
101
102 if (WalkUp(Typedef->getDeclContext(), NestedPattern->getTemplatedDecl()))
103 return true;
104 if (WalkUp(NestedPattern->getTemplatedDecl(), Typedef->getDeclContext()))
105 return true;
106 return false;
107 }
108
111 SourceLocation TemplateNameLoc,
112 TemplateArgumentListInfo &TemplateArgs) {
113 if (!OuterInstantiationArgs ||
114 !isa_and_present<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()))
115 return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc,
116 TemplateArgs);
117
118 auto *TATD = cast<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
119 auto *Pattern = TATD;
120 while (Pattern->getInstantiatedFromMemberTemplate())
121 Pattern = Pattern->getInstantiatedFromMemberTemplate();
122 if (!mightReferToOuterTemplateParameters(Pattern->getTemplatedDecl()))
123 return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc,
124 TemplateArgs);
125
126 Decl *NewD =
127 TypedefNameInstantiator->InstantiateTypeAliasTemplateDecl(TATD);
128 if (!NewD)
129 return QualType();
130
131 auto *NewTATD = cast<TypeAliasTemplateDecl>(NewD);
132 MaterializedTypedefs.push_back(NewTATD->getTemplatedDecl());
133
135 TemplateName(NewTATD), TemplateNameLoc, TemplateArgs);
136 }
137
138 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
139 ASTContext &Context = SemaRef.getASTContext();
140 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
141 TypedefNameDecl *Decl = OrigDecl;
142 // Transform the underlying type of the typedef and clone the Decl only if
143 // the typedef has a dependent context.
144 bool InDependentContext = OrigDecl->getDeclContext()->isDependentContext();
145
146 // A typedef/alias Decl within the NestedPattern may reference the outer
147 // template parameters. They're substituted with corresponding instantiation
148 // arguments here and in RebuildTemplateSpecializationType() above.
149 // Otherwise, we would have a CTAD guide with "dangling" template
150 // parameters.
151 // For example,
152 // template <class T> struct Outer {
153 // using Alias = S<T>;
154 // template <class U> struct Inner {
155 // Inner(Alias);
156 // };
157 // };
158 if (OuterInstantiationArgs && InDependentContext &&
160 Decl = cast_if_present<TypedefNameDecl>(
161 TypedefNameInstantiator->InstantiateTypedefNameDecl(
162 OrigDecl, /*IsTypeAlias=*/isa<TypeAliasDecl>(OrigDecl)));
163 if (!Decl)
164 return QualType();
165 MaterializedTypedefs.push_back(Decl);
166 } else if (InDependentContext) {
167 TypeLocBuilder InnerTLB;
168 QualType Transformed =
169 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
170 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
171 if (isa<TypeAliasDecl>(OrigDecl))
173 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
174 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
175 else {
176 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
178 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
179 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
180 }
181 MaterializedTypedefs.push_back(Decl);
182 }
183
184 QualType TDTy = Context.getTypedefType(Decl);
185 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
186 TypedefTL.setNameLoc(TL.getNameLoc());
187
188 return TDTy;
189 }
190};
191
192// Build a deduction guide using the provided information.
193//
194// A deduction guide can be either a template or a non-template function
195// declaration. If \p TemplateParams is null, a non-template function
196// declaration will be created.
197NamedDecl *buildDeductionGuide(
198 Sema &SemaRef, TemplateDecl *OriginalTemplate,
199 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
201 SourceLocation Loc, SourceLocation LocEnd, bool IsImplicit,
202 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
203 DeclContext *DC = OriginalTemplate->getDeclContext();
204 auto DeductionGuideName =
206 OriginalTemplate);
207
208 DeclarationNameInfo Name(DeductionGuideName, Loc);
210 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
211
212 // Build the implicit deduction guide template.
213 auto *Guide =
214 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
215 TInfo->getType(), TInfo, LocEnd, Ctor);
216 Guide->setImplicit(IsImplicit);
217 Guide->setParams(Params);
218
219 for (auto *Param : Params)
220 Param->setDeclContext(Guide);
221 for (auto *TD : MaterializedTypedefs)
222 TD->setDeclContext(Guide);
223 if (isa<CXXRecordDecl>(DC))
224 Guide->setAccess(AS_public);
225
226 if (!TemplateParams) {
227 DC->addDecl(Guide);
228 return Guide;
229 }
230
231 auto *GuideTemplate = FunctionTemplateDecl::Create(
232 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
233 GuideTemplate->setImplicit(IsImplicit);
234 Guide->setDescribedFunctionTemplate(GuideTemplate);
235
236 if (isa<CXXRecordDecl>(DC))
237 GuideTemplate->setAccess(AS_public);
238
239 DC->addDecl(GuideTemplate);
240 return GuideTemplate;
241}
242
243// Transform a given template type parameter `TTP`.
244TemplateTypeParmDecl *transformTemplateTypeParam(
245 Sema &SemaRef, DeclContext *DC, TemplateTypeParmDecl *TTP,
246 MultiLevelTemplateArgumentList &Args, unsigned NewDepth, unsigned NewIndex,
247 bool EvaluateConstraint) {
248 // TemplateTypeParmDecl's index cannot be changed after creation, so
249 // substitute it directly.
250 auto *NewTTP = TemplateTypeParmDecl::Create(
251 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), NewDepth,
252 NewIndex, TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
253 TTP->isParameterPack(), TTP->hasTypeConstraint(),
255 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
256 : std::nullopt);
257 if (const auto *TC = TTP->getTypeConstraint())
258 SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
259 /*EvaluateConstraint=*/EvaluateConstraint);
260 if (TTP->hasDefaultArgument()) {
261 TemplateArgumentLoc InstantiatedDefaultArg;
262 if (!SemaRef.SubstTemplateArgument(
263 TTP->getDefaultArgument(), Args, InstantiatedDefaultArg,
264 TTP->getDefaultArgumentLoc(), TTP->getDeclName()))
265 NewTTP->setDefaultArgument(SemaRef.Context, InstantiatedDefaultArg);
266 }
267 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TTP, NewTTP);
268 return NewTTP;
269}
270// Similar to above, but for non-type template or template template parameters.
271template <typename NonTypeTemplateOrTemplateTemplateParmDecl>
272NonTypeTemplateOrTemplateTemplateParmDecl *
273transformTemplateParam(Sema &SemaRef, DeclContext *DC,
274 NonTypeTemplateOrTemplateTemplateParmDecl *OldParam,
275 MultiLevelTemplateArgumentList &Args, unsigned NewIndex,
276 unsigned NewDepth) {
277 // Ask the template instantiator to do the heavy lifting for us, then adjust
278 // the index of the parameter once it's done.
279 auto *NewParam = cast<NonTypeTemplateOrTemplateTemplateParmDecl>(
280 SemaRef.SubstDecl(OldParam, DC, Args));
281 NewParam->setPosition(NewIndex);
282 NewParam->setDepth(NewDepth);
283 return NewParam;
284}
285
286NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
289 unsigned NewIndex, unsigned NewDepth,
290 bool EvaluateConstraint = true) {
291 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
292 return transformTemplateTypeParam(
293 SemaRef, DC, TTP, Args, NewDepth, NewIndex,
294 /*EvaluateConstraint=*/EvaluateConstraint);
295 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
296 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex, NewDepth);
297 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(TemplateParam))
298 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex, NewDepth);
299 llvm_unreachable("Unhandled template parameter types");
300}
301
302/// Transform to convert portions of a constructor declaration into the
303/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
304struct ConvertConstructorToDeductionGuideTransform {
305 ConvertConstructorToDeductionGuideTransform(Sema &S,
306 ClassTemplateDecl *Template)
307 : SemaRef(S), Template(Template) {
308 // If the template is nested, then we need to use the original
309 // pattern to iterate over the constructors.
310 ClassTemplateDecl *Pattern = Template;
311 while (Pattern->getInstantiatedFromMemberTemplate()) {
312 if (Pattern->isMemberSpecialization())
313 break;
314 Pattern = Pattern->getInstantiatedFromMemberTemplate();
315 NestedPattern = Pattern;
316 }
317
318 if (NestedPattern)
319 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
320 }
321
322 Sema &SemaRef;
323 ClassTemplateDecl *Template;
324 ClassTemplateDecl *NestedPattern = nullptr;
325
326 DeclContext *DC = Template->getDeclContext();
327 CXXRecordDecl *Primary = Template->getTemplatedDecl();
328 DeclarationName DeductionGuideName =
330
331 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
332
333 // Index adjustment to apply to convert depth-1 template parameters into
334 // depth-0 template parameters.
335 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
336
337 // Instantiation arguments for the outermost depth-1 templates
338 // when the template is nested
339 MultiLevelTemplateArgumentList OuterInstantiationArgs;
340
341 /// Transform a constructor declaration into a deduction guide.
342 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
343 CXXConstructorDecl *CD) {
345
347
348 // C++ [over.match.class.deduct]p1:
349 // -- For each constructor of the class template designated by the
350 // template-name, a function template with the following properties:
351
352 // -- The template parameters are the template parameters of the class
353 // template followed by the template parameters (including default
354 // template arguments) of the constructor, if any.
355 TemplateParameterList *TemplateParams =
356 SemaRef.GetTemplateParameterList(Template);
357 if (FTD) {
358 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
361 AllParams.reserve(TemplateParams->size() + InnerParams->size());
362 AllParams.insert(AllParams.begin(), TemplateParams->begin(),
363 TemplateParams->end());
364 SubstArgs.reserve(InnerParams->size());
365 Depth1Args.reserve(InnerParams->size());
366
367 // Later template parameters could refer to earlier ones, so build up
368 // a list of substituted template arguments as we go.
369 for (NamedDecl *Param : *InnerParams) {
371 Args.setKind(TemplateSubstitutionKind::Rewrite);
372 Args.addOuterTemplateArguments(Depth1Args);
374 if (NestedPattern)
375 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
376 auto [Depth, Index] = getDepthAndIndex(Param);
377 NamedDecl *NewParam = transformTemplateParameter(
378 SemaRef, DC, Param, Args, Index + Depth1IndexAdjustment, Depth - 1);
379 if (!NewParam)
380 return nullptr;
381 // Constraints require that we substitute depth-1 arguments
382 // to match depths when substituted for evaluation later
383 Depth1Args.push_back(SemaRef.Context.getInjectedTemplateArg(NewParam));
384
385 if (NestedPattern) {
386 auto [Depth, Index] = getDepthAndIndex(NewParam);
387 NewParam = transformTemplateParameter(
388 SemaRef, DC, NewParam, OuterInstantiationArgs, Index,
389 Depth - OuterInstantiationArgs.getNumSubstitutedLevels(),
390 /*EvaluateConstraint=*/false);
391 }
392
393 assert(NewParam->getTemplateDepth() == 0 &&
394 "Unexpected template parameter depth");
395
396 AllParams.push_back(NewParam);
397 SubstArgs.push_back(SemaRef.Context.getInjectedTemplateArg(NewParam));
398 }
399
400 // Substitute new template parameters into requires-clause if present.
401 Expr *RequiresClause = nullptr;
402 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
404 Args.setKind(TemplateSubstitutionKind::Rewrite);
405 Args.addOuterTemplateArguments(Depth1Args);
407 if (NestedPattern)
408 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
409 ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
410 if (E.isInvalid())
411 return nullptr;
412 RequiresClause = E.getAs<Expr>();
413 }
414
415 TemplateParams = TemplateParameterList::Create(
416 SemaRef.Context, InnerParams->getTemplateLoc(),
417 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
418 RequiresClause);
419 }
420
421 // If we built a new template-parameter-list, track that we need to
422 // substitute references to the old parameters into references to the
423 // new ones.
425 Args.setKind(TemplateSubstitutionKind::Rewrite);
426 if (FTD) {
427 Args.addOuterTemplateArguments(SubstArgs);
429 }
430
432 ->getTypeLoc()
434 assert(FPTL && "no prototype for constructor declaration");
435
436 // Transform the type of the function, adjusting the return type and
437 // replacing references to the old parameters with references to the
438 // new ones.
439 TypeLocBuilder TLB;
441 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
442 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
443 MaterializedTypedefs);
444 if (NewType.isNull())
445 return nullptr;
446 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
447
448 return buildDeductionGuide(
449 SemaRef, Template, TemplateParams, CD, CD->getExplicitSpecifier(),
450 NewTInfo, CD->getBeginLoc(), CD->getLocation(), CD->getEndLoc(),
451 /*IsImplicit=*/true, MaterializedTypedefs);
452 }
453
454 /// Build a deduction guide with the specified parameter types.
455 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
456 SourceLocation Loc = Template->getLocation();
457
458 // Build the requested type.
460 EPI.HasTrailingReturn = true;
461 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
462 DeductionGuideName, EPI);
463 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
464 if (NestedPattern)
465 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
466 DeductionGuideName);
467
468 if (!TSI)
469 return nullptr;
470
473
474 // Build the parameters, needed during deduction / substitution.
476 for (auto T : ParamTypes) {
477 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
478 if (NestedPattern)
479 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
481 if (!TSI)
482 return nullptr;
483
484 ParmVarDecl *NewParam =
485 ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
486 TSI->getType(), TSI, SC_None, nullptr);
487 NewParam->setScopeInfo(0, Params.size());
488 FPTL.setParam(Params.size(), NewParam);
489 Params.push_back(NewParam);
490 }
491
492 return buildDeductionGuide(
493 SemaRef, Template, SemaRef.GetTemplateParameterList(Template), nullptr,
494 ExplicitSpecifier(), TSI, Loc, Loc, Loc, /*IsImplicit=*/true);
495 }
496
497private:
498 QualType transformFunctionProtoType(
502 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
503 SmallVector<QualType, 4> ParamTypes;
504 const FunctionProtoType *T = TL.getTypePtr();
505
506 // -- The types of the function parameters are those of the constructor.
507 for (auto *OldParam : TL.getParams()) {
508 ParmVarDecl *NewParam = OldParam;
509 // Given
510 // template <class T> struct C {
511 // template <class U> struct D {
512 // template <class V> D(U, V);
513 // };
514 // };
515 // First, transform all the references to template parameters that are
516 // defined outside of the surrounding class template. That is T in the
517 // above example.
518 if (NestedPattern) {
519 NewParam = transformFunctionTypeParam(
520 NewParam, OuterInstantiationArgs, MaterializedTypedefs,
521 /*TransformingOuterPatterns=*/true);
522 if (!NewParam)
523 return QualType();
524 }
525 // Then, transform all the references to template parameters that are
526 // defined at the class template and the constructor. In this example,
527 // they're U and V, respectively.
528 NewParam =
529 transformFunctionTypeParam(NewParam, Args, MaterializedTypedefs,
530 /*TransformingOuterPatterns=*/false);
531 if (!NewParam)
532 return QualType();
533 ParamTypes.push_back(NewParam->getType());
534 Params.push_back(NewParam);
535 }
536
537 // -- The return type is the class template specialization designated by
538 // the template-name and template arguments corresponding to the
539 // template parameters obtained from the class template.
540 //
541 // We use the injected-class-name type of the primary template instead.
542 // This has the convenient property that it is different from any type that
543 // the user can write in a deduction-guide (because they cannot enter the
544 // context of the template), so implicit deduction guides can never collide
545 // with explicit ones.
546 QualType ReturnType = DeducedType;
547 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
548
549 // Resolving a wording defect, we also inherit the variadicness of the
550 // constructor.
552 EPI.Variadic = T->isVariadic();
553 EPI.HasTrailingReturn = true;
554
555 QualType Result = SemaRef.BuildFunctionType(
556 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
557 if (Result.isNull())
558 return QualType();
559
562 NewTL.setLParenLoc(TL.getLParenLoc());
563 NewTL.setRParenLoc(TL.getRParenLoc());
566 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
567 NewTL.setParam(I, Params[I]);
568
569 return Result;
570 }
571
572 ParmVarDecl *transformFunctionTypeParam(
574 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs,
575 bool TransformingOuterPatterns) {
576 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
577 TypeSourceInfo *NewDI;
578 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
579 // Expand out the one and only element in each inner pack.
580 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
581 NewDI =
582 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
583 OldParam->getLocation(), OldParam->getDeclName());
584 if (!NewDI)
585 return nullptr;
586 NewDI =
587 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
588 PackTL.getTypePtr()->getNumExpansions());
589 } else
590 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
591 OldParam->getDeclName());
592 if (!NewDI)
593 return nullptr;
594
595 // Extract the type. This (for instance) replaces references to typedef
596 // members of the current instantiations with the definitions of those
597 // typedefs, avoiding triggering instantiation of the deduced type during
598 // deduction.
599 NewDI = ExtractTypeForDeductionGuide(
600 SemaRef, MaterializedTypedefs, NestedPattern,
601 TransformingOuterPatterns ? &Args : nullptr)
602 .transform(NewDI);
603
604 // Resolving a wording defect, we also inherit default arguments from the
605 // constructor.
606 ExprResult NewDefArg;
607 if (OldParam->hasDefaultArg()) {
608 // We don't care what the value is (we won't use it); just create a
609 // placeholder to indicate there is a default argument.
610 QualType ParamTy = NewDI->getType();
611 NewDefArg = new (SemaRef.Context)
613 ParamTy.getNonLValueExprType(SemaRef.Context),
615 : ParamTy->isRValueReferenceType() ? VK_XValue
616 : VK_PRValue);
617 }
618 // Handle arrays and functions decay.
619 auto NewType = NewDI->getType();
620 if (NewType->isArrayType() || NewType->isFunctionType())
621 NewType = SemaRef.Context.getDecayedType(NewType);
622
624 SemaRef.Context, DC, OldParam->getInnerLocStart(),
625 OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewDI,
626 OldParam->getStorageClass(), NewDefArg.get());
627 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
628 OldParam->getFunctionScopeIndex());
629 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
630 return NewParam;
631 }
632};
633
634// Find all template parameters that appear in the given DeducedArgs.
635// Return the indices of the template parameters in the TemplateParams.
636SmallVector<unsigned> TemplateParamsReferencedInTemplateArgumentList(
637 const TemplateParameterList *TemplateParamsList,
638 ArrayRef<TemplateArgument> DeducedArgs) {
639 struct TemplateParamsReferencedFinder : DynamicRecursiveASTVisitor {
640 const TemplateParameterList *TemplateParamList;
641 llvm::BitVector ReferencedTemplateParams;
642
643 TemplateParamsReferencedFinder(
644 const TemplateParameterList *TemplateParamList)
645 : TemplateParamList(TemplateParamList),
646 ReferencedTemplateParams(TemplateParamList->size()) {}
647
648 bool VisitTemplateTypeParmType(TemplateTypeParmType *TTP) override {
649 // We use the index and depth to retrieve the corresponding template
650 // parameter from the parameter list, which is more robost.
651 Mark(TTP->getDepth(), TTP->getIndex());
652 return true;
653 }
654
655 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
656 MarkAppeared(DRE->getFoundDecl());
657 return true;
658 }
659
660 bool TraverseTemplateName(TemplateName Template) override {
661 if (auto *TD = Template.getAsTemplateDecl())
662 MarkAppeared(TD);
664 }
665
666 void MarkAppeared(NamedDecl *ND) {
669 auto [Depth, Index] = getDepthAndIndex(ND);
670 Mark(Depth, Index);
671 }
672 }
673 void Mark(unsigned Depth, unsigned Index) {
674 if (Index < TemplateParamList->size() &&
675 TemplateParamList->getParam(Index)->getTemplateDepth() == Depth)
676 ReferencedTemplateParams.set(Index);
677 }
678 };
679 TemplateParamsReferencedFinder Finder(TemplateParamsList);
680 Finder.TraverseTemplateArguments(DeducedArgs);
681
682 SmallVector<unsigned> Results;
683 for (unsigned Index = 0; Index < TemplateParamsList->size(); ++Index) {
684 if (Finder.ReferencedTemplateParams[Index])
685 Results.push_back(Index);
686 }
687 return Results;
688}
689
690bool hasDeclaredDeductionGuides(DeclarationName Name, DeclContext *DC) {
691 // Check whether we've already declared deduction guides for this template.
692 // FIXME: Consider storing a flag on the template to indicate this.
693 assert(Name.getNameKind() ==
694 DeclarationName::NameKind::CXXDeductionGuideName &&
695 "name must be a deduction guide name");
696 auto Existing = DC->lookup(Name);
697 for (auto *D : Existing)
698 if (D->isImplicit())
699 return true;
700 return false;
701}
702
703// Build the associated constraints for the alias deduction guides.
704// C++ [over.match.class.deduct]p3.3:
705// The associated constraints ([temp.constr.decl]) are the conjunction of the
706// associated constraints of g and a constraint that is satisfied if and only
707// if the arguments of A are deducible (see below) from the return type.
708//
709// The return result is expected to be the require-clause for the synthesized
710// alias deduction guide.
711Expr *
712buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F,
715 unsigned FirstUndeducedParamIdx, Expr *IsDeducible) {
717 if (!RC)
718 return IsDeducible;
719
720 ASTContext &Context = SemaRef.Context;
722
723 // In the clang AST, constraint nodes are deliberately not instantiated unless
724 // they are actively being evaluated. Consequently, occurrences of template
725 // parameters in the require-clause expression have a subtle "depth"
726 // difference compared to normal occurrences in places, such as function
727 // parameters. When transforming the require-clause, we must take this
728 // distinction into account:
729 //
730 // 1) In the transformed require-clause, occurrences of template parameters
731 // must use the "uninstantiated" depth;
732 // 2) When substituting on the require-clause expr of the underlying
733 // deduction guide, we must use the entire set of template argument lists;
734 //
735 // It's important to note that we're performing this transformation on an
736 // *instantiated* AliasTemplate.
737
738 // For 1), if the alias template is nested within a class template, we
739 // calcualte the 'uninstantiated' depth by adding the substitution level back.
740 unsigned AdjustDepth = 0;
741 if (auto *PrimaryTemplate =
742 AliasTemplate->getInstantiatedFromMemberTemplate())
743 AdjustDepth = PrimaryTemplate->getTemplateDepth();
744
745 // We rebuild all template parameters with the uninstantiated depth, and
746 // build template arguments refer to them.
747 SmallVector<TemplateArgument> AdjustedAliasTemplateArgs;
748
749 for (auto *TP : *AliasTemplate->getTemplateParameters()) {
750 // Rebuild any internal references to earlier parameters and reindex
751 // as we go.
753 Args.setKind(TemplateSubstitutionKind::Rewrite);
754 Args.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
755 NamedDecl *NewParam = transformTemplateParameter(
756 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
757 /*NewIndex=*/AdjustedAliasTemplateArgs.size(),
758 getDepthAndIndex(TP).first + AdjustDepth);
759
760 TemplateArgument NewTemplateArgument =
761 Context.getInjectedTemplateArg(NewParam);
762 AdjustedAliasTemplateArgs.push_back(NewTemplateArgument);
763 }
764 // Template arguments used to transform the template arguments in
765 // DeducedResults.
766 SmallVector<TemplateArgument> TemplateArgsForBuildingRC(
768 // Transform the transformed template args
770 Args.setKind(TemplateSubstitutionKind::Rewrite);
771 Args.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
772
773 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
774 const auto &D = DeduceResults[Index];
775 if (D.isNull()) { // non-deduced template parameters of f
776 NamedDecl *TP = F->getTemplateParameters()->getParam(Index);
778 Args.setKind(TemplateSubstitutionKind::Rewrite);
779 Args.addOuterTemplateArguments(TemplateArgsForBuildingRC);
780 // Rebuild the template parameter with updated depth and index.
781 NamedDecl *NewParam =
782 transformTemplateParameter(SemaRef, F->getDeclContext(), TP, Args,
783 /*NewIndex=*/FirstUndeducedParamIdx,
784 getDepthAndIndex(TP).first + AdjustDepth);
785 FirstUndeducedParamIdx += 1;
786 assert(TemplateArgsForBuildingRC[Index].isNull());
787 TemplateArgsForBuildingRC[Index] =
788 Context.getInjectedTemplateArg(NewParam);
789 continue;
790 }
791 TemplateArgumentLoc Input =
793 TemplateArgumentLoc Output;
794 if (!SemaRef.SubstTemplateArgument(Input, Args, Output)) {
795 assert(TemplateArgsForBuildingRC[Index].isNull() &&
796 "InstantiatedArgs must be null before setting");
797 TemplateArgsForBuildingRC[Index] = Output.getArgument();
798 }
799 }
800
801 // A list of template arguments for transforming the require-clause of F.
802 // It must contain the entire set of template argument lists.
803 MultiLevelTemplateArgumentList ArgsForBuildingRC;
805 ArgsForBuildingRC.addOuterTemplateArguments(TemplateArgsForBuildingRC);
806 // For 2), if the underlying deduction guide F is nested in a class template,
807 // we need the entire template argument list, as the constraint AST in the
808 // require-clause of F remains completely uninstantiated.
809 //
810 // For example:
811 // template <typename T> // depth 0
812 // struct Outer {
813 // template <typename U>
814 // struct Foo { Foo(U); };
815 //
816 // template <typename U> // depth 1
817 // requires C<U>
818 // Foo(U) -> Foo<int>;
819 // };
820 // template <typename U>
821 // using AFoo = Outer<int>::Foo<U>;
822 //
823 // In this scenario, the deduction guide for `Foo` inside `Outer<int>`:
824 // - The occurrence of U in the require-expression is [depth:1, index:0]
825 // - The occurrence of U in the function parameter is [depth:0, index:0]
826 // - The template parameter of U is [depth:0, index:0]
827 //
828 // We add the outer template arguments which is [int] to the multi-level arg
829 // list to ensure that the occurrence U in `C<U>` will be replaced with int
830 // during the substitution.
831 //
832 // NOTE: The underlying deduction guide F is instantiated -- either from an
833 // explicitly-written deduction guide member, or from a constructor.
834 // getInstantiatedFromMemberTemplate() can only handle the former case, so we
835 // check the DeclContext kind.
837 clang::Decl::ClassTemplateSpecialization) {
838 auto OuterLevelArgs = SemaRef.getTemplateInstantiationArgs(
839 F, F->getLexicalDeclContext(),
840 /*Final=*/false, /*Innermost=*/std::nullopt,
841 /*RelativeToPrimary=*/true,
842 /*Pattern=*/nullptr,
843 /*ForConstraintInstantiation=*/true);
844 for (auto It : OuterLevelArgs)
845 ArgsForBuildingRC.addOuterTemplateArguments(It.Args);
846 }
847
848 ExprResult E = SemaRef.SubstExpr(RC, ArgsForBuildingRC);
849 if (E.isInvalid())
850 return nullptr;
851
852 auto Conjunction =
853 SemaRef.BuildBinOp(SemaRef.getCurScope(), SourceLocation{},
854 BinaryOperatorKind::BO_LAnd, E.get(), IsDeducible);
855 if (Conjunction.isInvalid())
856 return nullptr;
857 return Conjunction.getAs<Expr>();
858}
859// Build the is_deducible constraint for the alias deduction guides.
860// [over.match.class.deduct]p3.3:
861// ... and a constraint that is satisfied if and only if the arguments
862// of A are deducible (see below) from the return type.
863Expr *buildIsDeducibleConstraint(Sema &SemaRef,
865 QualType ReturnType,
866 SmallVector<NamedDecl *> TemplateParams) {
867 ASTContext &Context = SemaRef.Context;
868 // Constraint AST nodes must use uninstantiated depth.
869 if (auto *PrimaryTemplate =
870 AliasTemplate->getInstantiatedFromMemberTemplate();
871 PrimaryTemplate && TemplateParams.size() > 0) {
873
874 // Adjust the depth for TemplateParams.
875 unsigned AdjustDepth = PrimaryTemplate->getTemplateDepth();
876 SmallVector<TemplateArgument> TransformedTemplateArgs;
877 for (auto *TP : TemplateParams) {
878 // Rebuild any internal references to earlier parameters and reindex
879 // as we go.
881 Args.setKind(TemplateSubstitutionKind::Rewrite);
882 Args.addOuterTemplateArguments(TransformedTemplateArgs);
883 NamedDecl *NewParam = transformTemplateParameter(
884 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
885 /*NewIndex=*/TransformedTemplateArgs.size(),
886 getDepthAndIndex(TP).first + AdjustDepth);
887
888 TemplateArgument NewTemplateArgument =
889 Context.getInjectedTemplateArg(NewParam);
890 TransformedTemplateArgs.push_back(NewTemplateArgument);
891 }
892 // Transformed the ReturnType to restore the uninstantiated depth.
894 Args.setKind(TemplateSubstitutionKind::Rewrite);
895 Args.addOuterTemplateArguments(TransformedTemplateArgs);
896 ReturnType = SemaRef.SubstType(
897 ReturnType, Args, AliasTemplate->getLocation(),
899 };
900
901 SmallVector<TypeSourceInfo *> IsDeducibleTypeTraitArgs = {
904 TemplateName(AliasTemplate), /*DeducedType=*/QualType(),
905 /*IsDependent=*/true)), // template specialization type whose
906 // arguments will be deduced.
908 ReturnType), // type from which template arguments are deduced.
909 };
911 Context, Context.getLogicalOperationType(), AliasTemplate->getLocation(),
912 TypeTrait::BTT_IsDeducible, IsDeducibleTypeTraitArgs,
913 AliasTemplate->getLocation(), /*Value*/ false);
914}
915
916std::pair<TemplateDecl *, llvm::ArrayRef<TemplateArgument>>
917getRHSTemplateDeclAndArgs(Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate) {
918 // Unwrap the sugared ElaboratedType.
919 auto RhsType = AliasTemplate->getTemplatedDecl()
920 ->getUnderlyingType()
921 .getSingleStepDesugaredType(SemaRef.Context);
922 TemplateDecl *Template = nullptr;
923 llvm::ArrayRef<TemplateArgument> AliasRhsTemplateArgs;
924 if (const auto *TST = RhsType->getAs<TemplateSpecializationType>()) {
925 // Cases where the RHS of the alias is dependent. e.g.
926 // template<typename T>
927 // using AliasFoo1 = Foo<T>; // a class/type alias template specialization
928 Template = TST->getTemplateName().getAsTemplateDecl();
929 AliasRhsTemplateArgs = TST->template_arguments();
930 } else if (const auto *RT = RhsType->getAs<RecordType>()) {
931 // Cases where template arguments in the RHS of the alias are not
932 // dependent. e.g.
933 // using AliasFoo = Foo<bool>;
934 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
935 RT->getAsCXXRecordDecl())) {
936 Template = CTSD->getSpecializedTemplate();
937 AliasRhsTemplateArgs = CTSD->getTemplateArgs().asArray();
938 }
939 } else {
940 assert(false && "unhandled RHS type of the alias");
941 }
942 return {Template, AliasRhsTemplateArgs};
943}
944
945// Build deduction guides for a type alias template from the given underlying
946// deduction guide F.
948BuildDeductionGuideForTypeAlias(Sema &SemaRef,
952 Sema::InstantiatingTemplate BuildingDeductionGuides(
953 SemaRef, AliasTemplate->getLocation(), F,
955 if (BuildingDeductionGuides.isInvalid())
956 return nullptr;
957
958 auto &Context = SemaRef.Context;
959 auto [Template, AliasRhsTemplateArgs] =
960 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
961
962 auto RType = F->getTemplatedDecl()->getReturnType();
963 // The (trailing) return type of the deduction guide.
964 const TemplateSpecializationType *FReturnType =
966 if (const auto *InjectedCNT = RType->getAs<InjectedClassNameType>())
967 // implicitly-generated deduction guide.
968 FReturnType = InjectedCNT->getInjectedTST();
969 else if (const auto *ET = RType->getAs<ElaboratedType>())
970 // explicit deduction guide.
971 FReturnType = ET->getNamedType()->getAs<TemplateSpecializationType>();
972 assert(FReturnType && "expected to see a return type");
973 // Deduce template arguments of the deduction guide f from the RHS of
974 // the alias.
975 //
976 // C++ [over.match.class.deduct]p3: ...For each function or function
977 // template f in the guides of the template named by the
978 // simple-template-id of the defining-type-id, the template arguments
979 // of the return type of f are deduced from the defining-type-id of A
980 // according to the process in [temp.deduct.type] with the exception
981 // that deduction does not fail if not all template arguments are
982 // deduced.
983 //
984 //
985 // template<typename X, typename Y>
986 // f(X, Y) -> f<Y, X>;
987 //
988 // template<typename U>
989 // using alias = f<int, U>;
990 //
991 // The RHS of alias is f<int, U>, we deduced the template arguments of
992 // the return type of the deduction guide from it: Y->int, X->U
993 sema::TemplateDeductionInfo TDeduceInfo(Loc);
994 // Must initialize n elements, this is required by DeduceTemplateArguments.
997
998 // FIXME: DeduceTemplateArguments stops immediately at the first
999 // non-deducible template argument. However, this doesn't seem to casue
1000 // issues for practice cases, we probably need to extend it to continue
1001 // performing deduction for rest of arguments to align with the C++
1002 // standard.
1004 F->getTemplateParameters(), FReturnType->template_arguments(),
1005 AliasRhsTemplateArgs, TDeduceInfo, DeduceResults,
1006 /*NumberOfArgumentsMustMatch=*/false);
1007
1009 SmallVector<unsigned> NonDeducedTemplateParamsInFIndex;
1010 // !!NOTE: DeduceResults respects the sequence of template parameters of
1011 // the deduction guide f.
1012 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
1013 if (const auto &D = DeduceResults[Index]; !D.isNull()) // Deduced
1014 DeducedArgs.push_back(D);
1015 else
1016 NonDeducedTemplateParamsInFIndex.push_back(Index);
1017 }
1018 auto DeducedAliasTemplateParams =
1019 TemplateParamsReferencedInTemplateArgumentList(
1020 AliasTemplate->getTemplateParameters(), DeducedArgs);
1021 // All template arguments null by default.
1022 SmallVector<TemplateArgument> TemplateArgsForBuildingFPrime(
1023 F->getTemplateParameters()->size());
1024
1025 // Create a template parameter list for the synthesized deduction guide f'.
1026 //
1027 // C++ [over.match.class.deduct]p3.2:
1028 // If f is a function template, f' is a function template whose template
1029 // parameter list consists of all the template parameters of A
1030 // (including their default template arguments) that appear in the above
1031 // deductions or (recursively) in their default template arguments
1032 SmallVector<NamedDecl *> FPrimeTemplateParams;
1033 // Store template arguments that refer to the newly-created template
1034 // parameters, used for building `TemplateArgsForBuildingFPrime`.
1035 SmallVector<TemplateArgument, 16> TransformedDeducedAliasArgs(
1036 AliasTemplate->getTemplateParameters()->size());
1037
1038 for (unsigned AliasTemplateParamIdx : DeducedAliasTemplateParams) {
1039 auto *TP =
1040 AliasTemplate->getTemplateParameters()->getParam(AliasTemplateParamIdx);
1041 // Rebuild any internal references to earlier parameters and reindex as
1042 // we go.
1044 Args.setKind(TemplateSubstitutionKind::Rewrite);
1045 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
1046 NamedDecl *NewParam = transformTemplateParameter(
1047 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
1048 /*NewIndex=*/FPrimeTemplateParams.size(), getDepthAndIndex(TP).first);
1049 FPrimeTemplateParams.push_back(NewParam);
1050
1051 TemplateArgument NewTemplateArgument =
1052 Context.getInjectedTemplateArg(NewParam);
1053 TransformedDeducedAliasArgs[AliasTemplateParamIdx] = NewTemplateArgument;
1054 }
1055 unsigned FirstUndeducedParamIdx = FPrimeTemplateParams.size();
1056 // ...followed by the template parameters of f that were not deduced
1057 // (including their default template arguments)
1058 for (unsigned FTemplateParamIdx : NonDeducedTemplateParamsInFIndex) {
1059 auto *TP = F->getTemplateParameters()->getParam(FTemplateParamIdx);
1061 Args.setKind(TemplateSubstitutionKind::Rewrite);
1062 // We take a shortcut here, it is ok to reuse the
1063 // TemplateArgsForBuildingFPrime.
1064 Args.addOuterTemplateArguments(TemplateArgsForBuildingFPrime);
1065 NamedDecl *NewParam = transformTemplateParameter(
1066 SemaRef, F->getDeclContext(), TP, Args, FPrimeTemplateParams.size(),
1067 getDepthAndIndex(TP).first);
1068 FPrimeTemplateParams.push_back(NewParam);
1069
1070 assert(TemplateArgsForBuildingFPrime[FTemplateParamIdx].isNull() &&
1071 "The argument must be null before setting");
1072 TemplateArgsForBuildingFPrime[FTemplateParamIdx] =
1073 Context.getInjectedTemplateArg(NewParam);
1074 }
1075
1076 // To form a deduction guide f' from f, we leverage clang's instantiation
1077 // mechanism, we construct a template argument list where the template
1078 // arguments refer to the newly-created template parameters of f', and
1079 // then apply instantiation on this template argument list to instantiate
1080 // f, this ensures all template parameter occurrences are updated
1081 // correctly.
1082 //
1083 // The template argument list is formed from the `DeducedArgs`, two parts:
1084 // 1) appeared template parameters of alias: transfrom the deduced
1085 // template argument;
1086 // 2) non-deduced template parameters of f: rebuild a
1087 // template argument;
1088 //
1089 // 2) has been built already (when rebuilding the new template
1090 // parameters), we now perform 1).
1092 Args.setKind(TemplateSubstitutionKind::Rewrite);
1093 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
1094 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
1095 const auto &D = DeduceResults[Index];
1096 if (D.isNull()) {
1097 // 2): Non-deduced template parameter has been built already.
1098 assert(!TemplateArgsForBuildingFPrime[Index].isNull() &&
1099 "template arguments for non-deduced template parameters should "
1100 "be been set!");
1101 continue;
1102 }
1103 TemplateArgumentLoc Input =
1105 TemplateArgumentLoc Output;
1106 if (!SemaRef.SubstTemplateArgument(Input, Args, Output)) {
1107 assert(TemplateArgsForBuildingFPrime[Index].isNull() &&
1108 "InstantiatedArgs must be null before setting");
1109 TemplateArgsForBuildingFPrime[Index] = Output.getArgument();
1110 }
1111 }
1112
1113 auto *TemplateArgListForBuildingFPrime =
1114 TemplateArgumentList::CreateCopy(Context, TemplateArgsForBuildingFPrime);
1115 // Form the f' by substituting the template arguments into f.
1116 if (auto *FPrime = SemaRef.InstantiateFunctionDeclaration(
1117 F, TemplateArgListForBuildingFPrime, AliasTemplate->getLocation(),
1119 auto *GG = cast<CXXDeductionGuideDecl>(FPrime);
1120
1121 Expr *IsDeducible = buildIsDeducibleConstraint(
1122 SemaRef, AliasTemplate, FPrime->getReturnType(), FPrimeTemplateParams);
1123 Expr *RequiresClause =
1124 buildAssociatedConstraints(SemaRef, F, AliasTemplate, DeduceResults,
1125 FirstUndeducedParamIdx, IsDeducible);
1126
1127 auto *FPrimeTemplateParamList = TemplateParameterList::Create(
1128 Context, AliasTemplate->getTemplateParameters()->getTemplateLoc(),
1129 AliasTemplate->getTemplateParameters()->getLAngleLoc(),
1130 FPrimeTemplateParams,
1131 AliasTemplate->getTemplateParameters()->getRAngleLoc(),
1132 /*RequiresClause=*/RequiresClause);
1133 auto *Result = cast<FunctionTemplateDecl>(buildDeductionGuide(
1134 SemaRef, AliasTemplate, FPrimeTemplateParamList,
1135 GG->getCorrespondingConstructor(), GG->getExplicitSpecifier(),
1136 GG->getTypeSourceInfo(), AliasTemplate->getBeginLoc(),
1137 AliasTemplate->getLocation(), AliasTemplate->getEndLoc(),
1138 F->isImplicit()));
1139 cast<CXXDeductionGuideDecl>(Result->getTemplatedDecl())
1140 ->setDeductionCandidateKind(GG->getDeductionCandidateKind());
1141 return Result;
1142 }
1143 return nullptr;
1144}
1145
1146void DeclareImplicitDeductionGuidesForTypeAlias(
1148 if (AliasTemplate->isInvalidDecl())
1149 return;
1150 auto &Context = SemaRef.Context;
1151 // FIXME: if there is an explicit deduction guide after the first use of the
1152 // type alias usage, we will not cover this explicit deduction guide. fix this
1153 // case.
1154 if (hasDeclaredDeductionGuides(
1156 AliasTemplate->getDeclContext()))
1157 return;
1158 auto [Template, AliasRhsTemplateArgs] =
1159 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
1160 if (!Template)
1161 return;
1162 DeclarationNameInfo NameInfo(
1163 Context.DeclarationNames.getCXXDeductionGuideName(Template), Loc);
1164 LookupResult Guides(SemaRef, NameInfo, clang::Sema::LookupOrdinaryName);
1165 SemaRef.LookupQualifiedName(Guides, Template->getDeclContext());
1166 Guides.suppressDiagnostics();
1167
1168 for (auto *G : Guides) {
1169 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(G)) {
1170 // The deduction guide is a non-template function decl, we just clone it.
1171 auto *FunctionType =
1172 SemaRef.Context.getTrivialTypeSourceInfo(DG->getType());
1174 FunctionType->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1175
1176 // Clone the parameters.
1177 for (unsigned I = 0, N = DG->getNumParams(); I != N; ++I) {
1178 const auto *P = DG->getParamDecl(I);
1179 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(P->getType());
1180 ParmVarDecl *NewParam = ParmVarDecl::Create(
1181 SemaRef.Context, G->getDeclContext(),
1182 DG->getParamDecl(I)->getBeginLoc(), P->getLocation(), nullptr,
1183 TSI->getType(), TSI, SC_None, nullptr);
1184 NewParam->setScopeInfo(0, I);
1185 FPTL.setParam(I, NewParam);
1186 }
1187 auto *Transformed = cast<FunctionDecl>(buildDeductionGuide(
1188 SemaRef, AliasTemplate, /*TemplateParams=*/nullptr,
1189 /*Constructor=*/nullptr, DG->getExplicitSpecifier(), FunctionType,
1190 AliasTemplate->getBeginLoc(), AliasTemplate->getLocation(),
1191 AliasTemplate->getEndLoc(), DG->isImplicit()));
1192
1193 // FIXME: Here the synthesized deduction guide is not a templated
1194 // function. Per [dcl.decl]p4, the requires-clause shall be present only
1195 // if the declarator declares a templated function, a bug in standard?
1196 auto *Constraint = buildIsDeducibleConstraint(
1197 SemaRef, AliasTemplate, Transformed->getReturnType(), {});
1198 if (auto *RC = DG->getTrailingRequiresClause()) {
1199 auto Conjunction =
1200 SemaRef.BuildBinOp(SemaRef.getCurScope(), SourceLocation{},
1201 BinaryOperatorKind::BO_LAnd, RC, Constraint);
1202 if (!Conjunction.isInvalid())
1203 Constraint = Conjunction.getAs<Expr>();
1204 }
1205 Transformed->setTrailingRequiresClause(Constraint);
1206 }
1207 FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(G);
1208 if (!F)
1209 continue;
1210 // The **aggregate** deduction guides are handled in a different code path
1211 // (DeclareAggregateDeductionGuideFromInitList), which involves the tricky
1212 // cache.
1213 if (cast<CXXDeductionGuideDecl>(F->getTemplatedDecl())
1214 ->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
1215 continue;
1216
1217 BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate, F, Loc);
1218 }
1219}
1220
1221// Build an aggregate deduction guide for a type alias template.
1222FunctionTemplateDecl *DeclareAggregateDeductionGuideForTypeAlias(
1225 TemplateDecl *RHSTemplate =
1226 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate).first;
1227 if (!RHSTemplate)
1228 return nullptr;
1229
1231 llvm::SmallVector<QualType> NewParamTypes;
1232 ExtractTypeForDeductionGuide TypeAliasTransformer(SemaRef, TypedefDecls);
1233 for (QualType P : ParamTypes) {
1234 QualType Type = TypeAliasTransformer.TransformType(P);
1235 if (Type.isNull())
1236 return nullptr;
1237 NewParamTypes.push_back(Type);
1238 }
1239
1240 auto *RHSDeductionGuide = SemaRef.DeclareAggregateDeductionGuideFromInitList(
1241 RHSTemplate, NewParamTypes, Loc);
1242 if (!RHSDeductionGuide)
1243 return nullptr;
1244
1245 for (TypedefNameDecl *TD : TypedefDecls)
1246 TD->setDeclContext(RHSDeductionGuide->getTemplatedDecl());
1247
1248 return BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate,
1249 RHSDeductionGuide, Loc);
1250}
1251
1252} // namespace
1253
1255 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
1257 llvm::FoldingSetNodeID ID;
1258 ID.AddPointer(Template);
1259 for (auto &T : ParamTypes)
1260 T.getCanonicalType().Profile(ID);
1261 unsigned Hash = ID.ComputeHash();
1262
1263 auto Found = AggregateDeductionCandidates.find(Hash);
1264 if (Found != AggregateDeductionCandidates.end()) {
1265 CXXDeductionGuideDecl *GD = Found->getSecond();
1266 return GD->getDescribedFunctionTemplate();
1267 }
1268
1269 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
1270 if (auto *FTD = DeclareAggregateDeductionGuideForTypeAlias(
1271 *this, AliasTemplate, ParamTypes, Loc)) {
1272 auto *GD = cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1273 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
1275 return FTD;
1276 }
1277 }
1278
1279 if (CXXRecordDecl *DefRecord =
1280 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
1281 if (TemplateDecl *DescribedTemplate =
1282 DefRecord->getDescribedClassTemplate())
1283 Template = DescribedTemplate;
1284 }
1285
1286 DeclContext *DC = Template->getDeclContext();
1287 if (DC->isDependentContext())
1288 return nullptr;
1289
1290 ConvertConstructorToDeductionGuideTransform Transform(
1291 *this, cast<ClassTemplateDecl>(Template));
1292 if (!isCompleteType(Loc, Transform.DeducedType))
1293 return nullptr;
1294
1295 // In case we were expanding a pack when we attempted to declare deduction
1296 // guides, turn off pack expansion for everything we're about to do.
1297 ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
1298 /*NewSubstitutionIndex=*/-1);
1299 // Create a template instantiation record to track the "instantiation" of
1300 // constructors into deduction guides.
1301 InstantiatingTemplate BuildingDeductionGuides(
1302 *this, Loc, Template,
1304 if (BuildingDeductionGuides.isInvalid())
1305 return nullptr;
1306
1307 ClassTemplateDecl *Pattern =
1308 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
1309 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
1310
1311 auto *FTD = cast<FunctionTemplateDecl>(
1312 Transform.buildSimpleDeductionGuide(ParamTypes));
1313 SavedContext.pop();
1314 auto *GD = cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1315 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
1317 return FTD;
1318}
1319
1322 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
1323 DeclareImplicitDeductionGuidesForTypeAlias(*this, AliasTemplate, Loc);
1324 return;
1325 }
1326 if (CXXRecordDecl *DefRecord =
1327 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
1328 if (TemplateDecl *DescribedTemplate =
1329 DefRecord->getDescribedClassTemplate())
1330 Template = DescribedTemplate;
1331 }
1332
1333 DeclContext *DC = Template->getDeclContext();
1334 if (DC->isDependentContext())
1335 return;
1336
1337 ConvertConstructorToDeductionGuideTransform Transform(
1338 *this, cast<ClassTemplateDecl>(Template));
1339 if (!isCompleteType(Loc, Transform.DeducedType))
1340 return;
1341
1342 if (hasDeclaredDeductionGuides(Transform.DeductionGuideName, DC))
1343 return;
1344
1345 // In case we were expanding a pack when we attempted to declare deduction
1346 // guides, turn off pack expansion for everything we're about to do.
1347 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1348 // Create a template instantiation record to track the "instantiation" of
1349 // constructors into deduction guides.
1350 InstantiatingTemplate BuildingDeductionGuides(
1351 *this, Loc, Template,
1353 if (BuildingDeductionGuides.isInvalid())
1354 return;
1355
1356 // Convert declared constructors into deduction guide templates.
1357 // FIXME: Skip constructors for which deduction must necessarily fail (those
1358 // for which some class template parameter without a default argument never
1359 // appears in a deduced context).
1360 ClassTemplateDecl *Pattern =
1361 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
1362 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
1363 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
1364 bool AddedAny = false;
1365 for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) {
1366 D = D->getUnderlyingDecl();
1367 if (D->isInvalidDecl() || D->isImplicit())
1368 continue;
1369
1370 D = cast<NamedDecl>(D->getCanonicalDecl());
1371
1372 // Within C++20 modules, we may have multiple same constructors in
1373 // multiple same RecordDecls. And it doesn't make sense to create
1374 // duplicated deduction guides for the duplicated constructors.
1375 if (ProcessedCtors.count(D))
1376 continue;
1377
1378 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1379 auto *CD =
1380 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1381 // Class-scope explicit specializations (MS extension) do not result in
1382 // deduction guides.
1383 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1384 continue;
1385
1386 // Cannot make a deduction guide when unparsed arguments are present.
1387 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
1388 return !P || P->hasUnparsedDefaultArg();
1389 }))
1390 continue;
1391
1392 ProcessedCtors.insert(D);
1393 Transform.transformConstructor(FTD, CD);
1394 AddedAny = true;
1395 }
1396
1397 // C++17 [over.match.class.deduct]
1398 // -- If C is not defined or does not declare any constructors, an
1399 // additional function template derived as above from a hypothetical
1400 // constructor C().
1401 if (!AddedAny)
1402 Transform.buildSimpleDeductionGuide({});
1403
1404 // -- An additional function template derived as above from a hypothetical
1405 // constructor C(C), called the copy deduction candidate.
1406 cast<CXXDeductionGuideDecl>(
1407 cast<FunctionTemplateDecl>(
1408 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1409 ->getTemplatedDecl())
1410 ->setDeductionCandidateKind(DeductionCandidate::Copy);
1411
1412 SavedContext.pop();
1413}
Defines the clang::ASTContext interface.
StringRef P
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
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
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
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 getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2132
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
PtrTy get() const
Definition: Ownership.h:170
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2624
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1967
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2250
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
bool isRecord() const
Definition: DeclBase.h:2169
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2082
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1370
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:293
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:355
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
The name of a declaration.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:777
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6522
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6943
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
This represents one expression.
Definition: Expr.h:110
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3867
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5479
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
unsigned getNumParams() const
Definition: TypeLoc.h:1531
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1483
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1479
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1495
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1538
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1522
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1503
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1487
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1517
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1475
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1491
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1499
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6793
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void InstantiatedLocal(const Decl *D, Decl *Inst)
Represents the results of name lookup.
Definition: Lookup.h:46
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
void addOuterRetainedLevel()
Add an outermost level that we are not substituting.
Definition: Template.h:257
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
void setKind(TemplateSubstitutionKind K)
Definition: Template.h:109
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
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
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
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
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2992
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2922
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3023
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1775
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:3521
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:859
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13193
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3003
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12636
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.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:731
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8983
FunctionTemplateDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
ASTContext & Context
Definition: Sema.h:908
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2632
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ASTContext & getASTContext() const
Definition: Sema.h:531
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.
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition: Sema.h:8665
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...
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14938
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15345
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
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
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:431
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
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.
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
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6661
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6729
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
bool wasDeclaredWithTypename() const
Whether this template type parameter was declared with the 'typename' keyword.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
bool hasTypeConstraint() const
Determine whether this template parameter has a type-constraint.
const TypeConstraint * getTypeConstraint() const
Returns the type constraint associated with this template parameter (if any).
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a template type parameter pack that has a known list of different type-cons...
bool isParameterPack() const
Returns whether this is a parameter pack.
unsigned getNumExpansionParameters() const
Retrieves the number of parameters in an expanded parameter pack.
unsigned getIndex() const
Definition: Type.h:6343
unsigned getDepth() const
Definition: Type.h:6342
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
QualType RebuildTemplateSpecializationType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &Args)
Build a new template specialization type.
QualType TransformType(QualType T)
Transforms the given type into another type.
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5576
Declaration of an alias template.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3398
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
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
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2715
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7902
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:7913
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
static TypeTraitExpr * Create(const ASTContext &C, QualType T, SourceLocation Loc, TypeTrait Kind, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc, bool Value)
Create a new type trait expression.
Definition: ExprCXX.cpp:1876
The base class of the type hierarchy.
Definition: Type.h:1828
bool isRValueReferenceType() const
Definition: Type.h:8212
bool isArrayType() const
Definition: Type.h:8258
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isLValueReferenceType() const
Definition: Type.h:8208
bool isFunctionType() const
Definition: Type.h:8182
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5525
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3413
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3463
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
TypedefNameDecl * getTypedefNameDecl() const
Definition: TypeLoc.h:695
QualType getType() const
Definition: Decl.h:682
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
Provides information about an attempted template argument deduction, whose success or failure was des...
The JSON file list parser is used to communicate input to InstallAPI.
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
@ SC_None
Definition: Specifiers.h:250
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
@ AS_public
Definition: Specifiers.h:124
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
Extra information about a function prototype.
Definition: Type.h:5187
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12760
A stack object to be created when performing template instantiation.
Definition: Sema.h:12838