Debian Codegraph @

clang/lib/Sema/SemaConcept.cpp

raw
1 //===-- SemaConcept.cpp - Semantic Analysis for Constraints and Concepts --===//
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 semantic analysis for C++ constraints and concepts.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/Sema/SemaConcept.h"
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConcept.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/ExprConcepts.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/Basic/OperatorPrecedence.h"
21 #include "clang/Sema/EnterExpressionEvaluationContext.h"
22 #include "clang/Sema/Initialization.h"
23 #include "clang/Sema/Overload.h"
24 #include "clang/Sema/ScopeInfo.h"
25 #include "clang/Sema/Sema.h"
26 #include "clang/Sema/SemaInternal.h"
27 #include "clang/Sema/Template.h"
28 #include "clang/Sema/TemplateDeduction.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/PointerUnion.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/SaveAndRestore.h"
33 #include "llvm/Support/TimeProfiler.h"
34
35 using namespace clang;
36 using namespace sema;
37
38 namespace {
39 class LogicalBinOp {
40 SourceLocation Loc;
41 OverloadedOperatorKind Op = OO_None;
42 const Expr *LHS = nullptr;
43 const Expr *RHS = nullptr;
44
45 public:
46 LogicalBinOp(const Expr *E) {
47 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
48 Op = BinaryOperator::getOverloadedOperator(BO->getOpcode());
49 LHS = BO->getLHS();
50 RHS = BO->getRHS();
51 Loc = BO->getExprLoc();
52 } else if (auto *OO = dyn_cast<CXXOperatorCallExpr>(E)) {
53 // If OO is not || or && it might not have exactly 2 arguments.
54 if (OO->getNumArgs() == 2) {
55 Op = OO->getOperator();
56 LHS = OO->getArg(0);
57 RHS = OO->getArg(1);
58 Loc = OO->getOperatorLoc();
59 }
60 }
61 }
62
63 bool isAnd() const { return Op == OO_AmpAmp; }
64 bool isOr() const { return Op == OO_PipePipe; }
65 explicit operator bool() const { return isAnd() || isOr(); }
66
67 const Expr *getLHS() const { return LHS; }
68 const Expr *getRHS() const { return RHS; }
69 OverloadedOperatorKind getOp() const { return Op; }
70
71 ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS) const {
72 return recreateBinOp(SemaRef, LHS, const_cast<Expr *>(getRHS()));
73 }
74
75 ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS,
76 ExprResult RHS) const {
77 assert((isAnd() || isOr()) && "Not the right kind of op?");
78 assert((!LHS.isInvalid() && !RHS.isInvalid()) && "not good expressions?");
79
80 if (!LHS.isUsable() || !RHS.isUsable())
81 return ExprEmpty();
82
83 // We should just be able to 'normalize' these to the builtin Binary
84 // Operator, since that is how they are evaluated in constriant checks.
85 return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
86 BinaryOperator::getOverloadedOpcode(Op),
87 SemaRef.Context.BoolTy, VK_PRValue,
88 OK_Ordinary, Loc, FPOptionsOverride{});
89 }
90 };
91 } // namespace
92
93 bool Sema::CheckConstraintExpression(const Expr *ConstraintExpression,
94 Token NextToken, bool *PossibleNonPrimary,
95 bool IsTrailingRequiresClause) {
96 // C++2a [temp.constr.atomic]p1
97 // ..E shall be a constant expression of type bool.
98
99 ConstraintExpression = ConstraintExpression->IgnoreParenImpCasts();
100
101 if (LogicalBinOp BO = ConstraintExpression) {
102 return CheckConstraintExpression(BO.getLHS(), NextToken,
103 PossibleNonPrimary) &&
104 CheckConstraintExpression(BO.getRHS(), NextToken,
105 PossibleNonPrimary);
106 } else if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpression))
107 return CheckConstraintExpression(C->getSubExpr(), NextToken,
108 PossibleNonPrimary);
109
110 QualType Type = ConstraintExpression->getType();
111
112 auto CheckForNonPrimary = [&] {
113 if (!PossibleNonPrimary)
114 return;
115
116 *PossibleNonPrimary =
117 // We have the following case:
118 // template<typename> requires func(0) struct S { };
119 // The user probably isn't aware of the parentheses required around
120 // the function call, and we're only going to parse 'func' as the
121 // primary-expression, and complain that it is of non-bool type.
122 //
123 // However, if we're in a lambda, this might also be:
124 // []<typename> requires var () {};
125 // Which also looks like a function call due to the lambda parentheses,
126 // but unlike the first case, isn't an error, so this check is skipped.
127 (NextToken.is(tok::l_paren) &&
128 (IsTrailingRequiresClause ||
129 (Type->isDependentType() &&
130 isa<UnresolvedLookupExpr>(ConstraintExpression) &&
131 !dyn_cast_if_present<LambdaScopeInfo>(getCurFunction())) ||
132 Type->isFunctionType() ||
133 Type->isSpecificBuiltinType(BuiltinType::Overload))) ||
134 // We have the following case:
135 // template<typename T> requires size_<T> == 0 struct S { };
136 // The user probably isn't aware of the parentheses required around
137 // the binary operator, and we're only going to parse 'func' as the
138 // first operand, and complain that it is of non-bool type.
139 getBinOpPrecedence(NextToken.getKind(),
140 /*GreaterThanIsOperator=*/true,
141 getLangOpts().CPlusPlus11) > prec::LogicalAnd;
142 };
143
144 // An atomic constraint!
145 if (ConstraintExpression->isTypeDependent()) {
146 CheckForNonPrimary();
147 return true;
148 }
149
150 if (!Context.hasSameUnqualifiedType(Type, Context.BoolTy)) {
151 Diag(ConstraintExpression->getExprLoc(),
152 diag::err_non_bool_atomic_constraint)
153 << Type << ConstraintExpression->getSourceRange();
154 CheckForNonPrimary();
155 return false;
156 }
157
158 if (PossibleNonPrimary)
159 *PossibleNonPrimary = false;
160 return true;
161 }
162
163 namespace {
164 struct SatisfactionStackRAII {
165 Sema &SemaRef;
166 bool Inserted = false;
167 SatisfactionStackRAII(Sema &SemaRef, const NamedDecl *ND,
168 const llvm::FoldingSetNodeID &FSNID)
169 : SemaRef(SemaRef) {
170 if (ND) {
171 SemaRef.PushSatisfactionStackEntry(ND, FSNID);
172 Inserted = true;
173 }
174 }
175 ~SatisfactionStackRAII() {
176 if (Inserted)
177 SemaRef.PopSatisfactionStackEntry();
178 }
179 };
180 } // namespace
181
182 static bool DiagRecursiveConstraintEval(
183 Sema &S, llvm::FoldingSetNodeID &ID, const NamedDecl *Templ, const Expr *E,
184 const MultiLevelTemplateArgumentList *MLTAL = nullptr) {
185 E->Profile(ID, S.Context, /*Canonical=*/true);
186 if (MLTAL) {
187 for (const auto &List : *MLTAL)
188 for (const auto &TemplateArg : List.Args)
189 S.Context.getCanonicalTemplateArgument(TemplateArg)
190 .Profile(ID, S.Context);
191 }
192 if (S.SatisfactionStackContains(Templ, ID)) {
193 S.Diag(E->getExprLoc(), diag::err_constraint_depends_on_self)
194 << E << E->getSourceRange();
195 return true;
196 }
197 return false;
198 }
199
200 // Figure out the to-translation-unit depth for this function declaration for
201 // the purpose of seeing if they differ by constraints. This isn't the same as
202 // getTemplateDepth, because it includes already instantiated parents.
203 static unsigned
204 CalculateTemplateDepthForConstraints(Sema &S, const NamedDecl *ND,
205 bool SkipForSpecialization = false) {
206 MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
207 ND, ND->getLexicalDeclContext(), /*Final=*/false,
208 /*Innermost=*/std::nullopt,
209 /*RelativeToPrimary=*/true,
210 /*Pattern=*/nullptr,
211 /*ForConstraintInstantiation=*/true, SkipForSpecialization);
212 return MLTAL.getNumLevels();
213 }
214
215 namespace {
216 class AdjustConstraints : public TreeTransform<AdjustConstraints> {
217 unsigned TemplateDepth = 0;
218
219 bool RemoveNonPackExpansionPacks = false;
220
221 public:
222 using inherited = TreeTransform<AdjustConstraints>;
223 AdjustConstraints(Sema &SemaRef, unsigned TemplateDepth,
224 bool RemoveNonPackExpansionPacks = false)
225 : inherited(SemaRef), TemplateDepth(TemplateDepth),
226 RemoveNonPackExpansionPacks(RemoveNonPackExpansionPacks) {}
227
228 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
229 UnsignedOrNone NumExpansions) {
230 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc, NumExpansions);
231 }
232
233 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
234 SourceLocation EllipsisLoc,
235 UnsignedOrNone NumExpansions) {
236 if (!RemoveNonPackExpansionPacks)
237 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,
238 NumExpansions);
239 return Pattern;
240 }
241
242 bool PreparePackForExpansion(TemplateArgumentLoc In, bool Uneval,
243 TemplateArgumentLoc &Out, UnexpandedInfo &Info) {
244 if (!RemoveNonPackExpansionPacks)
245 return inherited::PreparePackForExpansion(In, Uneval, Out, Info);
246 assert(In.getArgument().isPackExpansion());
247 Out = In;
248 Info.Expand = false;
249 return false;
250 }
251
252 using inherited::TransformTemplateTypeParmType;
253 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
254 TemplateTypeParmTypeLoc TL, bool) {
255 const TemplateTypeParmType *T = TL.getTypePtr();
256
257 TemplateTypeParmDecl *NewTTPDecl = nullptr;
258 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
259 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
260 TransformDecl(TL.getNameLoc(), OldTTPDecl));
261
262 QualType Result = getSema().Context.getTemplateTypeParmType(
263 T->getDepth() + TemplateDepth, T->getIndex(),
264 RemoveNonPackExpansionPacks ? false : T->isParameterPack(), NewTTPDecl);
265 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
266 NewTL.setNameLoc(TL.getNameLoc());
267 return Result;
268 }
269
270 bool AlreadyTransformed(QualType T) {
271 if (T.isNull())
272 return true;
273
274 if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||
275 T->containsUnexpandedParameterPack())
276 return false;
277 return true;
278 }
279 };
280 } // namespace
281
282 namespace {
283
284 // FIXME: Convert it to DynamicRecursiveASTVisitor
285 class HashParameterMapping : public RecursiveASTVisitor<HashParameterMapping> {
286 using inherited = RecursiveASTVisitor<HashParameterMapping>;
287 friend inherited;
288
289 Sema &SemaRef;
290 const MultiLevelTemplateArgumentList &TemplateArgs;
291 llvm::FoldingSetNodeID &ID;
292 llvm::SmallVector<TemplateArgument, 10> UsedTemplateArgs;
293
294 UnsignedOrNone OuterPackSubstIndex;
295
296 bool shouldVisitTemplateInstantiations() const { return true; }
297
298 public:
299 HashParameterMapping(Sema &SemaRef,
300 const MultiLevelTemplateArgumentList &TemplateArgs,
301 llvm::FoldingSetNodeID &ID,
302 UnsignedOrNone OuterPackSubstIndex)
303 : SemaRef(SemaRef), TemplateArgs(TemplateArgs), ID(ID),
304 OuterPackSubstIndex(OuterPackSubstIndex) {}
305
306 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
307 // A lambda expression can introduce template parameters that don't have
308 // corresponding template arguments yet.
309 if (T->getDepth() >= TemplateArgs.getNumLevels())
310 return true;
311
312 // There might not be a corresponding template argument before substituting
313 // into the parameter mapping, e.g. a sizeof... expression.
314 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex()))
315 return true;
316
317 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
318
319 // In concept parameter mapping for fold expressions, packs that aren't
320 // expanded in place are treated as having non-pack dependency, so that
321 // a PackExpansionType won't prevent expanding the packs outside the
322 // TreeTransform. However we still need to check the pack at this point.
323 if ((T->isParameterPack() ||
324 (T->getDecl() && T->getDecl()->isTemplateParameterPack())) &&
325 SemaRef.ArgPackSubstIndex) {
326 assert(Arg.getKind() == TemplateArgument::Pack &&
327 "Missing argument pack");
328
329 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
330 }
331
332 UsedTemplateArgs.push_back(
333 SemaRef.Context.getCanonicalTemplateArgument(Arg));
334 return true;
335 }
336
337 bool VisitDeclRefExpr(DeclRefExpr *E) {
338 NamedDecl *D = E->getDecl();
339 NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D);
340 if (!NTTP)
341 return TraverseDecl(D);
342
343 if (NTTP->getDepth() >= TemplateArgs.getNumLevels())
344 return true;
345
346 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(), NTTP->getIndex()))
347 return true;
348
349 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
350 if (NTTP->isParameterPack() && SemaRef.ArgPackSubstIndex) {
351 assert(Arg.getKind() == TemplateArgument::Pack &&
352 "Missing argument pack");
353 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
354 }
355
356 UsedTemplateArgs.push_back(
357 SemaRef.Context.getCanonicalTemplateArgument(Arg));
358 return true;
359 }
360
361 bool VisitTypedefType(TypedefType *TT) {
362 return inherited::TraverseType(TT->desugar());
363 }
364
365 bool TraverseDecl(Decl *D) {
366 if (auto *VD = dyn_cast<ValueDecl>(D)) {
367 if (auto *Var = dyn_cast<VarDecl>(VD))
368 TraverseStmt(Var->getInit());
369 return TraverseType(VD->getType());
370 }
371
372 return inherited::TraverseDecl(D);
373 }
374
375 bool TraverseCallExpr(CallExpr *CE) {
376 inherited::TraverseStmt(CE->getCallee());
377
378 for (Expr *Arg : CE->arguments())
379 inherited::TraverseStmt(Arg);
380
381 return true;
382 }
383
384 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) {
385 // We don't care about TypeLocs. So traverse Types instead.
386 return TraverseType(TL.getType().getCanonicalType(), TraverseQualifier);
387 }
388
389 bool TraverseTagType(const TagType *T, bool TraverseQualifier) {
390 // T's parent can be dependent while T doesn't have any template arguments.
391 // We should have already traversed its qualifier.
392 // FIXME: Add an assert to catch cases where we failed to profile the
393 // concept.
394 return true;
395 }
396
397 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
398 bool TraverseQualifier) {
399 return TraverseTemplateArguments(T->getTemplateArgs(SemaRef.Context));
400 }
401
402 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
403 if (!Arg.containsUnexpandedParameterPack() || Arg.isPackExpansion()) {
404 // Act as if we are fully expanding this pack, if it is a PackExpansion.
405 Sema::ArgPackSubstIndexRAII _1(SemaRef, std::nullopt);
406 llvm::SaveAndRestore<UnsignedOrNone> _2(OuterPackSubstIndex,
407 std::nullopt);
408 return inherited::TraverseTemplateArgument(Arg);
409 }
410
411 Sema::ArgPackSubstIndexRAII _1(SemaRef, OuterPackSubstIndex);
412 return inherited::TraverseTemplateArgument(Arg);
413 }
414
415 bool TraverseSizeOfPackExpr(SizeOfPackExpr *SOPE) {
416 return TraverseDecl(SOPE->getPack());
417 }
418
419 bool VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
420 return inherited::TraverseStmt(E->getReplacement());
421 }
422
423 bool TraverseTemplateName(TemplateName Template) {
424 if (auto *TTP = dyn_cast_if_present<TemplateTemplateParmDecl>(
425 Template.getAsTemplateDecl());
426 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
427 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
428 TTP->getPosition()))
429 return true;
430
431 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
432 if (TTP->isParameterPack() && SemaRef.ArgPackSubstIndex) {
433 assert(Arg.getKind() == TemplateArgument::Pack &&
434 "Missing argument pack");
435 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
436 }
437 assert(!Arg.getAsTemplate().isNull() &&
438 "Null template template argument");
439 UsedTemplateArgs.push_back(
440 SemaRef.Context.getCanonicalTemplateArgument(Arg));
441 }
442 return inherited::TraverseTemplateName(Template);
443 }
444
445 void VisitConstraint(const NormalizedConstraintWithParamMapping &Constraint) {
446 if (!Constraint.hasParameterMapping()) {
447 for (const auto &List : TemplateArgs)
448 for (const TemplateArgument &Arg : List.Args)
449 SemaRef.Context.getCanonicalTemplateArgument(Arg).Profile(
450 ID, SemaRef.Context);
451 return;
452 }
453
454 llvm::ArrayRef<TemplateArgumentLoc> Mapping =
455 Constraint.getParameterMapping();
456 for (auto &ArgLoc : Mapping) {
457 TemplateArgument Canonical =
458 SemaRef.Context.getCanonicalTemplateArgument(ArgLoc.getArgument());
459 // We don't want sugars to impede the profile of cache.
460 UsedTemplateArgs.push_back(Canonical);
461 TraverseTemplateArgument(Canonical);
462 }
463
464 for (auto &Used : UsedTemplateArgs) {
465 llvm::FoldingSetNodeID R;
466 Used.Profile(R, SemaRef.Context);
467 ID.AddNodeID(R);
468 }
469 }
470 };
471
472 class ConstraintSatisfactionChecker {
473 Sema &S;
474 const NamedDecl *Template;
475 SourceLocation TemplateNameLoc;
476 UnsignedOrNone PackSubstitutionIndex;
477 ConstraintSatisfaction &Satisfaction;
478 bool BuildExpression;
479
480 private:
481 template <class Constraint>
482 UnsignedOrNone getOuterPackIndex(const Constraint &C) const {
483 return C.getPackSubstitutionIndex() ? C.getPackSubstitutionIndex()
484 : PackSubstitutionIndex;
485 }
486
487 ExprResult
488 EvaluateAtomicConstraint(const Expr *AtomicExpr,
489 const MultiLevelTemplateArgumentList &MLTAL);
490
491 UnsignedOrNone EvaluateFoldExpandedConstraintSize(
492 const FoldExpandedConstraint &FE,
493 const MultiLevelTemplateArgumentList &MLTAL);
494
495 // XXX: It is SLOW! Use it very carefully.
496 std::optional<MultiLevelTemplateArgumentList> SubstitutionInTemplateArguments(
497 const NormalizedConstraintWithParamMapping &Constraint,
498 const MultiLevelTemplateArgumentList &MLTAL,
499 llvm::SmallVector<TemplateArgument> &SubstitutedOuterMost);
500
501 ExprResult EvaluateSlow(const AtomicConstraint &Constraint,
502 const MultiLevelTemplateArgumentList &MLTAL);
503
504 ExprResult Evaluate(const AtomicConstraint &Constraint,
505 const MultiLevelTemplateArgumentList &MLTAL);
506
507 ExprResult EvaluateSlow(const FoldExpandedConstraint &Constraint,
508 const MultiLevelTemplateArgumentList &MLTAL);
509
510 ExprResult Evaluate(const FoldExpandedConstraint &Constraint,
511 const MultiLevelTemplateArgumentList &MLTAL);
512
513 ExprResult EvaluateSlow(const ConceptIdConstraint &Constraint,
514 const MultiLevelTemplateArgumentList &MLTAL,
515 unsigned int Size);
516
517 ExprResult Evaluate(const ConceptIdConstraint &Constraint,
518 const MultiLevelTemplateArgumentList &MLTAL);
519
520 ExprResult Evaluate(const CompoundConstraint &Constraint,
521 const MultiLevelTemplateArgumentList &MLTAL);
522
523 public:
524 ConstraintSatisfactionChecker(Sema &SemaRef, const NamedDecl *Template,
525 SourceLocation TemplateNameLoc,
526 UnsignedOrNone PackSubstitutionIndex,
527 ConstraintSatisfaction &Satisfaction,
528 bool BuildExpression)
529 : S(SemaRef), Template(Template), TemplateNameLoc(TemplateNameLoc),
530 PackSubstitutionIndex(PackSubstitutionIndex),
531 Satisfaction(Satisfaction), BuildExpression(BuildExpression) {}
532
533 ExprResult Evaluate(const NormalizedConstraint &Constraint,
534 const MultiLevelTemplateArgumentList &MLTAL);
535 };
536
537 StringRef allocateStringFromConceptDiagnostic(const Sema &S,
538 const PartialDiagnostic Diag) {
539 SmallString<128> DiagString;
540 DiagString = ": ";
541 Diag.EmitToString(S.getDiagnostics(), DiagString);
542 return S.getASTContext().backupStr(DiagString);
543 }
544
545 } // namespace
546
547 ExprResult ConstraintSatisfactionChecker::EvaluateAtomicConstraint(
548 const Expr *AtomicExpr, const MultiLevelTemplateArgumentList &MLTAL) {
549 llvm::FoldingSetNodeID ID;
550 if (Template &&
551 DiagRecursiveConstraintEval(S, ID, Template, AtomicExpr, &MLTAL)) {
552 Satisfaction.IsSatisfied = false;
553 Satisfaction.ContainsErrors = true;
554 return ExprEmpty();
555 }
556 SatisfactionStackRAII StackRAII(S, Template, ID);
557
558 // Atomic constraint - substitute arguments and check satisfaction.
559 ExprResult SubstitutedExpression = const_cast<Expr *>(AtomicExpr);
560 {
561 TemplateDeductionInfo Info(TemplateNameLoc);
562 Sema::InstantiatingTemplate Inst(
563 S, AtomicExpr->getBeginLoc(),
564 Sema::InstantiatingTemplate::ConstraintSubstitution{},
565 // FIXME: improve const-correctness of InstantiatingTemplate
566 const_cast<NamedDecl *>(Template), AtomicExpr->getSourceRange());
567 if (Inst.isInvalid())
568 return ExprError();
569
570 // We do not want error diagnostics escaping here.
571 Sema::SFINAETrap Trap(S, Info);
572 SubstitutedExpression =
573 S.SubstConstraintExpr(const_cast<Expr *>(AtomicExpr), MLTAL);
574
575 if (SubstitutedExpression.isInvalid() || Trap.hasErrorOccurred()) {
576 // C++2a [temp.constr.atomic]p1
577 // ...If substitution results in an invalid type or expression, the
578 // constraint is not satisfied.
579 if (!Trap.hasErrorOccurred())
580 // A non-SFINAE error has occurred as a result of this
581 // substitution.
582 return ExprError();
583
584 PartialDiagnosticAt SubstDiag{SourceLocation(),
585 PartialDiagnostic::NullDiagnostic()};
586 Info.takeSFINAEDiagnostic(SubstDiag);
587 // FIXME: This is an unfortunate consequence of there
588 // being no serialization code for PartialDiagnostics and the fact
589 // that serializing them would likely take a lot more storage than
590 // just storing them as strings. We would still like, in the
591 // future, to serialize the proper PartialDiagnostic as serializing
592 // it as a string defeats the purpose of the diagnostic mechanism.
593 Satisfaction.Details.emplace_back(
594 new (S.Context) ConstraintSubstitutionDiagnostic{
595 SubstDiag.first,
596 allocateStringFromConceptDiagnostic(S, SubstDiag.second)});
597 Satisfaction.IsSatisfied = false;
598 return ExprEmpty();
599 }
600 }
601
602 if (!S.CheckConstraintExpression(SubstitutedExpression.get()))
603 return ExprError();
604
605 // [temp.constr.atomic]p3: To determine if an atomic constraint is
606 // satisfied, the parameter mapping and template arguments are first
607 // substituted into its expression. If substitution results in an
608 // invalid type or expression, the constraint is not satisfied.
609 // Otherwise, the lvalue-to-rvalue conversion is performed if necessary,
610 // and E shall be a constant expression of type bool.
611 //
612 // Perform the L to R Value conversion if necessary. We do so for all
613 // non-PRValue categories, else we fail to extend the lifetime of
614 // temporaries, and that fails the constant expression check.
615 if (!SubstitutedExpression.get()->isPRValue())
616 SubstitutedExpression = ImplicitCastExpr::Create(
617 S.Context, SubstitutedExpression.get()->getType(), CK_LValueToRValue,
618 SubstitutedExpression.get(),
619 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
620
621 return SubstitutedExpression;
622 }
623
624 std::optional<MultiLevelTemplateArgumentList>
625 ConstraintSatisfactionChecker::SubstitutionInTemplateArguments(
626 const NormalizedConstraintWithParamMapping &Constraint,
627 const MultiLevelTemplateArgumentList &MLTAL,
628 llvm::SmallVector<TemplateArgument> &SubstitutedOutermost) {
629
630 if (!Constraint.hasParameterMapping())
631 return std::move(MLTAL);
632
633 // The mapping is empty, meaning no template arguments are needed for
634 // evaluation.
635 if (Constraint.getParameterMapping().empty())
636 return MultiLevelTemplateArgumentList();
637
638 TemplateDeductionInfo Info(Constraint.getBeginLoc());
639 Sema::SFINAETrap Trap(S, Info);
640 Sema::InstantiatingTemplate Inst(
641 S, Constraint.getBeginLoc(),
642 Sema::InstantiatingTemplate::ConstraintSubstitution{},
643 // FIXME: improve const-correctness of InstantiatingTemplate
644 const_cast<NamedDecl *>(Template), Constraint.getSourceRange());
645 if (Inst.isInvalid())
646 return std::nullopt;
647
648 TemplateArgumentListInfo SubstArgs;
649 Sema::ArgPackSubstIndexRAII SubstIndex(S, getOuterPackIndex(Constraint));
650
651 if (S.SubstTemplateArgumentsInParameterMapping(
652 Constraint.getParameterMapping(), Constraint.getBeginLoc(), MLTAL,
653 SubstArgs)) {
654 Satisfaction.IsSatisfied = false;
655 return std::nullopt;
656 }
657
658 Sema::CheckTemplateArgumentInfo CTAI;
659 auto *TD = const_cast<TemplateDecl *>(
660 cast<TemplateDecl>(Constraint.getConstraintDecl()));
661 if (S.CheckTemplateArgumentList(TD, Constraint.getUsedTemplateParamList(),
662 TD->getLocation(), SubstArgs,
663 /*DefaultArguments=*/{},
664 /*PartialTemplateArgs=*/false, CTAI))
665 return std::nullopt;
666 const NormalizedConstraint::OccurenceList &Used =
667 Constraint.mappingOccurenceList();
668 // The empty MLTAL situation should only occur when evaluating non-dependent
669 // constraints.
670 if (MLTAL.getNumSubstitutedLevels())
671 SubstitutedOutermost =
672 llvm::to_vector_of<TemplateArgument>(MLTAL.getOutermost());
673 unsigned Offset = 0;
674 for (unsigned I = 0, MappedIndex = 0; I < Used.size(); I++) {
675 TemplateArgument Arg;
676 if (Used[I])
677 Arg = S.Context.getCanonicalTemplateArgument(
678 CTAI.SugaredConverted[MappedIndex++]);
679 if (I < SubstitutedOutermost.size()) {
680 SubstitutedOutermost[I] = Arg;
681 Offset = I + 1;
682 } else {
683 SubstitutedOutermost.push_back(Arg);
684 Offset = SubstitutedOutermost.size();
685 }
686 }
687 if (Offset < SubstitutedOutermost.size())
688 SubstitutedOutermost.erase(SubstitutedOutermost.begin() + Offset);
689
690 MultiLevelTemplateArgumentList SubstitutedTemplateArgs;
691 SubstitutedTemplateArgs.addOuterTemplateArguments(TD, SubstitutedOutermost,
692 /*Final=*/false);
693 return std::move(SubstitutedTemplateArgs);
694 }
695
696 ExprResult ConstraintSatisfactionChecker::EvaluateSlow(
697 const AtomicConstraint &Constraint,
698 const MultiLevelTemplateArgumentList &MLTAL) {
699 EnterExpressionEvaluationContext ConstantEvaluated(
700 S, Sema::ExpressionEvaluationContext::ConstantEvaluated,
701 Sema::ReuseLambdaContextDecl);
702
703 llvm::SmallVector<TemplateArgument> SubstitutedOutermost;
704 std::optional<MultiLevelTemplateArgumentList> SubstitutedArgs =
705 SubstitutionInTemplateArguments(Constraint, MLTAL, SubstitutedOutermost);
706 if (!SubstitutedArgs) {
707 Satisfaction.IsSatisfied = false;
708 return ExprEmpty();
709 }
710
711 Sema::ArgPackSubstIndexRAII SubstIndex(S, PackSubstitutionIndex);
712 ExprResult SubstitutedAtomicExpr = EvaluateAtomicConstraint(
713 Constraint.getConstraintExpr(), *SubstitutedArgs);
714
715 if (SubstitutedAtomicExpr.isInvalid())
716 return ExprError();
717
718 if (SubstitutedAtomicExpr.isUnset())
719 // Evaluator has decided satisfaction without yielding an expression.
720 return ExprEmpty();
721
722 // We don't have the ability to evaluate this, since it contains a
723 // RecoveryExpr, so we want to fail overload resolution. Otherwise,
724 // we'd potentially pick up a different overload, and cause confusing
725 // diagnostics. SO, add a failure detail that will cause us to make this
726 // overload set not viable.
727 if (SubstitutedAtomicExpr.get()->containsErrors()) {
728 Satisfaction.IsSatisfied = false;
729 Satisfaction.ContainsErrors = true;
730
731 PartialDiagnostic Msg = S.PDiag(diag::note_constraint_references_error);
732 Satisfaction.Details.emplace_back(
733 new (S.Context) ConstraintSubstitutionDiagnostic{
734 SubstitutedAtomicExpr.get()->getBeginLoc(),
735 allocateStringFromConceptDiagnostic(S, Msg)});
736 return SubstitutedAtomicExpr;
737 }
738
739 if (SubstitutedAtomicExpr.get()->isValueDependent()) {
740 Satisfaction.IsSatisfied = true;
741 Satisfaction.ContainsErrors = false;
742 return SubstitutedAtomicExpr;
743 }
744
745 SmallVector<PartialDiagnosticAt, 2> EvaluationDiags;
746 Expr::EvalResult EvalResult;
747 EvalResult.Diag = &EvaluationDiags;
748 if (!SubstitutedAtomicExpr.get()->EvaluateAsConstantExpr(EvalResult,
749 S.Context) ||
750 !EvaluationDiags.empty()) {
751 // C++2a [temp.constr.atomic]p1
752 // ...E shall be a constant expression of type bool.
753 S.Diag(SubstitutedAtomicExpr.get()->getBeginLoc(),
754 diag::err_non_constant_constraint_expression)
755 << SubstitutedAtomicExpr.get()->getSourceRange();
756 for (const PartialDiagnosticAt &PDiag : EvaluationDiags)
757 S.Diag(PDiag.first, PDiag.second);
758 return ExprError();
759 }
760
761 assert(EvalResult.Val.isInt() &&
762 "evaluating bool expression didn't produce int");
763 Satisfaction.IsSatisfied = EvalResult.Val.getInt().getBoolValue();
764 if (!Satisfaction.IsSatisfied)
765 Satisfaction.Details.emplace_back(SubstitutedAtomicExpr.get());
766
767 return SubstitutedAtomicExpr;
768 }
769
770 ExprResult ConstraintSatisfactionChecker::Evaluate(
771 const AtomicConstraint &Constraint,
772 const MultiLevelTemplateArgumentList &MLTAL) {
773
774 unsigned Size = Satisfaction.Details.size();
775 llvm::FoldingSetNodeID ID;
776 UnsignedOrNone OuterPackSubstIndex = getOuterPackIndex(Constraint);
777
778 ID.AddPointer(Constraint.getConstraintExpr());
779 ID.AddInteger(OuterPackSubstIndex.toInternalRepresentation());
780 HashParameterMapping(S, MLTAL, ID, OuterPackSubstIndex)
781 .VisitConstraint(Constraint);
782
783 if (auto Iter = S.UnsubstitutedConstraintSatisfactionCache.find(ID);
784 Iter != S.UnsubstitutedConstraintSatisfactionCache.end()) {
785 auto &Cached = Iter->second.Satisfaction;
786 Satisfaction.ContainsErrors = Cached.ContainsErrors;
787 Satisfaction.IsSatisfied = Cached.IsSatisfied;
788 Satisfaction.Details.insert(Satisfaction.Details.begin() + Size,
789 Cached.Details.begin(), Cached.Details.end());
790 return Iter->second.SubstExpr;
791 }
792
793 ExprResult E = EvaluateSlow(Constraint, MLTAL);
794
795 UnsubstitutedConstraintSatisfactionCacheResult Cache;
796 Cache.Satisfaction.ContainsErrors = Satisfaction.ContainsErrors;
797 Cache.Satisfaction.IsSatisfied = Satisfaction.IsSatisfied;
798 Cache.Satisfaction.Details.insert(Cache.Satisfaction.Details.end(),
799 Satisfaction.Details.begin() + Size,
800 Satisfaction.Details.end());
801 Cache.SubstExpr = E;
802 S.UnsubstitutedConstraintSatisfactionCache.insert({ID, std::move(Cache)});
803
804 return E;
805 }
806
807 UnsignedOrNone
808 ConstraintSatisfactionChecker::EvaluateFoldExpandedConstraintSize(
809 const FoldExpandedConstraint &FE,
810 const MultiLevelTemplateArgumentList &MLTAL) {
811
812 Expr *Pattern = const_cast<Expr *>(FE.getPattern());
813
814 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
815 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
816 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
817 bool Expand = true;
818 bool RetainExpansion = false;
819 UnsignedOrNone NumExpansions(std::nullopt);
820 if (S.CheckParameterPacksForExpansion(
821 Pattern->getExprLoc(), Pattern->getSourceRange(), Unexpanded, MLTAL,
822 /*FailOnPackProducingTemplates=*/false, Expand, RetainExpansion,
823 NumExpansions, /*Diagnose=*/false) ||
824 !Expand || RetainExpansion)
825 return std::nullopt;
826
827 if (NumExpansions && S.getLangOpts().BracketDepth < *NumExpansions)
828 return std::nullopt;
829 return NumExpansions;
830 }
831
832 ExprResult ConstraintSatisfactionChecker::EvaluateSlow(
833 const FoldExpandedConstraint &Constraint,
834 const MultiLevelTemplateArgumentList &MLTAL) {
835
836 bool Conjunction = Constraint.getFoldOperator() ==
837 FoldExpandedConstraint::FoldOperatorKind::And;
838 unsigned EffectiveDetailEndIndex = Satisfaction.Details.size();
839
840 llvm::SmallVector<TemplateArgument> SubstitutedOutermost;
841 // FIXME: Is PackSubstitutionIndex correct?
842 llvm::SaveAndRestore _(PackSubstitutionIndex, S.ArgPackSubstIndex);
843 std::optional<MultiLevelTemplateArgumentList> SubstitutedArgs =
844 SubstitutionInTemplateArguments(
845 static_cast<const NormalizedConstraintWithParamMapping &>(Constraint),
846 MLTAL, SubstitutedOutermost);
847 if (!SubstitutedArgs) {
848 Satisfaction.IsSatisfied = false;
849 return ExprError();
850 }
851
852 ExprResult Out;
853 UnsignedOrNone NumExpansions =
854 EvaluateFoldExpandedConstraintSize(Constraint, *SubstitutedArgs);
855 if (!NumExpansions)
856 return ExprEmpty();
857
858 if (*NumExpansions == 0) {
859 Satisfaction.IsSatisfied = Conjunction;
860 return ExprEmpty();
861 }
862
863 for (unsigned I = 0; I < *NumExpansions; I++) {
864 Sema::ArgPackSubstIndexRAII SubstIndex(S, I);
865 Satisfaction.IsSatisfied = false;
866 Satisfaction.ContainsErrors = false;
867 ExprResult Expr =
868 ConstraintSatisfactionChecker(S, Template, TemplateNameLoc,
869 UnsignedOrNone(I), Satisfaction,
870 /*BuildExpression=*/false)
871 .Evaluate(Constraint.getNormalizedPattern(), *SubstitutedArgs);
872 if (BuildExpression) {
873 if (Out.isUnset() || !Expr.isUsable())
874 Out = Expr;
875 else
876 Out = BinaryOperator::Create(S.Context, Out.get(), Expr.get(),
877 Conjunction ? BinaryOperatorKind::BO_LAnd
878 : BinaryOperatorKind::BO_LOr,
879 S.Context.BoolTy, VK_PRValue, OK_Ordinary,
880 Constraint.getBeginLoc(),
881 FPOptionsOverride{});
882 }
883 if (!Conjunction && Satisfaction.IsSatisfied) {
884 Satisfaction.Details.erase(Satisfaction.Details.begin() +
885 EffectiveDetailEndIndex,
886 Satisfaction.Details.end());
887 break;
888 }
889 if (Satisfaction.IsSatisfied != Conjunction)
890 return Out;
891 }
892
893 return Out;
894 }
895
896 ExprResult ConstraintSatisfactionChecker::Evaluate(
897 const FoldExpandedConstraint &Constraint,
898 const MultiLevelTemplateArgumentList &MLTAL) {
899
900 llvm::FoldingSetNodeID ID;
901 ID.AddPointer(Constraint.getPattern());
902 HashParameterMapping(S, MLTAL, ID, std::nullopt).VisitConstraint(Constraint);
903
904 if (auto Iter = S.UnsubstitutedConstraintSatisfactionCache.find(ID);
905 Iter != S.UnsubstitutedConstraintSatisfactionCache.end()) {
906
907 auto &Cached = Iter->second.Satisfaction;
908 Satisfaction.ContainsErrors = Cached.ContainsErrors;
909 Satisfaction.IsSatisfied = Cached.IsSatisfied;
910 Satisfaction.Details.insert(Satisfaction.Details.end(),
911 Cached.Details.begin(), Cached.Details.end());
912 return Iter->second.SubstExpr;
913 }
914
915 unsigned Size = Satisfaction.Details.size();
916
917 ExprResult E = EvaluateSlow(Constraint, MLTAL);
918 UnsubstitutedConstraintSatisfactionCacheResult Cache;
919 Cache.Satisfaction.ContainsErrors = Satisfaction.ContainsErrors;
920 Cache.Satisfaction.IsSatisfied = Satisfaction.IsSatisfied;
921 Cache.Satisfaction.Details.insert(Cache.Satisfaction.Details.end(),
922 Satisfaction.Details.begin() + Size,
923 Satisfaction.Details.end());
924 Cache.SubstExpr = E;
925 S.UnsubstitutedConstraintSatisfactionCache.insert({ID, std::move(Cache)});
926 return E;
927 }
928
929 ExprResult ConstraintSatisfactionChecker::EvaluateSlow(
930 const ConceptIdConstraint &Constraint,
931 const MultiLevelTemplateArgumentList &MLTAL, unsigned Size) {
932 const ConceptReference *ConceptId = Constraint.getConceptId();
933
934 llvm::SmallVector<TemplateArgument> SubstitutedOutermost;
935 std::optional<MultiLevelTemplateArgumentList> SubstitutedArgs =
936 SubstitutionInTemplateArguments(Constraint, MLTAL, SubstitutedOutermost);
937
938 if (!SubstitutedArgs) {
939 Satisfaction.IsSatisfied = false;
940 // FIXME: diagnostics?
941 return ExprError();
942 }
943
944 Sema::ArgPackSubstIndexRAII SubstIndex(S, getOuterPackIndex(Constraint));
945
946 const ASTTemplateArgumentListInfo *Ori =
947 ConceptId->getTemplateArgsAsWritten();
948 TemplateDeductionInfo Info(TemplateNameLoc);
949 Sema::SFINAETrap Trap(S, Info);
950 Sema::InstantiatingTemplate _2(
951 S, TemplateNameLoc, Sema::InstantiatingTemplate::ConstraintSubstitution{},
952 const_cast<NamedDecl *>(Template), Constraint.getSourceRange());
953
954 TemplateArgumentListInfo OutArgs(Ori->LAngleLoc, Ori->RAngleLoc);
955 if (S.SubstTemplateArguments(Ori->arguments(), *SubstitutedArgs, OutArgs) ||
956 Trap.hasErrorOccurred()) {
957 Satisfaction.IsSatisfied = false;
958 if (!Trap.hasErrorOccurred())
959 return ExprError();
960
961 PartialDiagnosticAt SubstDiag{SourceLocation(),
962 PartialDiagnostic::NullDiagnostic()};
963 Info.takeSFINAEDiagnostic(SubstDiag);
964 // FIXME: This is an unfortunate consequence of there
965 // being no serialization code for PartialDiagnostics and the fact
966 // that serializing them would likely take a lot more storage than
967 // just storing them as strings. We would still like, in the
968 // future, to serialize the proper PartialDiagnostic as serializing
969 // it as a string defeats the purpose of the diagnostic mechanism.
970 Satisfaction.Details.insert(
971 Satisfaction.Details.begin() + Size,
972 new (S.Context) ConstraintSubstitutionDiagnostic{
973 SubstDiag.first,
974 allocateStringFromConceptDiagnostic(S, SubstDiag.second)});
975 return ExprError();
976 }
977
978 CXXScopeSpec SS;
979 SS.Adopt(ConceptId->getNestedNameSpecifierLoc());
980
981 ExprResult SubstitutedConceptId = S.CheckConceptTemplateId(
982 SS, ConceptId->getTemplateKWLoc(), ConceptId->getConceptNameInfo(),
983 ConceptId->getFoundDecl(), ConceptId->getNamedConcept(), &OutArgs,
984 /*DoCheckConstraintSatisfaction=*/false);
985
986 if (SubstitutedConceptId.isInvalid() || Trap.hasErrorOccurred())
987 return ExprError();
988
989 if (Size != Satisfaction.Details.size()) {
990 Satisfaction.Details.insert(
991 Satisfaction.Details.begin() + Size,
992 UnsatisfiedConstraintRecord(
993 SubstitutedConceptId.getAs<ConceptSpecializationExpr>()
994 ->getConceptReference()));
995 }
996 return SubstitutedConceptId;
997 }
998
999 ExprResult ConstraintSatisfactionChecker::Evaluate(
1000 const ConceptIdConstraint &Constraint,
1001 const MultiLevelTemplateArgumentList &MLTAL) {
1002
1003 const ConceptReference *ConceptId = Constraint.getConceptId();
1004 Sema::InstantiatingTemplate InstTemplate(
1005 S, ConceptId->getBeginLoc(),
1006 Sema::InstantiatingTemplate::ConstraintsCheck{},
1007 ConceptId->getNamedConcept(),
1008 // We may have empty template arguments when checking non-dependent
1009 // nested constraint expressions.
1010 // In such cases, non-SFINAE errors would have already been diagnosed
1011 // during parameter mapping substitution, so the instantiating template
1012 // arguments are less useful here.
1013 MLTAL.getNumSubstitutedLevels() ? MLTAL.getInnermost()
1014 : ArrayRef<TemplateArgument>{},
1015 Constraint.getSourceRange());
1016 if (InstTemplate.isInvalid())
1017 return ExprError();
1018
1019 unsigned Size = Satisfaction.Details.size();
1020
1021 ExprResult E = Evaluate(Constraint.getNormalizedConstraint(), MLTAL);
1022
1023 if (E.isInvalid()) {
1024 Satisfaction.Details.insert(Satisfaction.Details.begin() + Size, ConceptId);
1025 return E;
1026 }
1027
1028 // ConceptIdConstraint is only relevant for diagnostics,
1029 // so if the normalized constraint is satisfied, we should not
1030 // substitute into the constraint.
1031 if (Satisfaction.IsSatisfied)
1032 return E;
1033
1034 UnsignedOrNone OuterPackSubstIndex = getOuterPackIndex(Constraint);
1035 llvm::FoldingSetNodeID ID;
1036 ID.AddPointer(Constraint.getConceptId());
1037 ID.AddInteger(OuterPackSubstIndex.toInternalRepresentation());
1038 HashParameterMapping(S, MLTAL, ID, OuterPackSubstIndex)
1039 .VisitConstraint(Constraint);
1040
1041 if (auto Iter = S.UnsubstitutedConstraintSatisfactionCache.find(ID);
1042 Iter != S.UnsubstitutedConstraintSatisfactionCache.end()) {
1043
1044 auto &Cached = Iter->second.Satisfaction;
1045 Satisfaction.ContainsErrors = Cached.ContainsErrors;
1046 Satisfaction.IsSatisfied = Cached.IsSatisfied;
1047 Satisfaction.Details.insert(Satisfaction.Details.begin() + Size,
1048 Cached.Details.begin(), Cached.Details.end());
1049 return Iter->second.SubstExpr;
1050 }
1051
1052 ExprResult CE = EvaluateSlow(Constraint, MLTAL, Size);
1053 if (CE.isInvalid())
1054 return E;
1055 UnsubstitutedConstraintSatisfactionCacheResult Cache;
1056 Cache.Satisfaction.ContainsErrors = Satisfaction.ContainsErrors;
1057 Cache.Satisfaction.IsSatisfied = Satisfaction.IsSatisfied;
1058 Cache.Satisfaction.Details.insert(Cache.Satisfaction.Details.end(),
1059 Satisfaction.Details.begin() + Size,
1060 Satisfaction.Details.end());
1061 Cache.SubstExpr = CE;
1062 S.UnsubstitutedConstraintSatisfactionCache.insert({ID, std::move(Cache)});
1063 return CE;
1064 }
1065
1066 ExprResult ConstraintSatisfactionChecker::Evaluate(
1067 const CompoundConstraint &Constraint,
1068 const MultiLevelTemplateArgumentList &MLTAL) {
1069
1070 unsigned EffectiveDetailEndIndex = Satisfaction.Details.size();
1071
1072 bool Conjunction =
1073 Constraint.getCompoundKind() == NormalizedConstraint::CCK_Conjunction;
1074
1075 ExprResult LHS = Evaluate(Constraint.getLHS(), MLTAL);
1076
1077 if (Conjunction && (!Satisfaction.IsSatisfied || Satisfaction.ContainsErrors))
1078 return LHS;
1079
1080 if (!Conjunction && !LHS.isInvalid() && Satisfaction.IsSatisfied &&
1081 !Satisfaction.ContainsErrors)
1082 return LHS;
1083
1084 Satisfaction.ContainsErrors = false;
1085 Satisfaction.IsSatisfied = false;
1086
1087 ExprResult RHS = Evaluate(Constraint.getRHS(), MLTAL);
1088
1089 if (!Conjunction && !RHS.isInvalid() && Satisfaction.IsSatisfied &&
1090 !Satisfaction.ContainsErrors)
1091 Satisfaction.Details.erase(Satisfaction.Details.begin() +
1092 EffectiveDetailEndIndex,
1093 Satisfaction.Details.end());
1094
1095 if (!BuildExpression)
1096 return Satisfaction.ContainsErrors ? ExprError() : ExprEmpty();
1097
1098 if (!LHS.isUsable())
1099 return RHS;
1100
1101 if (!RHS.isUsable())
1102 return LHS;
1103
1104 return BinaryOperator::Create(S.Context, LHS.get(), RHS.get(),
1105 Conjunction ? BinaryOperatorKind::BO_LAnd
1106 : BinaryOperatorKind::BO_LOr,
1107 S.Context.BoolTy, VK_PRValue, OK_Ordinary,
1108 Constraint.getBeginLoc(), FPOptionsOverride{});
1109 }
1110
1111 ExprResult ConstraintSatisfactionChecker::Evaluate(
1112 const NormalizedConstraint &Constraint,
1113 const MultiLevelTemplateArgumentList &MLTAL) {
1114 switch (Constraint.getKind()) {
1115 case NormalizedConstraint::ConstraintKind::Atomic:
1116 return Evaluate(static_cast<const AtomicConstraint &>(Constraint), MLTAL);
1117
1118 case NormalizedConstraint::ConstraintKind::FoldExpanded:
1119 return Evaluate(static_cast<const FoldExpandedConstraint &>(Constraint),
1120 MLTAL);
1121
1122 case NormalizedConstraint::ConstraintKind::ConceptId:
1123 return Evaluate(static_cast<const ConceptIdConstraint &>(Constraint),
1124 MLTAL);
1125
1126 case NormalizedConstraint::ConstraintKind::Compound:
1127 return Evaluate(static_cast<const CompoundConstraint &>(Constraint), MLTAL);
1128 }
1129 llvm_unreachable("Unknown ConstraintKind enum");
1130 }
1131
1132 static bool CheckConstraintSatisfaction(
1133 Sema &S, const NamedDecl *Template,
1134 ArrayRef<AssociatedConstraint> AssociatedConstraints,
1135 const MultiLevelTemplateArgumentList &TemplateArgsLists,
1136 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
1137 Expr **ConvertedExpr, const ConceptReference *TopLevelConceptId = nullptr) {
1138
1139 if (ConvertedExpr)
1140 *ConvertedExpr = nullptr;
1141
1142 if (AssociatedConstraints.empty()) {
1143 Satisfaction.IsSatisfied = true;
1144 return false;
1145 }
1146
1147 // In the general case, we can't check satisfaction if the arguments contain
1148 // unsubstituted template parameters, even if they are purely syntactic,
1149 // because they may still turn out to be invalid after substitution.
1150 // This could be permitted in cases where this substitution will still be
1151 // attempted later and diagnosed, such as function template specializations,
1152 // but that's not the case for concept specializations.
1153 if (TemplateArgsLists.isAnyArgInstantiationDependent()) {
1154 Satisfaction.IsSatisfied = true;
1155 return false;
1156 }
1157
1158 llvm::ArrayRef<TemplateArgument> Args;
1159 if (TemplateArgsLists.getNumLevels() != 0)
1160 Args = TemplateArgsLists.getInnermost();
1161
1162 struct SynthesisContextPair {
1163 Sema::InstantiatingTemplate Inst;
1164 Sema::NonSFINAEContext NSC;
1165 SynthesisContextPair(Sema &S, NamedDecl *Template,
1166 ArrayRef<TemplateArgument> TemplateArgs,
1167 SourceRange InstantiationRange)
1168 : Inst(S, InstantiationRange.getBegin(),
1169 Sema::InstantiatingTemplate::ConstraintsCheck{}, Template,
1170 TemplateArgs, InstantiationRange),
1171 NSC(S) {}
1172 };
1173 std::optional<SynthesisContextPair> SynthesisContext;
1174 if (!TopLevelConceptId)
1175 SynthesisContext.emplace(S, const_cast<NamedDecl *>(Template), Args,
1176 TemplateIDRange);
1177
1178 const NormalizedConstraint *C =
1179 S.getNormalizedAssociatedConstraints(Template, AssociatedConstraints);
1180 if (!C) {
1181 Satisfaction.IsSatisfied = false;
1182 return true;
1183 }
1184
1185 if (TopLevelConceptId)
1186 C = ConceptIdConstraint::Create(S.getASTContext(), TopLevelConceptId,
1187 const_cast<NormalizedConstraint *>(C),
1188 Template, /*CSE=*/nullptr,
1189 S.ArgPackSubstIndex);
1190
1191 ExprResult Res = ConstraintSatisfactionChecker(
1192 S, Template, TemplateIDRange.getBegin(),
1193 S.ArgPackSubstIndex, Satisfaction,
1194 /*BuildExpression=*/ConvertedExpr != nullptr)
1195 .Evaluate(*C, TemplateArgsLists);
1196
1197 if (Res.isInvalid())
1198 return true;
1199
1200 if (Res.isUsable() && ConvertedExpr)
1201 *ConvertedExpr = Res.get();
1202
1203 return false;
1204 }
1205
1206 bool Sema::CheckConstraintSatisfaction(
1207 ConstrainedDeclOrNestedRequirement Entity,
1208 ArrayRef<AssociatedConstraint> AssociatedConstraints,
1209 const MultiLevelTemplateArgumentList &TemplateArgsLists,
1210 SourceRange TemplateIDRange, ConstraintSatisfaction &OutSatisfaction,
1211 const ConceptReference *TopLevelConceptId, Expr **ConvertedExpr) {
1212 llvm::TimeTraceScope TimeScope(
1213 "CheckConstraintSatisfaction", [TemplateIDRange, this] {
1214 return TemplateIDRange.printToString(getSourceManager());
1215 });
1216 if (AssociatedConstraints.empty()) {
1217 OutSatisfaction.IsSatisfied = true;
1218 return false;
1219 }
1220 const auto *Template = Entity.dyn_cast<const NamedDecl *>();
1221 if (!Template) {
1222 return ::CheckConstraintSatisfaction(
1223 *this, nullptr, AssociatedConstraints, TemplateArgsLists,
1224 TemplateIDRange, OutSatisfaction, ConvertedExpr, TopLevelConceptId);
1225 }
1226 // Invalid templates could make their way here. Substituting them could result
1227 // in dependent expressions.
1228 if (Template->isInvalidDecl()) {
1229 OutSatisfaction.IsSatisfied = false;
1230 return true;
1231 }
1232
1233 // A list of the template argument list flattened in a predictible manner for
1234 // the purposes of caching. The ConstraintSatisfaction type is in AST so it
1235 // has no access to the MultiLevelTemplateArgumentList, so this has to happen
1236 // here.
1237 llvm::SmallVector<TemplateArgument, 4> FlattenedArgs;
1238 for (auto List : TemplateArgsLists)
1239 for (const TemplateArgument &Arg : List.Args)
1240 FlattenedArgs.emplace_back(Context.getCanonicalTemplateArgument(Arg));
1241
1242 const NamedDecl *Owner = Template;
1243 if (TopLevelConceptId)
1244 Owner = TopLevelConceptId->getNamedConcept();
1245
1246 llvm::FoldingSetNodeID ID;
1247 ConstraintSatisfaction::Profile(ID, Context, Owner, FlattenedArgs);
1248 void *InsertPos;
1249 if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
1250 OutSatisfaction = *Cached;
1251 return false;
1252 }
1253
1254 auto Satisfaction =
1255 std::make_unique<ConstraintSatisfaction>(Owner, FlattenedArgs);
1256 if (::CheckConstraintSatisfaction(
1257 *this, Template, AssociatedConstraints, TemplateArgsLists,
1258 TemplateIDRange, *Satisfaction, ConvertedExpr, TopLevelConceptId)) {
1259 OutSatisfaction = std::move(*Satisfaction);
1260 return true;
1261 }
1262
1263 if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
1264 // The evaluation of this constraint resulted in us trying to re-evaluate it
1265 // recursively. This isn't really possible, except we try to form a
1266 // RecoveryExpr as a part of the evaluation. If this is the case, just
1267 // return the 'cached' version (which will have the same result), and save
1268 // ourselves the extra-insert. If it ever becomes possible to legitimately
1269 // recursively check a constraint, we should skip checking the 'inner' one
1270 // above, and replace the cached version with this one, as it would be more
1271 // specific.
1272 OutSatisfaction = *Cached;
1273 return false;
1274 }
1275
1276 // Else we can simply add this satisfaction to the list.
1277 OutSatisfaction = *Satisfaction;
1278 // We cannot use InsertPos here because CheckConstraintSatisfaction might have
1279 // invalidated it.
1280 // Note that entries of SatisfactionCache are deleted in Sema's destructor.
1281 SatisfactionCache.InsertNode(Satisfaction.release());
1282 return false;
1283 }
1284
1285 static ExprResult
1286 SubstituteConceptsInConstraintExpression(Sema &S, const NamedDecl *D,
1287 const ConceptSpecializationExpr *CSE,
1288 UnsignedOrNone SubstIndex) {
1289
1290 // [C++2c] [temp.constr.normal]
1291 // Otherwise, to form CE, any non-dependent concept template argument Ai
1292 // is substituted into the constraint-expression of C.
1293 // If any such substitution results in an invalid concept-id,
1294 // the program is ill-formed; no diagnostic is required.
1295
1296 ConceptDecl *Concept = CSE->getNamedConcept()->getCanonicalDecl();
1297 Sema::ArgPackSubstIndexRAII _(S, SubstIndex);
1298
1299 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1300 CSE->getTemplateArgsAsWritten();
1301 if (llvm::none_of(
1302 ArgsAsWritten->arguments(), [&](const TemplateArgumentLoc &ArgLoc) {
1303 return !ArgLoc.getArgument().isDependent() &&
1304 ArgLoc.getArgument().isConceptOrConceptTemplateParameter();
1305 })) {
1306 return Concept->getConstraintExpr();
1307 }
1308
1309 MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
1310 Concept, Concept->getLexicalDeclContext(),
1311 /*Final=*/false, CSE->getTemplateArguments(),
1312 /*RelativeToPrimary=*/true,
1313 /*Pattern=*/nullptr,
1314 /*ForConstraintInstantiation=*/true);
1315 return S.SubstConceptTemplateArguments(CSE, Concept->getConstraintExpr(),
1316 MLTAL);
1317 }
1318
1319 bool Sema::SetupConstraintScope(
1320 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
1321 const MultiLevelTemplateArgumentList &MLTAL,
1322 LocalInstantiationScope &Scope) {
1323 assert(!isLambdaCallOperator(FD) &&
1324 "Use LambdaScopeForCallOperatorInstantiationRAII to handle lambda "
1325 "instantiations");
1326 if (FD->isTemplateInstantiation() && FD->getPrimaryTemplate()) {
1327 FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
1328 InstantiatingTemplate Inst(
1329 *this, FD->getPointOfInstantiation(),
1330 Sema::InstantiatingTemplate::ConstraintsCheck{}, PrimaryTemplate,
1331 TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
1332 SourceRange());
1333 if (Inst.isInvalid())
1334 return true;
1335
1336 // addInstantiatedParametersToScope creates a map of 'uninstantiated' to
1337 // 'instantiated' parameters and adds it to the context. For the case where
1338 // this function is a template being instantiated NOW, we also need to add
1339 // the list of current template arguments to the list so that they also can
1340 // be picked out of the map.
1341 if (auto *SpecArgs = FD->getTemplateSpecializationArgs()) {
1342 MultiLevelTemplateArgumentList JustTemplArgs(FD, SpecArgs->asArray(),
1343 /*Final=*/false);
1344 if (addInstantiatedParametersToScope(
1345 FD, PrimaryTemplate->getTemplatedDecl(), Scope, JustTemplArgs))
1346 return true;
1347 }
1348
1349 // If this is a member function, make sure we get the parameters that
1350 // reference the original primary template.
1351 if (FunctionTemplateDecl *FromMemTempl =
1352 PrimaryTemplate->getInstantiatedFromMemberTemplate()) {
1353 if (addInstantiatedParametersToScope(FD, FromMemTempl->getTemplatedDecl(),
1354 Scope, MLTAL))
1355 return true;
1356 }
1357
1358 return false;
1359 }
1360
1361 if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization ||
1362 FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate) {
1363 FunctionDecl *InstantiatedFrom =
1364 FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization
1365 ? FD->getInstantiatedFromMemberFunction()
1366 : FD->getInstantiatedFromDecl();
1367
1368 InstantiatingTemplate Inst(
1369 *this, FD->getPointOfInstantiation(),
1370 Sema::InstantiatingTemplate::ConstraintsCheck{}, InstantiatedFrom,
1371 TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
1372 SourceRange());
1373 if (Inst.isInvalid())
1374 return true;
1375
1376 // Case where this was not a template, but instantiated as a
1377 // child-function.
1378 if (addInstantiatedParametersToScope(FD, InstantiatedFrom, Scope, MLTAL))
1379 return true;
1380 }
1381
1382 return false;
1383 }
1384
1385 // This function collects all of the template arguments for the purposes of
1386 // constraint-instantiation and checking.
1387 std::optional<MultiLevelTemplateArgumentList>
1388 Sema::SetupConstraintCheckingTemplateArgumentsAndScope(
1389 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
1390 LocalInstantiationScope &Scope) {
1391 MultiLevelTemplateArgumentList MLTAL;
1392
1393 // Collect the list of template arguments relative to the 'primary' template.
1394 // We need the entire list, since the constraint is completely uninstantiated
1395 // at this point.
1396 MLTAL =
1397 getTemplateInstantiationArgs(FD, FD->getLexicalDeclContext(),
1398 /*Final=*/false, /*Innermost=*/std::nullopt,
1399 /*RelativeToPrimary=*/true,
1400 /*Pattern=*/nullptr,
1401 /*ForConstraintInstantiation=*/true);
1402 // Lambdas are handled by LambdaScopeForCallOperatorInstantiationRAII.
1403 if (isLambdaCallOperator(FD))
1404 return MLTAL;
1405 if (SetupConstraintScope(FD, TemplateArgs, MLTAL, Scope))
1406 return std::nullopt;
1407
1408 return MLTAL;
1409 }
1410
1411 bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
1412 ConstraintSatisfaction &Satisfaction,
1413 SourceLocation UsageLoc,
1414 bool ForOverloadResolution) {
1415 // Don't check constraints if the function is dependent. Also don't check if
1416 // this is a function template specialization, as the call to
1417 // CheckFunctionTemplateConstraints after this will check it
1418 // better.
1419 if (FD->isDependentContext() ||
1420 FD->getTemplatedKind() ==
1421 FunctionDecl::TK_FunctionTemplateSpecialization) {
1422 Satisfaction.IsSatisfied = true;
1423 return false;
1424 }
1425
1426 // A lambda conversion operator has the same constraints as the call operator
1427 // and constraints checking relies on whether we are in a lambda call operator
1428 // (and may refer to its parameters), so check the call operator instead.
1429 // Note that the declarations outside of the lambda should also be
1430 // considered. Turning on the 'ForOverloadResolution' flag results in the
1431 // LocalInstantiationScope not looking into its parents, but we can still
1432 // access Decls from the parents while building a lambda RAII scope later.
1433 if (const auto *MD = dyn_cast<CXXConversionDecl>(FD);
1434 MD && isLambdaConversionOperator(const_cast<CXXConversionDecl *>(MD)))
1435 return CheckFunctionConstraints(MD->getParent()->getLambdaCallOperator(),
1436 Satisfaction, UsageLoc,
1437 /*ShouldAddDeclsFromParentScope=*/true);
1438
1439 DeclContext *CtxToSave = const_cast<FunctionDecl *>(FD);
1440
1441 while (isLambdaCallOperator(CtxToSave) || FD->isTransparentContext()) {
1442 if (isLambdaCallOperator(CtxToSave))
1443 CtxToSave = CtxToSave->getParent()->getParent();
1444 else
1445 CtxToSave = CtxToSave->getNonTransparentContext();
1446 }
1447
1448 ContextRAII SavedContext{*this, CtxToSave};
1449 LocalInstantiationScope Scope(*this, !ForOverloadResolution);
1450 std::optional<MultiLevelTemplateArgumentList> MLTAL =
1451 SetupConstraintCheckingTemplateArgumentsAndScope(
1452 const_cast<FunctionDecl *>(FD), {}, Scope);
1453
1454 if (!MLTAL)
1455 return true;
1456
1457 Qualifiers ThisQuals;
1458 CXXRecordDecl *Record = nullptr;
1459 if (auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
1460 ThisQuals = Method->getMethodQualifiers();
1461 Record = const_cast<CXXRecordDecl *>(Method->getParent());
1462 }
1463 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
1464
1465 LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
1466 *this, const_cast<FunctionDecl *>(FD), *MLTAL, Scope,
1467 ForOverloadResolution);
1468
1469 return CheckConstraintSatisfaction(
1470 FD, FD->getTrailingRequiresClause(), *MLTAL,
1471 SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
1472 Satisfaction);
1473 }
1474
1475 static const Expr *SubstituteConstraintExpressionWithoutSatisfaction(
1476 Sema &S, const Sema::TemplateCompareNewDeclInfo &DeclInfo,
1477 const Expr *ConstrExpr) {
1478 MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
1479 DeclInfo.getDecl(), DeclInfo.getDeclContext(), /*Final=*/false,
1480 /*Innermost=*/std::nullopt,
1481 /*RelativeToPrimary=*/true,
1482 /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
1483 /*SkipForSpecialization*/ false);
1484
1485 if (MLTAL.getNumSubstitutedLevels() == 0)
1486 return ConstrExpr;
1487
1488 Sema::NonSFINAEContext _(S);
1489 Sema::InstantiatingTemplate Inst(
1490 S, DeclInfo.getLocation(),
1491 Sema::InstantiatingTemplate::ConstraintNormalization{},
1492 const_cast<NamedDecl *>(DeclInfo.getDecl()), SourceRange{});
1493 if (Inst.isInvalid())
1494 return nullptr;
1495
1496 // Set up a dummy 'instantiation' scope in the case of reference to function
1497 // parameters that the surrounding function hasn't been instantiated yet. Note
1498 // this may happen while we're comparing two templates' constraint
1499 // equivalence.
1500 std::optional<LocalInstantiationScope> ScopeForParameters;
1501 if (const NamedDecl *ND = DeclInfo.getDecl();
1502 ND && ND->isFunctionOrFunctionTemplate()) {
1503 ScopeForParameters.emplace(S, /*CombineWithOuterScope=*/true);
1504 const FunctionDecl *FD = ND->getAsFunction();
1505 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate();
1506 Template && Template->getInstantiatedFromMemberTemplate())
1507 FD = Template->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
1508 for (auto *PVD : FD->parameters()) {
1509 if (ScopeForParameters->getInstantiationOfIfExists(PVD))
1510 continue;
1511 if (!PVD->isParameterPack()) {
1512 ScopeForParameters->InstantiatedLocal(PVD, PVD);
1513 continue;
1514 }
1515 // This is hacky: we're mapping the parameter pack to a size-of-1 argument
1516 // to avoid building SubstTemplateTypeParmPackTypes for
1517 // PackExpansionTypes. The SubstTemplateTypeParmPackType node would
1518 // otherwise reference the AssociatedDecl of the template arguments, which
1519 // is, in this case, the template declaration.
1520 //
1521 // However, as we are in the process of comparing potential
1522 // re-declarations, the canonical declaration is the declaration itself at
1523 // this point. So if we didn't expand these packs, we would end up with an
1524 // incorrect profile difference because we will be profiling the
1525 // canonical types!
1526 //
1527 // FIXME: Improve the "no-transform" machinery in FindInstantiatedDecl so
1528 // that we can eliminate the Scope in the cases where the declarations are
1529 // not necessarily instantiated. It would also benefit the noexcept
1530 // specifier comparison.
1531 ScopeForParameters->MakeInstantiatedLocalArgPack(PVD);
1532 ScopeForParameters->InstantiatedLocalPackArg(PVD, PVD);
1533 }
1534 }
1535
1536 std::optional<Sema::CXXThisScopeRAII> ThisScope;
1537
1538 // See TreeTransform::RebuildTemplateSpecializationType. A context scope is
1539 // essential for having an injected class as the canonical type for a template
1540 // specialization type at the rebuilding stage. This guarantees that, for
1541 // out-of-line definitions, injected class name types and their equivalent
1542 // template specializations can be profiled to the same value, which makes it
1543 // possible that e.g. constraints involving C<Class<T>> and C<Class> are
1544 // perceived identical.
1545 std::optional<Sema::ContextRAII> ContextScope;
1546 const DeclContext *DC = [&] {
1547 if (!DeclInfo.getDecl())
1548 return DeclInfo.getDeclContext();
1549 return DeclInfo.getDecl()->getFriendObjectKind()
1550 ? DeclInfo.getLexicalDeclContext()
1551 : DeclInfo.getDeclContext();
1552 }();
1553 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
1554 ThisScope.emplace(S, const_cast<CXXRecordDecl *>(RD), Qualifiers());
1555 ContextScope.emplace(S, const_cast<DeclContext *>(cast<DeclContext>(RD)),
1556 /*NewThisContext=*/false);
1557 }
1558 EnterExpressionEvaluationContext UnevaluatedContext(
1559 S, Sema::ExpressionEvaluationContext::Unevaluated,
1560 Sema::ReuseLambdaContextDecl);
1561 ExprResult SubstConstr = S.SubstConstraintExprWithoutSatisfaction(
1562 const_cast<clang::Expr *>(ConstrExpr), MLTAL);
1563 if (!SubstConstr.isUsable())
1564 return nullptr;
1565 return SubstConstr.get();
1566 }
1567
1568 bool Sema::AreConstraintExpressionsEqual(const NamedDecl *Old,
1569 const Expr *OldConstr,
1570 const TemplateCompareNewDeclInfo &New,
1571 const Expr *NewConstr) {
1572 if (OldConstr == NewConstr)
1573 return true;
1574 // C++ [temp.constr.decl]p4
1575 if (Old && !New.isInvalid() && !New.ContainsDecl(Old) &&
1576 Old->getLexicalDeclContext() != New.getLexicalDeclContext()) {
1577 if (const Expr *SubstConstr =
1578 SubstituteConstraintExpressionWithoutSatisfaction(*this, Old,
1579 OldConstr))
1580 OldConstr = SubstConstr;
1581 else
1582 return false;
1583 if (const Expr *SubstConstr =
1584 SubstituteConstraintExpressionWithoutSatisfaction(*this, New,
1585 NewConstr))
1586 NewConstr = SubstConstr;
1587 else
1588 return false;
1589 }
1590
1591 llvm::FoldingSetNodeID ID1, ID2;
1592 OldConstr->Profile(ID1, Context, /*Canonical=*/true);
1593 NewConstr->Profile(ID2, Context, /*Canonical=*/true);
1594 return ID1 == ID2;
1595 }
1596
1597 bool Sema::FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD) {
1598 assert(FD->getFriendObjectKind() && "Must be a friend!");
1599
1600 // The logic for non-templates is handled in ASTContext::isSameEntity, so we
1601 // don't have to bother checking 'DependsOnEnclosingTemplate' for a
1602 // non-function-template.
1603 assert(FD->getDescribedFunctionTemplate() &&
1604 "Non-function templates don't need to be checked");
1605
1606 SmallVector<AssociatedConstraint, 3> ACs;
1607 FD->getDescribedFunctionTemplate()->getAssociatedConstraints(ACs);
1608
1609 unsigned OldTemplateDepth = CalculateTemplateDepthForConstraints(*this, FD);
1610 for (const AssociatedConstraint &AC : ACs)
1611 if (ConstraintExpressionDependsOnEnclosingTemplate(FD, OldTemplateDepth,
1612 AC.ConstraintExpr))
1613 return true;
1614
1615 return false;
1616 }
1617
1618 bool Sema::EnsureTemplateArgumentListConstraints(
1619 TemplateDecl *TD, const MultiLevelTemplateArgumentList &TemplateArgsLists,
1620 SourceRange TemplateIDRange) {
1621 ConstraintSatisfaction Satisfaction;
1622 llvm::SmallVector<AssociatedConstraint, 3> AssociatedConstraints;
1623 TD->getAssociatedConstraints(AssociatedConstraints);
1624 if (CheckConstraintSatisfaction(TD, AssociatedConstraints, TemplateArgsLists,
1625 TemplateIDRange, Satisfaction))
1626 return true;
1627
1628 if (!Satisfaction.IsSatisfied) {
1629 SmallString<128> TemplateArgString;
1630 TemplateArgString = " ";
1631 TemplateArgString += getTemplateArgumentBindingsText(
1632 TD->getTemplateParameters(), TemplateArgsLists.getInnermost().data(),
1633 TemplateArgsLists.getInnermost().size());
1634
1635 Diag(TemplateIDRange.getBegin(),
1636 diag::err_template_arg_list_constraints_not_satisfied)
1637 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << TD
1638 << TemplateArgString << TemplateIDRange;
1639 DiagnoseUnsatisfiedConstraint(Satisfaction);
1640 return true;
1641 }
1642 return false;
1643 }
1644
1645 static bool CheckFunctionConstraintsWithoutInstantiation(
1646 Sema &SemaRef, SourceLocation PointOfInstantiation,
1647 FunctionTemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
1648 ConstraintSatisfaction &Satisfaction) {
1649 SmallVector<AssociatedConstraint, 3> TemplateAC;
1650 Template->getAssociatedConstraints(TemplateAC);
1651 if (TemplateAC.empty()) {
1652 Satisfaction.IsSatisfied = true;
1653 return false;
1654 }
1655
1656 LocalInstantiationScope Scope(SemaRef);
1657
1658 FunctionDecl *FD = Template->getTemplatedDecl();
1659 // Collect the list of template arguments relative to the 'primary'
1660 // template. We need the entire list, since the constraint is completely
1661 // uninstantiated at this point.
1662
1663 MultiLevelTemplateArgumentList MLTAL;
1664 {
1665 // getTemplateInstantiationArgs uses this instantiation context to find out
1666 // template arguments for uninstantiated functions.
1667 // We don't want this RAII object to persist, because there would be
1668 // otherwise duplicate diagnostic notes.
1669 Sema::InstantiatingTemplate Inst(
1670 SemaRef, PointOfInstantiation,
1671 Sema::InstantiatingTemplate::ConstraintsCheck{}, Template, TemplateArgs,
1672 PointOfInstantiation);
1673 if (Inst.isInvalid())
1674 return true;
1675 MLTAL = SemaRef.getTemplateInstantiationArgs(
1676 /*D=*/FD, FD,
1677 /*Final=*/false, /*Innermost=*/{}, /*RelativeToPrimary=*/true,
1678 /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true);
1679 }
1680
1681 Sema::ContextRAII SavedContext(SemaRef, FD);
1682 return SemaRef.CheckConstraintSatisfaction(
1683 Template, TemplateAC, MLTAL, PointOfInstantiation, Satisfaction);
1684 }
1685
1686 bool Sema::CheckFunctionTemplateConstraints(
1687 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
1688 ArrayRef<TemplateArgument> TemplateArgs,
1689 ConstraintSatisfaction &Satisfaction) {
1690 // In most cases we're not going to have constraints, so check for that first.
1691 FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
1692
1693 if (!Template)
1694 return ::CheckFunctionConstraintsWithoutInstantiation(
1695 *this, PointOfInstantiation, Decl->getDescribedFunctionTemplate(),
1696 TemplateArgs, Satisfaction);
1697
1698 // Note - code synthesis context for the constraints check is created
1699 // inside CheckConstraintsSatisfaction.
1700 SmallVector<AssociatedConstraint, 3> TemplateAC;
1701 Template->getAssociatedConstraints(TemplateAC);
1702 if (TemplateAC.empty()) {
1703 Satisfaction.IsSatisfied = true;
1704 return false;
1705 }
1706
1707 // Enter the scope of this instantiation. We don't use
1708 // PushDeclContext because we don't have a scope.
1709 Sema::ContextRAII savedContext(*this, Decl);
1710 LocalInstantiationScope Scope(*this);
1711
1712 std::optional<MultiLevelTemplateArgumentList> MLTAL =
1713 SetupConstraintCheckingTemplateArgumentsAndScope(Decl, TemplateArgs,
1714 Scope);
1715
1716 if (!MLTAL)
1717 return true;
1718
1719 Qualifiers ThisQuals;
1720 CXXRecordDecl *Record = nullptr;
1721 if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
1722 ThisQuals = Method->getMethodQualifiers();
1723 Record = Method->getParent();
1724 }
1725
1726 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
1727 LambdaScopeForCallOperatorInstantiationRAII LambdaScope(*this, Decl, *MLTAL,
1728 Scope);
1729
1730 return CheckConstraintSatisfaction(Template, TemplateAC, *MLTAL,
1731 PointOfInstantiation, Satisfaction);
1732 }
1733
1734 static void diagnoseUnsatisfiedRequirement(Sema &S,
1735 concepts::ExprRequirement *Req,
1736 bool First) {
1737 assert(!Req->isSatisfied() &&
1738 "Diagnose() can only be used on an unsatisfied requirement");
1739 switch (Req->getSatisfactionStatus()) {
1740 case concepts::ExprRequirement::SS_Dependent:
1741 llvm_unreachable("Diagnosing a dependent requirement");
1742 break;
1743 case concepts::ExprRequirement::SS_ExprSubstitutionFailure: {
1744 auto *SubstDiag = Req->getExprSubstitutionDiagnostic();
1745 if (!SubstDiag->DiagMessage.empty())
1746 S.Diag(SubstDiag->DiagLoc,
1747 diag::note_expr_requirement_expr_substitution_error)
1748 << (int)First << SubstDiag->SubstitutedEntity
1749 << SubstDiag->DiagMessage;
1750 else
1751 S.Diag(SubstDiag->DiagLoc,
1752 diag::note_expr_requirement_expr_unknown_substitution_error)
1753 << (int)First << SubstDiag->SubstitutedEntity;
1754 break;
1755 }
1756 case concepts::ExprRequirement::SS_NoexceptNotMet:
1757 S.Diag(Req->getNoexceptLoc(), diag::note_expr_requirement_noexcept_not_met)
1758 << (int)First << Req->getExpr();
1759 break;
1760 case concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure: {
1761 auto *SubstDiag =
1762 Req->getReturnTypeRequirement().getSubstitutionDiagnostic();
1763 if (!SubstDiag->DiagMessage.empty())
1764 S.Diag(SubstDiag->DiagLoc,
1765 diag::note_expr_requirement_type_requirement_substitution_error)
1766 << (int)First << SubstDiag->SubstitutedEntity
1767 << SubstDiag->DiagMessage;
1768 else
1769 S.Diag(
1770 SubstDiag->DiagLoc,
1771 diag::
1772 note_expr_requirement_type_requirement_unknown_substitution_error)
1773 << (int)First << SubstDiag->SubstitutedEntity;
1774 break;
1775 }
1776 case concepts::ExprRequirement::SS_ConstraintsNotSatisfied: {
1777 ConceptSpecializationExpr *ConstraintExpr =
1778 Req->getReturnTypeRequirementSubstitutedConstraintExpr();
1779 S.DiagnoseUnsatisfiedConstraint(ConstraintExpr);
1780 break;
1781 }
1782 case concepts::ExprRequirement::SS_Satisfied:
1783 llvm_unreachable("We checked this above");
1784 }
1785 }
1786
1787 static void diagnoseUnsatisfiedRequirement(Sema &S,
1788 concepts::TypeRequirement *Req,
1789 bool First) {
1790 assert(!Req->isSatisfied() &&
1791 "Diagnose() can only be used on an unsatisfied requirement");
1792 switch (Req->getSatisfactionStatus()) {
1793 case concepts::TypeRequirement::SS_Dependent:
1794 llvm_unreachable("Diagnosing a dependent requirement");
1795 return;
1796 case concepts::TypeRequirement::SS_SubstitutionFailure: {
1797 auto *SubstDiag = Req->getSubstitutionDiagnostic();
1798 if (!SubstDiag->DiagMessage.empty())
1799 S.Diag(SubstDiag->DiagLoc, diag::note_type_requirement_substitution_error)
1800 << (int)First << SubstDiag->SubstitutedEntity
1801 << SubstDiag->DiagMessage;
1802 else
1803 S.Diag(SubstDiag->DiagLoc,
1804 diag::note_type_requirement_unknown_substitution_error)
1805 << (int)First << SubstDiag->SubstitutedEntity;
1806 return;
1807 }
1808 default:
1809 llvm_unreachable("Unknown satisfaction status");
1810 return;
1811 }
1812 }
1813
1814 static void diagnoseUnsatisfiedConceptIdExpr(Sema &S,
1815 const ConceptReference *Concept,
1816 SourceLocation Loc, bool First) {
1817 if (Concept->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
1818 S.Diag(
1819 Loc,
1820 diag::
1821 note_single_arg_concept_specialization_constraint_evaluated_to_false)
1822 << (int)First
1823 << Concept->getTemplateArgsAsWritten()->arguments()[0].getArgument()
1824 << Concept->getNamedConcept();
1825 } else {
1826 S.Diag(Loc, diag::note_concept_specialization_constraint_evaluated_to_false)
1827 << (int)First << Concept;
1828 }
1829 }
1830
1831 static void diagnoseUnsatisfiedConstraintExpr(
1832 Sema &S, const UnsatisfiedConstraintRecord &Record, SourceLocation Loc,
1833 bool First, concepts::NestedRequirement *Req = nullptr);
1834
1835 static void DiagnoseUnsatisfiedConstraint(
1836 Sema &S, ArrayRef<UnsatisfiedConstraintRecord> Records, SourceLocation Loc,
1837 bool First = true, concepts::NestedRequirement *Req = nullptr) {
1838 for (auto &Record : Records) {
1839 diagnoseUnsatisfiedConstraintExpr(S, Record, Loc, First, Req);
1840 Loc = {};
1841 First = isa<const ConceptReference *>(Record);
1842 }
1843 }
1844
1845 static void diagnoseUnsatisfiedRequirement(Sema &S,
1846 concepts::NestedRequirement *Req,
1847 bool First) {
1848 DiagnoseUnsatisfiedConstraint(S, Req->getConstraintSatisfaction().records(),
1849 Req->hasInvalidConstraint()
1850 ? SourceLocation()
1851 : Req->getConstraintExpr()->getExprLoc(),
1852 First, Req);
1853 }
1854
1855 static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S,
1856 const Expr *SubstExpr,
1857 bool First) {
1858 SubstExpr = SubstExpr->IgnoreParenImpCasts();
1859 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(SubstExpr)) {
1860 switch (BO->getOpcode()) {
1861 // These two cases will in practice only be reached when using fold
1862 // expressions with || and &&, since otherwise the || and && will have been
1863 // broken down into atomic constraints during satisfaction checking.
1864 case BO_LOr:
1865 // Or evaluated to false - meaning both RHS and LHS evaluated to false.
1866 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
1867 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
1868 /*First=*/false);
1869 return;
1870 case BO_LAnd: {
1871 bool LHSSatisfied =
1872 BO->getLHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1873 if (LHSSatisfied) {
1874 // LHS is true, so RHS must be false.
1875 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(), First);
1876 return;
1877 }
1878 // LHS is false
1879 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
1880
1881 // RHS might also be false
1882 bool RHSSatisfied =
1883 BO->getRHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1884 if (!RHSSatisfied)
1885 diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
1886 /*First=*/false);
1887 return;
1888 }
1889 case BO_GE:
1890 case BO_LE:
1891 case BO_GT:
1892 case BO_LT:
1893 case BO_EQ:
1894 case BO_NE:
1895 if (BO->getLHS()->getType()->isIntegerType() &&
1896 BO->getRHS()->getType()->isIntegerType()) {
1897 Expr::EvalResult SimplifiedLHS;
1898 Expr::EvalResult SimplifiedRHS;
1899 BO->getLHS()->EvaluateAsInt(SimplifiedLHS, S.Context,
1900 Expr::SE_NoSideEffects,
1901 /*InConstantContext=*/true);
1902 BO->getRHS()->EvaluateAsInt(SimplifiedRHS, S.Context,
1903 Expr::SE_NoSideEffects,
1904 /*InConstantContext=*/true);
1905 if (!SimplifiedLHS.Diag && !SimplifiedRHS.Diag) {
1906 S.Diag(SubstExpr->getBeginLoc(),
1907 diag::note_atomic_constraint_evaluated_to_false_elaborated)
1908 << (int)First << SubstExpr
1909 << toString(SimplifiedLHS.Val.getInt(), 10)
1910 << BinaryOperator::getOpcodeStr(BO->getOpcode())
1911 << toString(SimplifiedRHS.Val.getInt(), 10);
1912 return;
1913 }
1914 }
1915 break;
1916
1917 default:
1918 break;
1919 }
1920 } else if (auto *RE = dyn_cast<RequiresExpr>(SubstExpr)) {
1921 // FIXME: RequiresExpr should store dependent diagnostics.
1922 for (concepts::Requirement *Req : RE->getRequirements())
1923 if (!Req->isDependent() && !Req->isSatisfied()) {
1924 if (auto *E = dyn_cast<concepts::ExprRequirement>(Req))
1925 diagnoseUnsatisfiedRequirement(S, E, First);
1926 else if (auto *T = dyn_cast<concepts::TypeRequirement>(Req))
1927 diagnoseUnsatisfiedRequirement(S, T, First);
1928 else
1929 diagnoseUnsatisfiedRequirement(
1930 S, cast<concepts::NestedRequirement>(Req), First);
1931 break;
1932 }
1933 return;
1934 } else if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(SubstExpr)) {
1935 // Drill down concept ids treated as atomic constraints
1936 S.DiagnoseUnsatisfiedConstraint(CSE, First);
1937 return;
1938 } else if (auto *TTE = dyn_cast<TypeTraitExpr>(SubstExpr);
1939 TTE && TTE->getTrait() == clang::TypeTrait::BTT_IsDeducible) {
1940 assert(TTE->getNumArgs() == 2);
1941 S.Diag(SubstExpr->getSourceRange().getBegin(),
1942 diag::note_is_deducible_constraint_evaluated_to_false)
1943 << TTE->getArg(0)->getType() << TTE->getArg(1)->getType();
1944 return;
1945 }
1946
1947 S.Diag(SubstExpr->getSourceRange().getBegin(),
1948 diag::note_atomic_constraint_evaluated_to_false)
1949 << (int)First << SubstExpr;
1950 S.DiagnoseTypeTraitDetails(SubstExpr);
1951 }
1952
1953 static void diagnoseUnsatisfiedConstraintExpr(
1954 Sema &S, const UnsatisfiedConstraintRecord &Record, SourceLocation Loc,
1955 bool First, concepts::NestedRequirement *Req) {
1956 if (auto *Diag =
1957 Record
1958 .template dyn_cast<const ConstraintSubstitutionDiagnostic *>()) {
1959 if (Req)
1960 S.Diag(Diag->first, diag::note_nested_requirement_substitution_error)
1961 << (int)First << Req->getInvalidConstraintEntity() << Diag->second;
1962 else
1963 S.Diag(Diag->first, diag::note_substituted_constraint_expr_is_ill_formed)
1964 << Diag->second;
1965 return;
1966 }
1967 if (const auto *Concept = dyn_cast<const ConceptReference *>(Record)) {
1968 if (Loc.isInvalid())
1969 Loc = Concept->getBeginLoc();
1970 diagnoseUnsatisfiedConceptIdExpr(S, Concept, Loc, First);
1971 return;
1972 }
1973 diagnoseWellFormedUnsatisfiedConstraintExpr(
1974 S, cast<const class Expr *>(Record), First);
1975 }
1976
1977 void Sema::DiagnoseUnsatisfiedConstraint(
1978 const ConstraintSatisfaction &Satisfaction, SourceLocation Loc,
1979 bool First) {
1980
1981 assert(!Satisfaction.IsSatisfied &&
1982 "Attempted to diagnose a satisfied constraint");
1983 ::DiagnoseUnsatisfiedConstraint(*this, Satisfaction.Details, Loc, First);
1984 }
1985
1986 void Sema::DiagnoseUnsatisfiedConstraint(
1987 const ConceptSpecializationExpr *ConstraintExpr, bool First) {
1988
1989 const ASTConstraintSatisfaction &Satisfaction =
1990 ConstraintExpr->getSatisfaction();
1991
1992 assert(!Satisfaction.IsSatisfied &&
1993 "Attempted to diagnose a satisfied constraint");
1994
1995 ::DiagnoseUnsatisfiedConstraint(*this, Satisfaction.records(),
1996 ConstraintExpr->getBeginLoc(), First);
1997 }
1998
1999 namespace {
2000
2001 class SubstituteParameterMappings {
2002 Sema &SemaRef;
2003
2004 const MultiLevelTemplateArgumentList *MLTAL;
2005 const ASTTemplateArgumentListInfo *ArgsAsWritten;
2006
2007 // When normalizing a fold constraint, e.g.
2008 // C<Pack1, Pack2...> && ...
2009 // we want the TreeTransform to expand only Pack2 but not Pack1,
2010 // since Pack1 will be expanded during the evaluation of the fold expression.
2011 // This flag helps rewrite any non-PackExpansion packs into "expanded"
2012 // parameters.
2013 bool RemovePacksForFoldExpr;
2014
2015 SubstituteParameterMappings(Sema &SemaRef,
2016 const MultiLevelTemplateArgumentList *MLTAL,
2017 const ASTTemplateArgumentListInfo *ArgsAsWritten,
2018 bool RemovePacksForFoldExpr)
2019 : SemaRef(SemaRef), MLTAL(MLTAL), ArgsAsWritten(ArgsAsWritten),
2020 RemovePacksForFoldExpr(RemovePacksForFoldExpr) {}
2021
2022 void buildParameterMapping(NormalizedConstraintWithParamMapping &N);
2023
2024 bool substitute(NormalizedConstraintWithParamMapping &N);
2025
2026 bool substitute(ConceptIdConstraint &CC);
2027
2028 public:
2029 SubstituteParameterMappings(Sema &SemaRef,
2030 bool RemovePacksForFoldExpr = false)
2031 : SemaRef(SemaRef), MLTAL(nullptr), ArgsAsWritten(nullptr),
2032 RemovePacksForFoldExpr(RemovePacksForFoldExpr) {}
2033
2034 bool substitute(NormalizedConstraint &N);
2035 };
2036
2037 void SubstituteParameterMappings::buildParameterMapping(
2038 NormalizedConstraintWithParamMapping &N) {
2039 TemplateParameterList *TemplateParams =
2040 cast<TemplateDecl>(N.getConstraintDecl())->getTemplateParameters();
2041
2042 llvm::SmallBitVector OccurringIndices(TemplateParams->size());
2043 llvm::SmallBitVector OccurringIndicesForSubsumption(TemplateParams->size());
2044
2045 if (N.getKind() == NormalizedConstraint::ConstraintKind::Atomic) {
2046 SemaRef.MarkUsedTemplateParameters(
2047 static_cast<AtomicConstraint &>(N).getConstraintExpr(),
2048 /*OnlyDeduced=*/false,
2049 /*Depth=*/0, OccurringIndices);
2050
2051 SemaRef.MarkUsedTemplateParametersForSubsumptionParameterMapping(
2052 static_cast<AtomicConstraint &>(N).getConstraintExpr(),
2053 /*Depth=*/0, OccurringIndicesForSubsumption);
2054
2055 } else if (N.getKind() ==
2056 NormalizedConstraint::ConstraintKind::FoldExpanded) {
2057 SemaRef.MarkUsedTemplateParameters(
2058 static_cast<FoldExpandedConstraint &>(N).getPattern(),
2059 /*OnlyDeduced=*/false,
2060 /*Depth=*/0, OccurringIndices);
2061 } else if (N.getKind() == NormalizedConstraint::ConstraintKind::ConceptId) {
2062 auto *Args = static_cast<ConceptIdConstraint &>(N)
2063 .getConceptId()
2064 ->getTemplateArgsAsWritten();
2065 if (Args)
2066 SemaRef.MarkUsedTemplateParameters(Args->arguments(),
2067 /*Depth=*/0, OccurringIndices);
2068 }
2069 unsigned Size = OccurringIndices.count();
2070 // When the constraint is independent of any template parameters,
2071 // we build an empty mapping so that we can distinguish these cases
2072 // from cases where no mapping exists at all, e.g. when there are only atomic
2073 // constraints.
2074 TemplateArgumentLoc *TempArgs =
2075 new (SemaRef.Context) TemplateArgumentLoc[Size];
2076 llvm::SmallVector<NamedDecl *> UsedParams;
2077 for (unsigned I = 0, J = 0, C = TemplateParams->size(); I != C; ++I) {
2078 SourceLocation Loc = ArgsAsWritten->NumTemplateArgs > I
2079 ? ArgsAsWritten->arguments()[I].getLocation()
2080 : SourceLocation();
2081 // FIXME: Investigate why we couldn't always preserve the SourceLoc. We
2082 // can't assert Loc.isValid() now.
2083 if (OccurringIndices[I]) {
2084 NamedDecl *Param = TemplateParams->begin()[I];
2085 new (&(TempArgs)[J]) TemplateArgumentLoc(
2086 SemaRef.getIdentityTemplateArgumentLoc(Param, Loc));
2087 UsedParams.push_back(Param);
2088 J++;
2089 }
2090 }
2091 auto *UsedList = TemplateParameterList::Create(
2092 SemaRef.Context, TemplateParams->getTemplateLoc(),
2093 TemplateParams->getLAngleLoc(), UsedParams,
2094 /*RAngleLoc=*/SourceLocation(),
2095 /*RequiresClause=*/nullptr);
2096 N.updateParameterMapping(
2097 std::move(OccurringIndices), std::move(OccurringIndicesForSubsumption),
2098 MutableArrayRef<TemplateArgumentLoc>{TempArgs, Size}, UsedList);
2099 }
2100
2101 bool SubstituteParameterMappings::substitute(
2102 NormalizedConstraintWithParamMapping &N) {
2103 if (!N.hasParameterMapping())
2104 buildParameterMapping(N);
2105
2106 // If the parameter mapping is empty, there is nothing to substitute.
2107 if (N.getParameterMapping().empty())
2108 return false;
2109
2110 SourceLocation InstLocBegin, InstLocEnd;
2111 llvm::ArrayRef Arguments = ArgsAsWritten->arguments();
2112 if (Arguments.empty()) {
2113 InstLocBegin = ArgsAsWritten->getLAngleLoc();
2114 InstLocEnd = ArgsAsWritten->getRAngleLoc();
2115 } else {
2116 auto SR = Arguments[0].getSourceRange();
2117 InstLocBegin = SR.getBegin();
2118 InstLocEnd = SR.getEnd();
2119 }
2120 Sema::NonSFINAEContext _(SemaRef);
2121 Sema::InstantiatingTemplate Inst(
2122 SemaRef, InstLocBegin,
2123 Sema::InstantiatingTemplate::ParameterMappingSubstitution{},
2124 const_cast<NamedDecl *>(N.getConstraintDecl()),
2125 {InstLocBegin, InstLocEnd});
2126 if (Inst.isInvalid())
2127 return true;
2128
2129 // TransformTemplateArguments is unable to preserve the source location of a
2130 // pack. The SourceLocation is necessary for the instantiation location.
2131 // FIXME: The BaseLoc will be used as the location of the pack expansion,
2132 // which is wrong.
2133 TemplateArgumentListInfo SubstArgs;
2134 if (SemaRef.SubstTemplateArgumentsInParameterMapping(
2135 N.getParameterMapping(), N.getBeginLoc(), *MLTAL, SubstArgs))
2136 return true;
2137 Sema::CheckTemplateArgumentInfo CTAI;
2138 auto *TD =
2139 const_cast<TemplateDecl *>(cast<TemplateDecl>(N.getConstraintDecl()));
2140 if (SemaRef.CheckTemplateArgumentList(TD, N.getUsedTemplateParamList(),
2141 TD->getLocation(), SubstArgs,
2142 /*DefaultArguments=*/{},
2143 /*PartialTemplateArgs=*/false, CTAI))
2144 return true;
2145
2146 TemplateArgumentLoc *TempArgs =
2147 new (SemaRef.Context) TemplateArgumentLoc[CTAI.SugaredConverted.size()];
2148
2149 for (unsigned I = 0; I < CTAI.SugaredConverted.size(); ++I) {
2150 SourceLocation Loc;
2151 // If this is an empty pack, we have no corresponding SubstArgs.
2152 if (I < SubstArgs.size())
2153 Loc = SubstArgs.arguments()[I].getLocation();
2154
2155 TempArgs[I] = SemaRef.getTrivialTemplateArgumentLoc(
2156 CTAI.SugaredConverted[I], QualType(), Loc);
2157 }
2158
2159 MutableArrayRef<TemplateArgumentLoc> Mapping(TempArgs,
2160 CTAI.SugaredConverted.size());
2161 N.updateParameterMapping(N.mappingOccurenceList(),
2162 N.mappingOccurenceListForSubsumption(), Mapping,
2163 N.getUsedTemplateParamList());
2164 return false;
2165 }
2166
2167 bool SubstituteParameterMappings::substitute(ConceptIdConstraint &CC) {
2168 assert(CC.getConstraintDecl() && MLTAL && ArgsAsWritten);
2169
2170 if (substitute(static_cast<NormalizedConstraintWithParamMapping &>(CC)))
2171 return true;
2172
2173 auto *CSE = CC.getConceptSpecializationExpr();
2174 assert(CSE);
2175 assert(!CC.getBeginLoc().isInvalid());
2176
2177 SourceLocation InstLocBegin, InstLocEnd;
2178 if (llvm::ArrayRef Arguments = ArgsAsWritten->arguments();
2179 Arguments.empty()) {
2180 InstLocBegin = ArgsAsWritten->getLAngleLoc();
2181 InstLocEnd = ArgsAsWritten->getRAngleLoc();
2182 } else {
2183 auto SR = Arguments[0].getSourceRange();
2184 InstLocBegin = SR.getBegin();
2185 InstLocEnd = SR.getEnd();
2186 }
2187 Sema::NonSFINAEContext _(SemaRef);
2188 // This is useful for name lookup across modules; see Sema::getLookupModules.
2189 Sema::InstantiatingTemplate Inst(
2190 SemaRef, InstLocBegin,
2191 Sema::InstantiatingTemplate::ParameterMappingSubstitution{},
2192 const_cast<NamedDecl *>(CC.getConstraintDecl()),
2193 {InstLocBegin, InstLocEnd});
2194 if (Inst.isInvalid())
2195 return true;
2196
2197 TemplateArgumentListInfo Out;
2198 // TransformTemplateArguments is unable to preserve the source location of a
2199 // pack. The SourceLocation is necessary for the instantiation location.
2200 // FIXME: The BaseLoc will be used as the location of the pack expansion,
2201 // which is wrong.
2202 const ASTTemplateArgumentListInfo *ArgsAsWritten =
2203 CSE->getTemplateArgsAsWritten();
2204 if (SemaRef.SubstTemplateArgumentsInParameterMapping(
2205 ArgsAsWritten->arguments(), CC.getBeginLoc(), *MLTAL, Out))
2206 return true;
2207 Sema::CheckTemplateArgumentInfo CTAI;
2208 if (SemaRef.CheckTemplateArgumentList(CSE->getNamedConcept(),
2209 CSE->getConceptNameInfo().getLoc(), Out,
2210 /*DefaultArgs=*/{},
2211 /*PartialTemplateArgs=*/false, CTAI,
2212 /*UpdateArgsWithConversions=*/false))
2213 return true;
2214 auto TemplateArgs = *MLTAL;
2215 TemplateArgs.replaceOutermostTemplateArguments(CSE->getNamedConcept(),
2216 CTAI.SugaredConverted);
2217 return SubstituteParameterMappings(SemaRef, &TemplateArgs, ArgsAsWritten,
2218 RemovePacksForFoldExpr)
2219 .substitute(CC.getNormalizedConstraint());
2220 }
2221
2222 bool SubstituteParameterMappings::substitute(NormalizedConstraint &N) {
2223 switch (N.getKind()) {
2224 case NormalizedConstraint::ConstraintKind::Atomic: {
2225 if (!MLTAL) {
2226 assert(!ArgsAsWritten);
2227 return false;
2228 }
2229 return substitute(static_cast<NormalizedConstraintWithParamMapping &>(N));
2230 }
2231 case NormalizedConstraint::ConstraintKind::FoldExpanded: {
2232 auto &FE = static_cast<FoldExpandedConstraint &>(N);
2233 if (!MLTAL) {
2234 llvm::SaveAndRestore _1(RemovePacksForFoldExpr, true);
2235 assert(!ArgsAsWritten);
2236 return substitute(FE.getNormalizedPattern());
2237 }
2238 Sema::ArgPackSubstIndexRAII _(SemaRef, std::nullopt);
2239 substitute(static_cast<NormalizedConstraintWithParamMapping &>(FE));
2240 return SubstituteParameterMappings(SemaRef, /*RemovePacksForFoldExpr=*/true)
2241 .substitute(FE.getNormalizedPattern());
2242 }
2243 case NormalizedConstraint::ConstraintKind::ConceptId: {
2244 auto &CC = static_cast<ConceptIdConstraint &>(N);
2245 if (MLTAL) {
2246 assert(ArgsAsWritten);
2247 return substitute(CC);
2248 }
2249 assert(!ArgsAsWritten);
2250 const ConceptSpecializationExpr *CSE = CC.getConceptSpecializationExpr();
2251 SmallVector<TemplateArgument> InnerArgs(CSE->getTemplateArguments());
2252 ConceptDecl *Concept = CSE->getNamedConcept();
2253 if (RemovePacksForFoldExpr) {
2254 TemplateArgumentListInfo OutArgs;
2255 ArrayRef<TemplateArgumentLoc> InputArgLoc =
2256 CSE->getConceptReference()->getTemplateArgsAsWritten()->arguments();
2257 if (AdjustConstraints(SemaRef, /*TemplateDepth=*/0,
2258 /*RemoveNonPackExpansionPacks=*/true)
2259 .TransformTemplateArguments(InputArgLoc.begin(),
2260 InputArgLoc.end(), OutArgs))
2261 return true;
2262 Sema::CheckTemplateArgumentInfo CTAI;
2263 // Repack the packs.
2264 if (SemaRef.CheckTemplateArgumentList(
2265 Concept, Concept->getTemplateParameters(), Concept->getBeginLoc(),
2266 OutArgs,
2267 /*DefaultArguments=*/{},
2268 /*PartialTemplateArgs=*/false, CTAI))
2269 return true;
2270 InnerArgs = std::move(CTAI.SugaredConverted);
2271 }
2272
2273 MultiLevelTemplateArgumentList MLTAL = SemaRef.getTemplateInstantiationArgs(
2274 Concept, Concept->getLexicalDeclContext(),
2275 /*Final=*/true, InnerArgs,
2276 /*RelativeToPrimary=*/true,
2277 /*Pattern=*/nullptr,
2278 /*ForConstraintInstantiation=*/true);
2279
2280 return SubstituteParameterMappings(SemaRef, &MLTAL,
2281 CSE->getTemplateArgsAsWritten(),
2282 RemovePacksForFoldExpr)
2283 .substitute(CC.getNormalizedConstraint());
2284 }
2285 case NormalizedConstraint::ConstraintKind::Compound: {
2286 auto &Compound = static_cast<CompoundConstraint &>(N);
2287 if (substitute(Compound.getLHS()))
2288 return true;
2289 return substitute(Compound.getRHS());
2290 }
2291 }
2292 llvm_unreachable("Unknown ConstraintKind enum");
2293 }
2294
2295 } // namespace
2296
2297 NormalizedConstraint *NormalizedConstraint::fromAssociatedConstraints(
2298 Sema &S, const NamedDecl *D, ArrayRef<AssociatedConstraint> ACs) {
2299 assert(ACs.size() != 0);
2300 auto *Conjunction =
2301 fromConstraintExpr(S, D, ACs[0].ConstraintExpr, ACs[0].ArgPackSubstIndex);
2302 if (!Conjunction)
2303 return nullptr;
2304 for (unsigned I = 1; I < ACs.size(); ++I) {
2305 auto *Next = fromConstraintExpr(S, D, ACs[I].ConstraintExpr,
2306 ACs[I].ArgPackSubstIndex);
2307 if (!Next)
2308 return nullptr;
2309 Conjunction = CompoundConstraint::CreateConjunction(S.getASTContext(),
2310 Conjunction, Next);
2311 }
2312 return Conjunction;
2313 }
2314
2315 NormalizedConstraint *NormalizedConstraint::fromConstraintExpr(
2316 Sema &S, const NamedDecl *D, const Expr *E, UnsignedOrNone SubstIndex) {
2317 assert(E != nullptr);
2318
2319 // C++ [temp.constr.normal]p1.1
2320 // [...]
2321 // - The normal form of an expression (E) is the normal form of E.
2322 // [...]
2323 E = E->IgnoreParenImpCasts();
2324
2325 llvm::FoldingSetNodeID ID;
2326 if (D && DiagRecursiveConstraintEval(S, ID, D, E)) {
2327 return nullptr;
2328 }
2329 SatisfactionStackRAII StackRAII(S, D, ID);
2330
2331 // C++2a [temp.param]p4:
2332 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
2333 // Fold expression is considered atomic constraints per current wording.
2334 // See http://cplusplus.github.io/concepts-ts/ts-active.html#28
2335
2336 if (LogicalBinOp BO = E) {
2337 auto *LHS = fromConstraintExpr(S, D, BO.getLHS(), SubstIndex);
2338 if (!LHS)
2339 return nullptr;
2340 auto *RHS = fromConstraintExpr(S, D, BO.getRHS(), SubstIndex);
2341 if (!RHS)
2342 return nullptr;
2343
2344 return CompoundConstraint::Create(
2345 S.Context, LHS, BO.isAnd() ? CCK_Conjunction : CCK_Disjunction, RHS);
2346 } else if (auto *CSE = dyn_cast<const ConceptSpecializationExpr>(E)) {
2347 NormalizedConstraint *SubNF;
2348 {
2349 Sema::NonSFINAEContext _(S);
2350 Sema::InstantiatingTemplate Inst(
2351 S, CSE->getExprLoc(),
2352 Sema::InstantiatingTemplate::ConstraintNormalization{},
2353 // FIXME: improve const-correctness of InstantiatingTemplate
2354 const_cast<NamedDecl *>(D), CSE->getSourceRange());
2355 if (Inst.isInvalid())
2356 return nullptr;
2357 // C++ [temp.constr.normal]p1.1
2358 // [...]
2359 // The normal form of an id-expression of the form C<A1, A2, ..., AN>,
2360 // where C names a concept, is the normal form of the
2361 // constraint-expression of C, after substituting A1, A2, ..., AN for C’s
2362 // respective template parameters in the parameter mappings in each atomic
2363 // constraint. If any such substitution results in an invalid type or
2364 // expression, the program is ill-formed; no diagnostic is required.
2365 // [...]
2366
2367 // Use canonical declarations to merge ConceptDecls across
2368 // different modules.
2369 ConceptDecl *CD = CSE->getNamedConcept()->getCanonicalDecl();
2370
2371 ExprResult Res =
2372 SubstituteConceptsInConstraintExpression(S, D, CSE, SubstIndex);
2373 if (!Res.isUsable())
2374 return nullptr;
2375
2376 SubNF = NormalizedConstraint::fromAssociatedConstraints(
2377 S, CD, AssociatedConstraint(Res.get(), SubstIndex));
2378
2379 if (!SubNF)
2380 return nullptr;
2381 }
2382
2383 return ConceptIdConstraint::Create(S.getASTContext(),
2384 CSE->getConceptReference(), SubNF, D,
2385 CSE, SubstIndex);
2386
2387 } else if (auto *FE = dyn_cast<const CXXFoldExpr>(E);
2388 FE && S.getLangOpts().CPlusPlus26 &&
2389 (FE->getOperator() == BinaryOperatorKind::BO_LAnd ||
2390 FE->getOperator() == BinaryOperatorKind::BO_LOr)) {
2391
2392 // Normalize fold expressions in C++26.
2393
2394 FoldExpandedConstraint::FoldOperatorKind Kind =
2395 FE->getOperator() == BinaryOperatorKind::BO_LAnd
2396 ? FoldExpandedConstraint::FoldOperatorKind::And
2397 : FoldExpandedConstraint::FoldOperatorKind::Or;
2398
2399 if (FE->getInit()) {
2400 auto *LHS = fromConstraintExpr(S, D, FE->getLHS(), SubstIndex);
2401 auto *RHS = fromConstraintExpr(S, D, FE->getRHS(), SubstIndex);
2402 if (!LHS || !RHS)
2403 return nullptr;
2404
2405 if (FE->isRightFold())
2406 LHS = FoldExpandedConstraint::Create(S.getASTContext(),
2407 FE->getPattern(), D, Kind, LHS);
2408 else
2409 RHS = FoldExpandedConstraint::Create(S.getASTContext(),
2410 FE->getPattern(), D, Kind, RHS);
2411
2412 return CompoundConstraint::Create(
2413 S.getASTContext(), LHS,
2414 (FE->getOperator() == BinaryOperatorKind::BO_LAnd ? CCK_Conjunction
2415 : CCK_Disjunction),
2416 RHS);
2417 }
2418 auto *Sub = fromConstraintExpr(S, D, FE->getPattern(), SubstIndex);
2419 if (!Sub)
2420 return nullptr;
2421 return FoldExpandedConstraint::Create(S.getASTContext(), FE->getPattern(),
2422 D, Kind, Sub);
2423 }
2424 return AtomicConstraint::Create(S.getASTContext(), E, D, SubstIndex);
2425 }
2426
2427 const NormalizedConstraint *Sema::getNormalizedAssociatedConstraints(
2428 ConstrainedDeclOrNestedRequirement ConstrainedDeclOrNestedReq,
2429 ArrayRef<AssociatedConstraint> AssociatedConstraints) {
2430 if (!ConstrainedDeclOrNestedReq) {
2431 auto *Normalized = NormalizedConstraint::fromAssociatedConstraints(
2432 *this, nullptr, AssociatedConstraints);
2433 if (!Normalized ||
2434 SubstituteParameterMappings(*this).substitute(*Normalized))
2435 return nullptr;
2436
2437 return Normalized;
2438 }
2439
2440 // FIXME: ConstrainedDeclOrNestedReq is never a NestedRequirement!
2441 const NamedDecl *ND =
2442 ConstrainedDeclOrNestedReq.dyn_cast<const NamedDecl *>();
2443 auto CacheEntry = NormalizationCache.find(ConstrainedDeclOrNestedReq);
2444 if (CacheEntry == NormalizationCache.end()) {
2445 auto *Normalized = NormalizedConstraint::fromAssociatedConstraints(
2446 *this, ND, AssociatedConstraints);
2447 if (!Normalized) {
2448 NormalizationCache.try_emplace(ConstrainedDeclOrNestedReq, nullptr);
2449 return nullptr;
2450 }
2451 // substitute() can invalidate iterators of NormalizationCache.
2452 bool Failed = SubstituteParameterMappings(*this).substitute(*Normalized);
2453 CacheEntry =
2454 NormalizationCache.try_emplace(ConstrainedDeclOrNestedReq, Normalized)
2455 .first;
2456 if (Failed)
2457 return nullptr;
2458 }
2459 return CacheEntry->second;
2460 }
2461
2462 bool FoldExpandedConstraint::AreCompatibleForSubsumption(
2463 const FoldExpandedConstraint &A, const FoldExpandedConstraint &B) {
2464
2465 // [C++26] [temp.constr.fold]
2466 // Two fold expanded constraints are compatible for subsumption
2467 // if their respective constraints both contain an equivalent unexpanded pack.
2468
2469 llvm::SmallVector<UnexpandedParameterPack> APacks, BPacks;
2470 Sema::collectUnexpandedParameterPacks(const_cast<Expr *>(A.getPattern()),
2471 APacks);
2472 Sema::collectUnexpandedParameterPacks(const_cast<Expr *>(B.getPattern()),
2473 BPacks);
2474
2475 for (const UnexpandedParameterPack &APack : APacks) {
2476 auto ADI = getDepthAndIndex(APack);
2477 if (!ADI)
2478 continue;
2479 auto It = llvm::find_if(BPacks, [&](const UnexpandedParameterPack &BPack) {
2480 return getDepthAndIndex(BPack) == ADI;
2481 });
2482 if (It != BPacks.end())
2483 return true;
2484 }
2485 return false;
2486 }
2487
2488 bool Sema::IsAtLeastAsConstrained(const NamedDecl *D1,
2489 MutableArrayRef<AssociatedConstraint> AC1,
2490 const NamedDecl *D2,
2491 MutableArrayRef<AssociatedConstraint> AC2,
2492 bool &Result) {
2493 #ifndef NDEBUG
2494 if (const auto *FD1 = dyn_cast<FunctionDecl>(D1)) {
2495 auto IsExpectedEntity = [](const FunctionDecl *FD) {
2496 FunctionDecl::TemplatedKind Kind = FD->getTemplatedKind();
2497 return Kind == FunctionDecl::TK_NonTemplate ||
2498 Kind == FunctionDecl::TK_FunctionTemplate;
2499 };
2500 const auto *FD2 = dyn_cast<FunctionDecl>(D2);
2501 assert(IsExpectedEntity(FD1) && FD2 && IsExpectedEntity(FD2) &&
2502 "use non-instantiated function declaration for constraints partial "
2503 "ordering");
2504 }
2505 #endif
2506
2507 if (AC1.empty()) {
2508 Result = AC2.empty();
2509 return false;
2510 }
2511 if (AC2.empty()) {
2512 // TD1 has associated constraints and TD2 does not.
2513 Result = true;
2514 return false;
2515 }
2516
2517 std::pair<const NamedDecl *, const NamedDecl *> Key{D1, D2};
2518 auto CacheEntry = SubsumptionCache.find(Key);
2519 if (CacheEntry != SubsumptionCache.end()) {
2520 Result = CacheEntry->second;
2521 return false;
2522 }
2523
2524 unsigned Depth1 = CalculateTemplateDepthForConstraints(*this, D1, true);
2525 unsigned Depth2 = CalculateTemplateDepthForConstraints(*this, D2, true);
2526
2527 for (size_t I = 0; I != AC1.size() && I != AC2.size(); ++I) {
2528 if (Depth2 > Depth1) {
2529 AC1[I].ConstraintExpr =
2530 AdjustConstraints(*this, Depth2 - Depth1)
2531 .TransformExpr(const_cast<Expr *>(AC1[I].ConstraintExpr))
2532 .get();
2533 } else if (Depth1 > Depth2) {
2534 AC2[I].ConstraintExpr =
2535 AdjustConstraints(*this, Depth1 - Depth2)
2536 .TransformExpr(const_cast<Expr *>(AC2[I].ConstraintExpr))
2537 .get();
2538 }
2539 }
2540
2541 SubsumptionChecker SC(*this);
2542 // Associated declarations are used as a cache key in the event they were
2543 // normalized earlier during concept checking. However we cannot reuse these
2544 // cached results if any of the template depths have been adjusted.
2545 const NamedDecl *DeclAC1 = D1, *DeclAC2 = D2;
2546 if (Depth2 > Depth1)
2547 DeclAC1 = nullptr;
2548 else if (Depth1 > Depth2)
2549 DeclAC2 = nullptr;
2550 std::optional<bool> Subsumes = SC.Subsumes(DeclAC1, AC1, DeclAC2, AC2);
2551 if (!Subsumes) {
2552 // Normalization failed
2553 return true;
2554 }
2555 Result = *Subsumes;
2556 SubsumptionCache.try_emplace(Key, *Subsumes);
2557 return false;
2558 }
2559
2560 bool Sema::MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
2561 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
2562 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2) {
2563 if (isSFINAEContext())
2564 // No need to work here because our notes would be discarded.
2565 return false;
2566
2567 if (AC1.empty() || AC2.empty())
2568 return false;
2569
2570 const Expr *AmbiguousAtomic1 = nullptr, *AmbiguousAtomic2 = nullptr;
2571 auto IdenticalExprEvaluator = [&](const AtomicConstraint &A,
2572 const AtomicConstraint &B) {
2573 if (!A.hasMatchingParameterMapping(Context, B))
2574 return false;
2575 const Expr *EA = A.getConstraintExpr(), *EB = B.getConstraintExpr();
2576 if (EA == EB)
2577 return true;
2578
2579 // Not the same source level expression - are the expressions
2580 // identical?
2581 llvm::FoldingSetNodeID IDA, IDB;
2582 EA->Profile(IDA, Context, /*Canonical=*/true);
2583 EB->Profile(IDB, Context, /*Canonical=*/true);
2584 if (IDA != IDB)
2585 return false;
2586
2587 AmbiguousAtomic1 = EA;
2588 AmbiguousAtomic2 = EB;
2589 return true;
2590 };
2591
2592 {
2593 auto *Normalized1 = getNormalizedAssociatedConstraints(D1, AC1);
2594 if (!Normalized1)
2595 return false;
2596
2597 auto *Normalized2 = getNormalizedAssociatedConstraints(D2, AC2);
2598 if (!Normalized2)
2599 return false;
2600
2601 SubsumptionChecker SC(*this);
2602
2603 bool Is1AtLeastAs2Normally = SC.Subsumes(Normalized1, Normalized2);
2604 bool Is2AtLeastAs1Normally = SC.Subsumes(Normalized2, Normalized1);
2605
2606 SubsumptionChecker SC2(*this, IdenticalExprEvaluator);
2607 bool Is1AtLeastAs2 = SC2.Subsumes(Normalized1, Normalized2);
2608 bool Is2AtLeastAs1 = SC2.Subsumes(Normalized2, Normalized1);
2609
2610 if (Is1AtLeastAs2 == Is1AtLeastAs2Normally &&
2611 Is2AtLeastAs1 == Is2AtLeastAs1Normally)
2612 // Same result - no ambiguity was caused by identical atomic expressions.
2613 return false;
2614 }
2615 // A different result! Some ambiguous atomic constraint(s) caused a difference
2616 assert(AmbiguousAtomic1 && AmbiguousAtomic2);
2617
2618 Diag(AmbiguousAtomic1->getBeginLoc(), diag::note_ambiguous_atomic_constraints)
2619 << AmbiguousAtomic1->getSourceRange();
2620 Diag(AmbiguousAtomic2->getBeginLoc(),
2621 diag::note_ambiguous_atomic_constraints_similar_expression)
2622 << AmbiguousAtomic2->getSourceRange();
2623 return true;
2624 }
2625
2626 //
2627 //
2628 // ------------------------ Subsumption -----------------------------------
2629 //
2630 //
2631 SubsumptionChecker::SubsumptionChecker(Sema &SemaRef,
2632 SubsumptionCallable Callable)
2633 : SemaRef(SemaRef), Callable(Callable), NextID(1) {}
2634
2635 uint16_t SubsumptionChecker::getNewLiteralId() {
2636 assert((unsigned(NextID) + 1 < std::numeric_limits<uint16_t>::max()) &&
2637 "too many constraints!");
2638 return NextID++;
2639 }
2640
2641 auto SubsumptionChecker::find(const AtomicConstraint *Ori) -> Literal {
2642 auto &Elems = AtomicMap[Ori->getConstraintExpr()];
2643 // C++ [temp.constr.order] p2
2644 // - an atomic constraint A subsumes another atomic constraint B
2645 // if and only if the A and B are identical [...]
2646 //
2647 // C++ [temp.constr.atomic] p2
2648 // Two atomic constraints are identical if they are formed from the
2649 // same expression and the targets of the parameter mappings are
2650 // equivalent according to the rules for expressions [...]
2651
2652 // Because subsumption of atomic constraints is an identity
2653 // relationship that does not require further analysis
2654 // We cache the results such that if an atomic constraint literal
2655 // subsumes another, their literal will be the same
2656
2657 llvm::FoldingSetNodeID ID;
2658 ID.AddBoolean(Ori->hasParameterMapping());
2659 if (Ori->hasParameterMapping()) {
2660 const auto &Mapping = Ori->getParameterMapping();
2661 const NormalizedConstraint::OccurenceList &Indexes =
2662 Ori->mappingOccurenceListForSubsumption();
2663 for (auto [Idx, TAL] : llvm::enumerate(Mapping)) {
2664 if (Indexes[Idx])
2665 SemaRef.getASTContext()
2666 .getCanonicalTemplateArgument(TAL.getArgument())
2667 .Profile(ID, SemaRef.getASTContext());
2668 }
2669 }
2670 auto It = Elems.find(ID);
2671 if (It == Elems.end()) {
2672 It = Elems
2673 .insert({ID,
2674 MappedAtomicConstraint{
2675 Ori, {getNewLiteralId(), Literal::Atomic}}})
2676 .first;
2677 ReverseMap[It->second.ID.Value] = Ori;
2678 }
2679 return It->getSecond().ID;
2680 }
2681
2682 auto SubsumptionChecker::find(const FoldExpandedConstraint *Ori) -> Literal {
2683 auto &Elems = FoldMap[Ori->getPattern()];
2684
2685 FoldExpendedConstraintKey K;
2686 K.Kind = Ori->getFoldOperator();
2687
2688 auto It = llvm::find_if(Elems, [&K](const FoldExpendedConstraintKey &Other) {
2689 return K.Kind == Other.Kind;
2690 });
2691 if (It == Elems.end()) {
2692 K.ID = {getNewLiteralId(), Literal::FoldExpanded};
2693 It = Elems.insert(Elems.end(), std::move(K));
2694 ReverseMap[It->ID.Value] = Ori;
2695 }
2696 return It->ID;
2697 }
2698
2699 auto SubsumptionChecker::CNF(const NormalizedConstraint &C) -> CNFFormula {
2700 return SubsumptionChecker::Normalize<CNFFormula>(C);
2701 }
2702 auto SubsumptionChecker::DNF(const NormalizedConstraint &C) -> DNFFormula {
2703 return SubsumptionChecker::Normalize<DNFFormula>(C);
2704 }
2705
2706 ///
2707 /// \brief SubsumptionChecker::Normalize
2708 ///
2709 /// Normalize a formula to Conjunctive Normal Form or
2710 /// Disjunctive normal form.
2711 ///
2712 /// Each Atomic (and Fold Expanded) constraint gets represented by
2713 /// a single id to reduce space.
2714 ///
2715 /// To minimize risks of exponential blow up, if two atomic
2716 /// constraints subsumes each other (same constraint and mapping),
2717 /// they are represented by the same literal.
2718 ///
2719 template <typename FormulaType>
2720 FormulaType SubsumptionChecker::Normalize(const NormalizedConstraint &NC) {
2721 FormulaType Res;
2722
2723 auto Add = [&, this](Clause C) {
2724 // Sort each clause and remove duplicates for faster comparisons.
2725 llvm::sort(C);
2726 C.erase(llvm::unique(C), C.end());
2727 AddUniqueClauseToFormula(Res, std::move(C));
2728 };
2729
2730 switch (NC.getKind()) {
2731 case NormalizedConstraint::ConstraintKind::Atomic:
2732 return {{find(&static_cast<const AtomicConstraint &>(NC))}};
2733
2734 case NormalizedConstraint::ConstraintKind::FoldExpanded:
2735 return {{find(&static_cast<const FoldExpandedConstraint &>(NC))}};
2736
2737 case NormalizedConstraint::ConstraintKind::ConceptId:
2738 return Normalize<FormulaType>(
2739 static_cast<const ConceptIdConstraint &>(NC).getNormalizedConstraint());
2740
2741 case NormalizedConstraint::ConstraintKind::Compound: {
2742 const auto &Compound = static_cast<const CompoundConstraint &>(NC);
2743 FormulaType Left, Right;
2744 SemaRef.runWithSufficientStackSpace(SourceLocation(), [&] {
2745 Left = Normalize<FormulaType>(Compound.getLHS());
2746 Right = Normalize<FormulaType>(Compound.getRHS());
2747 });
2748
2749 if (Compound.getCompoundKind() == FormulaType::Kind) {
2750 unsigned SizeLeft = Left.size();
2751 Res = std::move(Left);
2752 Res.reserve(SizeLeft + Right.size());
2753 std::for_each(std::make_move_iterator(Right.begin()),
2754 std::make_move_iterator(Right.end()), Add);
2755 return Res;
2756 }
2757
2758 Res.reserve(Left.size() * Right.size());
2759 for (const auto &LTransform : Left) {
2760 for (const auto &RTransform : Right) {
2761 Clause Combined;
2762 Combined.reserve(LTransform.size() + RTransform.size());
2763 llvm::copy(LTransform, std::back_inserter(Combined));
2764 llvm::copy(RTransform, std::back_inserter(Combined));
2765 Add(std::move(Combined));
2766 }
2767 }
2768 return Res;
2769 }
2770 }
2771 llvm_unreachable("Unknown ConstraintKind enum");
2772 }
2773
2774 void SubsumptionChecker::AddUniqueClauseToFormula(Formula &F, Clause C) {
2775 for (auto &Other : F) {
2776 if (llvm::equal(C, Other))
2777 return;
2778 }
2779 F.push_back(C);
2780 }
2781
2782 std::optional<bool> SubsumptionChecker::Subsumes(
2783 const NamedDecl *DP, ArrayRef<AssociatedConstraint> P, const NamedDecl *DQ,
2784 ArrayRef<AssociatedConstraint> Q) {
2785 const NormalizedConstraint *PNormalized =
2786 SemaRef.getNormalizedAssociatedConstraints(DP, P);
2787 if (!PNormalized)
2788 return std::nullopt;
2789
2790 const NormalizedConstraint *QNormalized =
2791 SemaRef.getNormalizedAssociatedConstraints(DQ, Q);
2792 if (!QNormalized)
2793 return std::nullopt;
2794
2795 return Subsumes(PNormalized, QNormalized);
2796 }
2797
2798 bool SubsumptionChecker::Subsumes(const NormalizedConstraint *P,
2799 const NormalizedConstraint *Q) {
2800
2801 DNFFormula DNFP = DNF(*P);
2802 CNFFormula CNFQ = CNF(*Q);
2803 return Subsumes(DNFP, CNFQ);
2804 }
2805
2806 bool SubsumptionChecker::Subsumes(const DNFFormula &PDNF,
2807 const CNFFormula &QCNF) {
2808 for (const auto &Pi : PDNF) {
2809 for (const auto &Qj : QCNF) {
2810 // C++ [temp.constr.order] p2
2811 // - [...] a disjunctive clause Pi subsumes a conjunctive clause Qj if
2812 // and only if there exists an atomic constraint Pia in Pi for which
2813 // there exists an atomic constraint, Qjb, in Qj such that Pia
2814 // subsumes Qjb.
2815 if (!DNFSubsumes(Pi, Qj))
2816 return false;
2817 }
2818 }
2819 return true;
2820 }
2821
2822 bool SubsumptionChecker::DNFSubsumes(const Clause &P, const Clause &Q) {
2823
2824 return llvm::any_of(P, [&](Literal LP) {
2825 return llvm::any_of(Q, [this, LP](Literal LQ) { return Subsumes(LP, LQ); });
2826 });
2827 }
2828
2829 bool SubsumptionChecker::Subsumes(const FoldExpandedConstraint *A,
2830 const FoldExpandedConstraint *B) {
2831 std::pair<const FoldExpandedConstraint *, const FoldExpandedConstraint *> Key{
2832 A, B};
2833
2834 auto It = FoldSubsumptionCache.find(Key);
2835 if (It == FoldSubsumptionCache.end()) {
2836 // C++ [temp.constr.order]
2837 // a fold expanded constraint A subsumes another fold expanded
2838 // constraint B if they are compatible for subsumption, have the same
2839 // fold-operator, and the constraint of A subsumes that of B.
2840 bool DoesSubsume =
2841 A->getFoldOperator() == B->getFoldOperator() &&
2842 FoldExpandedConstraint::AreCompatibleForSubsumption(*A, *B) &&
2843 Subsumes(&A->getNormalizedPattern(), &B->getNormalizedPattern());
2844 It = FoldSubsumptionCache.try_emplace(std::move(Key), DoesSubsume).first;
2845 }
2846 return It->second;
2847 }
2848
2849 bool SubsumptionChecker::Subsumes(Literal A, Literal B) {
2850 if (A.Kind != B.Kind)
2851 return false;
2852 switch (A.Kind) {
2853 case Literal::Atomic:
2854 if (!Callable)
2855 return A.Value == B.Value;
2856 return Callable(
2857 *static_cast<const AtomicConstraint *>(ReverseMap[A.Value]),
2858 *static_cast<const AtomicConstraint *>(ReverseMap[B.Value]));
2859 case Literal::FoldExpanded:
2860 return Subsumes(
2861 static_cast<const FoldExpandedConstraint *>(ReverseMap[A.Value]),
2862 static_cast<const FoldExpandedConstraint *>(ReverseMap[B.Value]));
2863 }
2864 llvm_unreachable("unknown literal kind");
2865 }