xref: /llvm-project/clang/lib/Sema/SemaConcept.cpp (revision 69d0c4c1675c90cf99126210679a9c3ae0a8637e)
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/ASTLambda.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/ExprConcepts.h"
18 #include "clang/Basic/OperatorPrecedence.h"
19 #include "clang/Sema/EnterExpressionEvaluationContext.h"
20 #include "clang/Sema/Initialization.h"
21 #include "clang/Sema/Overload.h"
22 #include "clang/Sema/ScopeInfo.h"
23 #include "clang/Sema/Sema.h"
24 #include "clang/Sema/SemaInternal.h"
25 #include "clang/Sema/Template.h"
26 #include "clang/Sema/TemplateDeduction.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/PointerUnion.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include <optional>
31 
32 using namespace clang;
33 using namespace sema;
34 
35 namespace {
36 class LogicalBinOp {
37   SourceLocation Loc;
38   OverloadedOperatorKind Op = OO_None;
39   const Expr *LHS = nullptr;
40   const Expr *RHS = nullptr;
41 
42 public:
43   LogicalBinOp(const Expr *E) {
44     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
45       Op = BinaryOperator::getOverloadedOperator(BO->getOpcode());
46       LHS = BO->getLHS();
47       RHS = BO->getRHS();
48       Loc = BO->getExprLoc();
49     } else if (auto *OO = dyn_cast<CXXOperatorCallExpr>(E)) {
50       // If OO is not || or && it might not have exactly 2 arguments.
51       if (OO->getNumArgs() == 2) {
52         Op = OO->getOperator();
53         LHS = OO->getArg(0);
54         RHS = OO->getArg(1);
55         Loc = OO->getOperatorLoc();
56       }
57     }
58   }
59 
60   bool isAnd() const { return Op == OO_AmpAmp; }
61   bool isOr() const { return Op == OO_PipePipe; }
62   explicit operator bool() const { return isAnd() || isOr(); }
63 
64   const Expr *getLHS() const { return LHS; }
65   const Expr *getRHS() const { return RHS; }
66   OverloadedOperatorKind getOp() const { return Op; }
67 
68   ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS) const {
69     return recreateBinOp(SemaRef, LHS, const_cast<Expr *>(getRHS()));
70   }
71 
72   ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS,
73                            ExprResult RHS) const {
74     assert((isAnd() || isOr()) && "Not the right kind of op?");
75     assert((!LHS.isInvalid() && !RHS.isInvalid()) && "not good expressions?");
76 
77     if (!LHS.isUsable() || !RHS.isUsable())
78       return ExprEmpty();
79 
80     // We should just be able to 'normalize' these to the builtin Binary
81     // Operator, since that is how they are evaluated in constriant checks.
82     return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
83                                   BinaryOperator::getOverloadedOpcode(Op),
84                                   SemaRef.Context.BoolTy, VK_PRValue,
85                                   OK_Ordinary, Loc, FPOptionsOverride{});
86   }
87 };
88 }
89 
90 bool Sema::CheckConstraintExpression(const Expr *ConstraintExpression,
91                                      Token NextToken, bool *PossibleNonPrimary,
92                                      bool IsTrailingRequiresClause) {
93   // C++2a [temp.constr.atomic]p1
94   // ..E shall be a constant expression of type bool.
95 
96   ConstraintExpression = ConstraintExpression->IgnoreParenImpCasts();
97 
98   if (LogicalBinOp BO = ConstraintExpression) {
99     return CheckConstraintExpression(BO.getLHS(), NextToken,
100                                      PossibleNonPrimary) &&
101            CheckConstraintExpression(BO.getRHS(), NextToken,
102                                      PossibleNonPrimary);
103   } else if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpression))
104     return CheckConstraintExpression(C->getSubExpr(), NextToken,
105                                      PossibleNonPrimary);
106 
107   QualType Type = ConstraintExpression->getType();
108 
109   auto CheckForNonPrimary = [&] {
110     if (!PossibleNonPrimary)
111       return;
112 
113     *PossibleNonPrimary =
114         // We have the following case:
115         // template<typename> requires func(0) struct S { };
116         // The user probably isn't aware of the parentheses required around
117         // the function call, and we're only going to parse 'func' as the
118         // primary-expression, and complain that it is of non-bool type.
119         //
120         // However, if we're in a lambda, this might also be:
121         // []<typename> requires var () {};
122         // Which also looks like a function call due to the lambda parentheses,
123         // but unlike the first case, isn't an error, so this check is skipped.
124         (NextToken.is(tok::l_paren) &&
125          (IsTrailingRequiresClause ||
126           (Type->isDependentType() &&
127            isa<UnresolvedLookupExpr>(ConstraintExpression) &&
128            !dyn_cast_if_present<LambdaScopeInfo>(getCurFunction())) ||
129           Type->isFunctionType() ||
130           Type->isSpecificBuiltinType(BuiltinType::Overload))) ||
131         // We have the following case:
132         // template<typename T> requires size_<T> == 0 struct S { };
133         // The user probably isn't aware of the parentheses required around
134         // the binary operator, and we're only going to parse 'func' as the
135         // first operand, and complain that it is of non-bool type.
136         getBinOpPrecedence(NextToken.getKind(),
137                            /*GreaterThanIsOperator=*/true,
138                            getLangOpts().CPlusPlus11) > prec::LogicalAnd;
139   };
140 
141   // An atomic constraint!
142   if (ConstraintExpression->isTypeDependent()) {
143     CheckForNonPrimary();
144     return true;
145   }
146 
147   if (!Context.hasSameUnqualifiedType(Type, Context.BoolTy)) {
148     Diag(ConstraintExpression->getExprLoc(),
149          diag::err_non_bool_atomic_constraint) << Type
150         << ConstraintExpression->getSourceRange();
151     CheckForNonPrimary();
152     return false;
153   }
154 
155   if (PossibleNonPrimary)
156       *PossibleNonPrimary = false;
157   return true;
158 }
159 
160 namespace {
161 struct SatisfactionStackRAII {
162   Sema &SemaRef;
163   bool Inserted = false;
164   SatisfactionStackRAII(Sema &SemaRef, const NamedDecl *ND,
165                         const llvm::FoldingSetNodeID &FSNID)
166       : SemaRef(SemaRef) {
167       if (ND) {
168       SemaRef.PushSatisfactionStackEntry(ND, FSNID);
169       Inserted = true;
170       }
171   }
172   ~SatisfactionStackRAII() {
173         if (Inserted)
174           SemaRef.PopSatisfactionStackEntry();
175   }
176 };
177 } // namespace
178 
179 template <typename ConstraintEvaluator>
180 static ExprResult
181 calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr,
182                                 ConstraintSatisfaction &Satisfaction,
183                                 const ConstraintEvaluator &Evaluator);
184 
185 template <typename ConstraintEvaluator>
186 static ExprResult
187 calculateConstraintSatisfaction(Sema &S, const Expr *LHS,
188                                 OverloadedOperatorKind Op, const Expr *RHS,
189                                 ConstraintSatisfaction &Satisfaction,
190                                 const ConstraintEvaluator &Evaluator) {
191   size_t EffectiveDetailEndIndex = Satisfaction.Details.size();
192 
193   ExprResult LHSRes =
194       calculateConstraintSatisfaction(S, LHS, Satisfaction, Evaluator);
195 
196   if (LHSRes.isInvalid())
197     return ExprError();
198 
199   bool IsLHSSatisfied = Satisfaction.IsSatisfied;
200 
201   if (Op == clang::OO_PipePipe && IsLHSSatisfied)
202     // [temp.constr.op] p3
203     //    A disjunction is a constraint taking two operands. To determine if
204     //    a disjunction is satisfied, the satisfaction of the first operand
205     //    is checked. If that is satisfied, the disjunction is satisfied.
206     //    Otherwise, the disjunction is satisfied if and only if the second
207     //    operand is satisfied.
208     // LHS is instantiated while RHS is not. Skip creating invalid BinaryOp.
209     return LHSRes;
210 
211   if (Op == clang::OO_AmpAmp && !IsLHSSatisfied)
212     // [temp.constr.op] p2
213     //    A conjunction is a constraint taking two operands. To determine if
214     //    a conjunction is satisfied, the satisfaction of the first operand
215     //    is checked. If that is not satisfied, the conjunction is not
216     //    satisfied. Otherwise, the conjunction is satisfied if and only if
217     //    the second operand is satisfied.
218     // LHS is instantiated while RHS is not. Skip creating invalid BinaryOp.
219     return LHSRes;
220 
221   ExprResult RHSRes =
222       calculateConstraintSatisfaction(S, RHS, Satisfaction, Evaluator);
223   if (RHSRes.isInvalid())
224     return ExprError();
225 
226   bool IsRHSSatisfied = Satisfaction.IsSatisfied;
227   // Current implementation adds diagnostic information about the falsity
228   // of each false atomic constraint expression when it evaluates them.
229   // When the evaluation results to `false || true`, the information
230   // generated during the evaluation of left-hand side is meaningless
231   // because the whole expression evaluates to true.
232   // The following code removes the irrelevant diagnostic information.
233   // FIXME: We should probably delay the addition of diagnostic information
234   // until we know the entire expression is false.
235   if (Op == clang::OO_PipePipe && IsRHSSatisfied) {
236     auto EffectiveDetailEnd = Satisfaction.Details.begin();
237     std::advance(EffectiveDetailEnd, EffectiveDetailEndIndex);
238     Satisfaction.Details.erase(EffectiveDetailEnd, Satisfaction.Details.end());
239   }
240 
241   if (!LHSRes.isUsable() || !RHSRes.isUsable())
242     return ExprEmpty();
243 
244   return BinaryOperator::Create(S.Context, LHSRes.get(), RHSRes.get(),
245                                 BinaryOperator::getOverloadedOpcode(Op),
246                                 S.Context.BoolTy, VK_PRValue, OK_Ordinary,
247                                 LHS->getBeginLoc(), FPOptionsOverride{});
248 }
249 
250 template <typename ConstraintEvaluator>
251 static ExprResult
252 calculateConstraintSatisfaction(Sema &S, const CXXFoldExpr *FE,
253                                 ConstraintSatisfaction &Satisfaction,
254                                 const ConstraintEvaluator &Evaluator) {
255   bool Conjunction = FE->getOperator() == BinaryOperatorKind::BO_LAnd;
256   size_t EffectiveDetailEndIndex = Satisfaction.Details.size();
257 
258   ExprResult Out;
259   if (FE->isLeftFold() && FE->getInit()) {
260     Out = calculateConstraintSatisfaction(S, FE->getInit(), Satisfaction,
261                                           Evaluator);
262     if (Out.isInvalid())
263       return ExprError();
264 
265     // If the first clause of a conjunction is not satisfied,
266     // or if the first clause of a disjection is satisfied,
267     // we have established satisfaction of the whole constraint
268     // and we should not continue further.
269     if (Conjunction != Satisfaction.IsSatisfied)
270       return Out;
271   }
272   std::optional<unsigned> NumExpansions =
273       Evaluator.EvaluateFoldExpandedConstraintSize(FE);
274   if (!NumExpansions)
275     return ExprError();
276   for (unsigned I = 0; I < *NumExpansions; I++) {
277     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
278     ExprResult Res = calculateConstraintSatisfaction(S, FE->getPattern(),
279                                                      Satisfaction, Evaluator);
280     if (Res.isInvalid())
281       return ExprError();
282     bool IsRHSSatisfied = Satisfaction.IsSatisfied;
283     if (!Conjunction && IsRHSSatisfied) {
284       auto EffectiveDetailEnd = Satisfaction.Details.begin();
285       std::advance(EffectiveDetailEnd, EffectiveDetailEndIndex);
286       Satisfaction.Details.erase(EffectiveDetailEnd,
287                                  Satisfaction.Details.end());
288     }
289     if (Out.isUnset())
290       Out = Res;
291     else if (!Res.isUnset()) {
292       Out = BinaryOperator::Create(
293           S.Context, Out.get(), Res.get(), FE->getOperator(), S.Context.BoolTy,
294           VK_PRValue, OK_Ordinary, FE->getBeginLoc(), FPOptionsOverride{});
295     }
296     if (Conjunction != IsRHSSatisfied)
297       return Out;
298   }
299 
300   if (FE->isRightFold() && FE->getInit()) {
301     ExprResult Res = calculateConstraintSatisfaction(S, FE->getInit(),
302                                                      Satisfaction, Evaluator);
303     if (Out.isInvalid())
304       return ExprError();
305 
306     if (Out.isUnset())
307       Out = Res;
308     else if (!Res.isUnset()) {
309       Out = BinaryOperator::Create(
310           S.Context, Out.get(), Res.get(), FE->getOperator(), S.Context.BoolTy,
311           VK_PRValue, OK_Ordinary, FE->getBeginLoc(), FPOptionsOverride{});
312     }
313   }
314 
315   if (Out.isUnset()) {
316     Satisfaction.IsSatisfied = Conjunction;
317     Out = S.BuildEmptyCXXFoldExpr(FE->getBeginLoc(), FE->getOperator());
318   }
319   return Out;
320 }
321 
322 template <typename ConstraintEvaluator>
323 static ExprResult
324 calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr,
325                                 ConstraintSatisfaction &Satisfaction,
326                                 const ConstraintEvaluator &Evaluator) {
327   ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
328 
329   if (LogicalBinOp BO = ConstraintExpr)
330     return calculateConstraintSatisfaction(
331         S, BO.getLHS(), BO.getOp(), BO.getRHS(), Satisfaction, Evaluator);
332 
333   if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpr)) {
334     // These aren't evaluated, so we don't care about cleanups, so we can just
335     // evaluate these as if the cleanups didn't exist.
336     return calculateConstraintSatisfaction(S, C->getSubExpr(), Satisfaction,
337                                            Evaluator);
338   }
339 
340   if (auto *FE = dyn_cast<CXXFoldExpr>(ConstraintExpr);
341       FE && S.getLangOpts().CPlusPlus26 &&
342       (FE->getOperator() == BinaryOperatorKind::BO_LAnd ||
343        FE->getOperator() == BinaryOperatorKind::BO_LOr)) {
344     return calculateConstraintSatisfaction(S, FE, Satisfaction, Evaluator);
345   }
346 
347   // An atomic constraint expression
348   ExprResult SubstitutedAtomicExpr =
349       Evaluator.EvaluateAtomicConstraint(ConstraintExpr);
350 
351   if (SubstitutedAtomicExpr.isInvalid())
352     return ExprError();
353 
354   if (!SubstitutedAtomicExpr.isUsable())
355     // Evaluator has decided satisfaction without yielding an expression.
356     return ExprEmpty();
357 
358   // We don't have the ability to evaluate this, since it contains a
359   // RecoveryExpr, so we want to fail overload resolution.  Otherwise,
360   // we'd potentially pick up a different overload, and cause confusing
361   // diagnostics. SO, add a failure detail that will cause us to make this
362   // overload set not viable.
363   if (SubstitutedAtomicExpr.get()->containsErrors()) {
364     Satisfaction.IsSatisfied = false;
365     Satisfaction.ContainsErrors = true;
366 
367     PartialDiagnostic Msg = S.PDiag(diag::note_constraint_references_error);
368     SmallString<128> DiagString;
369     DiagString = ": ";
370     Msg.EmitToString(S.getDiagnostics(), DiagString);
371     unsigned MessageSize = DiagString.size();
372     char *Mem = new (S.Context) char[MessageSize];
373     memcpy(Mem, DiagString.c_str(), MessageSize);
374     Satisfaction.Details.emplace_back(
375         new (S.Context) ConstraintSatisfaction::SubstitutionDiagnostic{
376             SubstitutedAtomicExpr.get()->getBeginLoc(),
377             StringRef(Mem, MessageSize)});
378     return SubstitutedAtomicExpr;
379   }
380 
381   EnterExpressionEvaluationContext ConstantEvaluated(
382       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
383   SmallVector<PartialDiagnosticAt, 2> EvaluationDiags;
384   Expr::EvalResult EvalResult;
385   EvalResult.Diag = &EvaluationDiags;
386   if (!SubstitutedAtomicExpr.get()->EvaluateAsConstantExpr(EvalResult,
387                                                            S.Context) ||
388       !EvaluationDiags.empty()) {
389     // C++2a [temp.constr.atomic]p1
390     //   ...E shall be a constant expression of type bool.
391     S.Diag(SubstitutedAtomicExpr.get()->getBeginLoc(),
392            diag::err_non_constant_constraint_expression)
393         << SubstitutedAtomicExpr.get()->getSourceRange();
394     for (const PartialDiagnosticAt &PDiag : EvaluationDiags)
395       S.Diag(PDiag.first, PDiag.second);
396     return ExprError();
397   }
398 
399   assert(EvalResult.Val.isInt() &&
400          "evaluating bool expression didn't produce int");
401   Satisfaction.IsSatisfied = EvalResult.Val.getInt().getBoolValue();
402   if (!Satisfaction.IsSatisfied)
403     Satisfaction.Details.emplace_back(SubstitutedAtomicExpr.get());
404 
405   return SubstitutedAtomicExpr;
406 }
407 
408 static bool
409 DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID,
410                             const NamedDecl *Templ, const Expr *E,
411                             const MultiLevelTemplateArgumentList &MLTAL) {
412   E->Profile(ID, S.Context, /*Canonical=*/true);
413   for (const auto &List : MLTAL)
414     for (const auto &TemplateArg : List.Args)
415       TemplateArg.Profile(ID, S.Context);
416 
417   // Note that we have to do this with our own collection, because there are
418   // times where a constraint-expression check can cause us to need to evaluate
419   // other constriants that are unrelated, such as when evaluating a recovery
420   // expression, or when trying to determine the constexpr-ness of special
421   // members. Otherwise we could just use the
422   // Sema::InstantiatingTemplate::isAlreadyBeingInstantiated function.
423   if (S.SatisfactionStackContains(Templ, ID)) {
424     S.Diag(E->getExprLoc(), diag::err_constraint_depends_on_self)
425         << const_cast<Expr *>(E) << E->getSourceRange();
426     return true;
427   }
428 
429   return false;
430 }
431 
432 static ExprResult calculateConstraintSatisfaction(
433     Sema &S, const NamedDecl *Template, SourceLocation TemplateNameLoc,
434     const MultiLevelTemplateArgumentList &MLTAL, const Expr *ConstraintExpr,
435     ConstraintSatisfaction &Satisfaction) {
436 
437   struct ConstraintEvaluator {
438     Sema &S;
439     const NamedDecl *Template;
440     SourceLocation TemplateNameLoc;
441     const MultiLevelTemplateArgumentList &MLTAL;
442     ConstraintSatisfaction &Satisfaction;
443 
444     ExprResult EvaluateAtomicConstraint(const Expr *AtomicExpr) const {
445       EnterExpressionEvaluationContext ConstantEvaluated(
446           S, Sema::ExpressionEvaluationContext::ConstantEvaluated,
447           Sema::ReuseLambdaContextDecl);
448 
449       // Atomic constraint - substitute arguments and check satisfaction.
450       ExprResult SubstitutedExpression;
451       {
452         TemplateDeductionInfo Info(TemplateNameLoc);
453         Sema::InstantiatingTemplate Inst(
454             S, AtomicExpr->getBeginLoc(),
455             Sema::InstantiatingTemplate::ConstraintSubstitution{},
456             const_cast<NamedDecl *>(Template), Info,
457             AtomicExpr->getSourceRange());
458         if (Inst.isInvalid())
459           return ExprError();
460 
461         llvm::FoldingSetNodeID ID;
462         if (Template &&
463             DiagRecursiveConstraintEval(S, ID, Template, AtomicExpr, MLTAL)) {
464           Satisfaction.IsSatisfied = false;
465           Satisfaction.ContainsErrors = true;
466           return ExprEmpty();
467         }
468 
469         SatisfactionStackRAII StackRAII(S, Template, ID);
470 
471         // We do not want error diagnostics escaping here.
472         Sema::SFINAETrap Trap(S);
473         SubstitutedExpression =
474             S.SubstConstraintExpr(const_cast<Expr *>(AtomicExpr), MLTAL);
475 
476         if (SubstitutedExpression.isInvalid() || Trap.hasErrorOccurred()) {
477           // C++2a [temp.constr.atomic]p1
478           //   ...If substitution results in an invalid type or expression, the
479           //   constraint is not satisfied.
480           if (!Trap.hasErrorOccurred())
481             // A non-SFINAE error has occurred as a result of this
482             // substitution.
483             return ExprError();
484 
485           PartialDiagnosticAt SubstDiag{SourceLocation(),
486                                         PartialDiagnostic::NullDiagnostic()};
487           Info.takeSFINAEDiagnostic(SubstDiag);
488           // FIXME: Concepts: This is an unfortunate consequence of there
489           //  being no serialization code for PartialDiagnostics and the fact
490           //  that serializing them would likely take a lot more storage than
491           //  just storing them as strings. We would still like, in the
492           //  future, to serialize the proper PartialDiagnostic as serializing
493           //  it as a string defeats the purpose of the diagnostic mechanism.
494           SmallString<128> DiagString;
495           DiagString = ": ";
496           SubstDiag.second.EmitToString(S.getDiagnostics(), DiagString);
497           unsigned MessageSize = DiagString.size();
498           char *Mem = new (S.Context) char[MessageSize];
499           memcpy(Mem, DiagString.c_str(), MessageSize);
500           Satisfaction.Details.emplace_back(
501               new (S.Context) ConstraintSatisfaction::SubstitutionDiagnostic{
502                   SubstDiag.first, StringRef(Mem, MessageSize)});
503           Satisfaction.IsSatisfied = false;
504           return ExprEmpty();
505         }
506       }
507 
508       if (!S.CheckConstraintExpression(SubstitutedExpression.get()))
509         return ExprError();
510 
511       // [temp.constr.atomic]p3: To determine if an atomic constraint is
512       // satisfied, the parameter mapping and template arguments are first
513       // substituted into its expression.  If substitution results in an
514       // invalid type or expression, the constraint is not satisfied.
515       // Otherwise, the lvalue-to-rvalue conversion is performed if necessary,
516       // and E shall be a constant expression of type bool.
517       //
518       // Perform the L to R Value conversion if necessary. We do so for all
519       // non-PRValue categories, else we fail to extend the lifetime of
520       // temporaries, and that fails the constant expression check.
521       if (!SubstitutedExpression.get()->isPRValue())
522         SubstitutedExpression = ImplicitCastExpr::Create(
523             S.Context, SubstitutedExpression.get()->getType(),
524             CK_LValueToRValue, SubstitutedExpression.get(),
525             /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
526 
527       return SubstitutedExpression;
528     }
529 
530     std::optional<unsigned>
531     EvaluateFoldExpandedConstraintSize(const CXXFoldExpr *FE) const {
532 
533       // We should ignore errors in the presence of packs of different size.
534       Sema::SFINAETrap Trap(S);
535 
536       Expr *Pattern = FE->getPattern();
537 
538       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
539       S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
540       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
541       bool Expand = true;
542       bool RetainExpansion = false;
543       std::optional<unsigned> OrigNumExpansions = FE->getNumExpansions(),
544                               NumExpansions = OrigNumExpansions;
545       if (S.CheckParameterPacksForExpansion(
546               FE->getEllipsisLoc(), Pattern->getSourceRange(), Unexpanded,
547               MLTAL, Expand, RetainExpansion, NumExpansions) ||
548           !Expand || RetainExpansion)
549         return std::nullopt;
550 
551       if (NumExpansions && S.getLangOpts().BracketDepth < NumExpansions) {
552         S.Diag(FE->getEllipsisLoc(),
553                clang::diag::err_fold_expression_limit_exceeded)
554             << *NumExpansions << S.getLangOpts().BracketDepth
555             << FE->getSourceRange();
556         S.Diag(FE->getEllipsisLoc(), diag::note_bracket_depth);
557         return std::nullopt;
558       }
559       return NumExpansions;
560     }
561   };
562 
563   return calculateConstraintSatisfaction(
564       S, ConstraintExpr, Satisfaction,
565       ConstraintEvaluator{S, Template, TemplateNameLoc, MLTAL, Satisfaction});
566 }
567 
568 static bool CheckConstraintSatisfaction(
569     Sema &S, const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
570     llvm::SmallVectorImpl<Expr *> &Converted,
571     const MultiLevelTemplateArgumentList &TemplateArgsLists,
572     SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
573   if (ConstraintExprs.empty()) {
574     Satisfaction.IsSatisfied = true;
575     return false;
576   }
577 
578   if (TemplateArgsLists.isAnyArgInstantiationDependent()) {
579     // No need to check satisfaction for dependent constraint expressions.
580     Satisfaction.IsSatisfied = true;
581     return false;
582   }
583 
584   ArrayRef<TemplateArgument> TemplateArgs =
585       TemplateArgsLists.getNumSubstitutedLevels() > 0
586           ? TemplateArgsLists.getOutermost()
587           : ArrayRef<TemplateArgument>{};
588   Sema::InstantiatingTemplate Inst(S, TemplateIDRange.getBegin(),
589       Sema::InstantiatingTemplate::ConstraintsCheck{},
590       const_cast<NamedDecl *>(Template), TemplateArgs, TemplateIDRange);
591   if (Inst.isInvalid())
592     return true;
593 
594   for (const Expr *ConstraintExpr : ConstraintExprs) {
595     ExprResult Res = calculateConstraintSatisfaction(
596         S, Template, TemplateIDRange.getBegin(), TemplateArgsLists,
597         ConstraintExpr, Satisfaction);
598     if (Res.isInvalid())
599       return true;
600 
601     Converted.push_back(Res.get());
602     if (!Satisfaction.IsSatisfied) {
603       // Backfill the 'converted' list with nulls so we can keep the Converted
604       // and unconverted lists in sync.
605       Converted.append(ConstraintExprs.size() - Converted.size(), nullptr);
606       // [temp.constr.op] p2
607       // [...] To determine if a conjunction is satisfied, the satisfaction
608       // of the first operand is checked. If that is not satisfied, the
609       // conjunction is not satisfied. [...]
610       return false;
611     }
612   }
613   return false;
614 }
615 
616 bool Sema::CheckConstraintSatisfaction(
617     const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
618     llvm::SmallVectorImpl<Expr *> &ConvertedConstraints,
619     const MultiLevelTemplateArgumentList &TemplateArgsLists,
620     SourceRange TemplateIDRange, ConstraintSatisfaction &OutSatisfaction) {
621   if (ConstraintExprs.empty()) {
622     OutSatisfaction.IsSatisfied = true;
623     return false;
624   }
625   if (!Template) {
626     return ::CheckConstraintSatisfaction(
627         *this, nullptr, ConstraintExprs, ConvertedConstraints,
628         TemplateArgsLists, TemplateIDRange, OutSatisfaction);
629   }
630   // Invalid templates could make their way here. Substituting them could result
631   // in dependent expressions.
632   if (Template->isInvalidDecl()) {
633     OutSatisfaction.IsSatisfied = false;
634     return true;
635   }
636 
637   // A list of the template argument list flattened in a predictible manner for
638   // the purposes of caching. The ConstraintSatisfaction type is in AST so it
639   // has no access to the MultiLevelTemplateArgumentList, so this has to happen
640   // here.
641   llvm::SmallVector<TemplateArgument, 4> FlattenedArgs;
642   for (auto List : TemplateArgsLists)
643     FlattenedArgs.insert(FlattenedArgs.end(), List.Args.begin(),
644                          List.Args.end());
645 
646   llvm::FoldingSetNodeID ID;
647   ConstraintSatisfaction::Profile(ID, Context, Template, FlattenedArgs);
648   void *InsertPos;
649   if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
650     OutSatisfaction = *Cached;
651     return false;
652   }
653 
654   auto Satisfaction =
655       std::make_unique<ConstraintSatisfaction>(Template, FlattenedArgs);
656   if (::CheckConstraintSatisfaction(*this, Template, ConstraintExprs,
657                                     ConvertedConstraints, TemplateArgsLists,
658                                     TemplateIDRange, *Satisfaction)) {
659     OutSatisfaction = *Satisfaction;
660     return true;
661   }
662 
663   if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
664     // The evaluation of this constraint resulted in us trying to re-evaluate it
665     // recursively. This isn't really possible, except we try to form a
666     // RecoveryExpr as a part of the evaluation.  If this is the case, just
667     // return the 'cached' version (which will have the same result), and save
668     // ourselves the extra-insert. If it ever becomes possible to legitimately
669     // recursively check a constraint, we should skip checking the 'inner' one
670     // above, and replace the cached version with this one, as it would be more
671     // specific.
672     OutSatisfaction = *Cached;
673     return false;
674   }
675 
676   // Else we can simply add this satisfaction to the list.
677   OutSatisfaction = *Satisfaction;
678   // We cannot use InsertPos here because CheckConstraintSatisfaction might have
679   // invalidated it.
680   // Note that entries of SatisfactionCache are deleted in Sema's destructor.
681   SatisfactionCache.InsertNode(Satisfaction.release());
682   return false;
683 }
684 
685 bool Sema::CheckConstraintSatisfaction(const Expr *ConstraintExpr,
686                                        ConstraintSatisfaction &Satisfaction) {
687 
688   struct ConstraintEvaluator {
689     Sema &S;
690     ExprResult EvaluateAtomicConstraint(const Expr *AtomicExpr) const {
691       return S.PerformContextuallyConvertToBool(const_cast<Expr *>(AtomicExpr));
692     }
693 
694     std::optional<unsigned>
695     EvaluateFoldExpandedConstraintSize(const CXXFoldExpr *FE) const {
696       return 0;
697     }
698   };
699 
700   return calculateConstraintSatisfaction(*this, ConstraintExpr, Satisfaction,
701                                          ConstraintEvaluator{*this})
702       .isInvalid();
703 }
704 
705 bool Sema::addInstantiatedCapturesToScope(
706     FunctionDecl *Function, const FunctionDecl *PatternDecl,
707     LocalInstantiationScope &Scope,
708     const MultiLevelTemplateArgumentList &TemplateArgs) {
709   const auto *LambdaClass = cast<CXXMethodDecl>(Function)->getParent();
710   const auto *LambdaPattern = cast<CXXMethodDecl>(PatternDecl)->getParent();
711 
712   unsigned Instantiated = 0;
713 
714   auto AddSingleCapture = [&](const ValueDecl *CapturedPattern,
715                               unsigned Index) {
716     ValueDecl *CapturedVar = LambdaClass->getCapture(Index)->getCapturedVar();
717     assert(CapturedVar->isInitCapture());
718     Scope.InstantiatedLocal(CapturedPattern, CapturedVar);
719   };
720 
721   for (const LambdaCapture &CapturePattern : LambdaPattern->captures()) {
722     if (!CapturePattern.capturesVariable()) {
723       Instantiated++;
724       continue;
725     }
726     ValueDecl *CapturedPattern = CapturePattern.getCapturedVar();
727 
728     if (!CapturedPattern->isInitCapture()) {
729       Instantiated++;
730       continue;
731     }
732 
733     if (!CapturedPattern->isParameterPack()) {
734       AddSingleCapture(CapturedPattern, Instantiated++);
735     } else {
736       Scope.MakeInstantiatedLocalArgPack(CapturedPattern);
737       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
738       SemaRef.collectUnexpandedParameterPacks(
739           dyn_cast<VarDecl>(CapturedPattern)->getInit(), Unexpanded);
740       auto NumArgumentsInExpansion =
741           getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
742       if (!NumArgumentsInExpansion)
743         continue;
744       for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg)
745         AddSingleCapture(CapturedPattern, Instantiated++);
746     }
747   }
748   return false;
749 }
750 
751 bool Sema::SetupConstraintScope(
752     FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
753     const MultiLevelTemplateArgumentList &MLTAL,
754     LocalInstantiationScope &Scope) {
755   assert(!isLambdaCallOperator(FD) &&
756          "Use LambdaScopeForCallOperatorInstantiationRAII to handle lambda "
757          "instantiations");
758   if (FD->isTemplateInstantiation() && FD->getPrimaryTemplate()) {
759     FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
760     InstantiatingTemplate Inst(
761         *this, FD->getPointOfInstantiation(),
762         Sema::InstantiatingTemplate::ConstraintsCheck{}, PrimaryTemplate,
763         TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
764         SourceRange());
765     if (Inst.isInvalid())
766       return true;
767 
768     // addInstantiatedParametersToScope creates a map of 'uninstantiated' to
769     // 'instantiated' parameters and adds it to the context. For the case where
770     // this function is a template being instantiated NOW, we also need to add
771     // the list of current template arguments to the list so that they also can
772     // be picked out of the map.
773     if (auto *SpecArgs = FD->getTemplateSpecializationArgs()) {
774       MultiLevelTemplateArgumentList JustTemplArgs(FD, SpecArgs->asArray(),
775                                                    /*Final=*/false);
776       if (addInstantiatedParametersToScope(
777               FD, PrimaryTemplate->getTemplatedDecl(), Scope, JustTemplArgs))
778         return true;
779     }
780 
781     // If this is a member function, make sure we get the parameters that
782     // reference the original primary template.
783     if (FunctionTemplateDecl *FromMemTempl =
784             PrimaryTemplate->getInstantiatedFromMemberTemplate()) {
785       if (addInstantiatedParametersToScope(FD, FromMemTempl->getTemplatedDecl(),
786                                            Scope, MLTAL))
787         return true;
788     }
789 
790     return false;
791   }
792 
793   if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization ||
794       FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate) {
795     FunctionDecl *InstantiatedFrom =
796         FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization
797             ? FD->getInstantiatedFromMemberFunction()
798             : FD->getInstantiatedFromDecl();
799 
800     InstantiatingTemplate Inst(
801         *this, FD->getPointOfInstantiation(),
802         Sema::InstantiatingTemplate::ConstraintsCheck{}, InstantiatedFrom,
803         TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
804         SourceRange());
805     if (Inst.isInvalid())
806       return true;
807 
808     // Case where this was not a template, but instantiated as a
809     // child-function.
810     if (addInstantiatedParametersToScope(FD, InstantiatedFrom, Scope, MLTAL))
811       return true;
812   }
813 
814   return false;
815 }
816 
817 // This function collects all of the template arguments for the purposes of
818 // constraint-instantiation and checking.
819 std::optional<MultiLevelTemplateArgumentList>
820 Sema::SetupConstraintCheckingTemplateArgumentsAndScope(
821     FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
822     LocalInstantiationScope &Scope) {
823   MultiLevelTemplateArgumentList MLTAL;
824 
825   // Collect the list of template arguments relative to the 'primary' template.
826   // We need the entire list, since the constraint is completely uninstantiated
827   // at this point.
828   MLTAL =
829       getTemplateInstantiationArgs(FD, FD->getLexicalDeclContext(),
830                                    /*Final=*/false, /*Innermost=*/std::nullopt,
831                                    /*RelativeToPrimary=*/true,
832                                    /*Pattern=*/nullptr,
833                                    /*ForConstraintInstantiation=*/true);
834   // Lambdas are handled by LambdaScopeForCallOperatorInstantiationRAII.
835   if (isLambdaCallOperator(FD))
836     return MLTAL;
837   if (SetupConstraintScope(FD, TemplateArgs, MLTAL, Scope))
838     return std::nullopt;
839 
840   return MLTAL;
841 }
842 
843 bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
844                                     ConstraintSatisfaction &Satisfaction,
845                                     SourceLocation UsageLoc,
846                                     bool ForOverloadResolution) {
847   // Don't check constraints if the function is dependent. Also don't check if
848   // this is a function template specialization, as the call to
849   // CheckinstantiatedFunctionTemplateConstraints after this will check it
850   // better.
851   if (FD->isDependentContext() ||
852       FD->getTemplatedKind() ==
853           FunctionDecl::TK_FunctionTemplateSpecialization) {
854     Satisfaction.IsSatisfied = true;
855     return false;
856   }
857 
858   // A lambda conversion operator has the same constraints as the call operator
859   // and constraints checking relies on whether we are in a lambda call operator
860   // (and may refer to its parameters), so check the call operator instead.
861   // Note that the declarations outside of the lambda should also be
862   // considered. Turning on the 'ForOverloadResolution' flag results in the
863   // LocalInstantiationScope not looking into its parents, but we can still
864   // access Decls from the parents while building a lambda RAII scope later.
865   if (const auto *MD = dyn_cast<CXXConversionDecl>(FD);
866       MD && isLambdaConversionOperator(const_cast<CXXConversionDecl *>(MD)))
867     return CheckFunctionConstraints(MD->getParent()->getLambdaCallOperator(),
868                                     Satisfaction, UsageLoc,
869                                     /*ShouldAddDeclsFromParentScope=*/true);
870 
871   DeclContext *CtxToSave = const_cast<FunctionDecl *>(FD);
872 
873   while (isLambdaCallOperator(CtxToSave) || FD->isTransparentContext()) {
874     if (isLambdaCallOperator(CtxToSave))
875       CtxToSave = CtxToSave->getParent()->getParent();
876     else
877       CtxToSave = CtxToSave->getNonTransparentContext();
878   }
879 
880   ContextRAII SavedContext{*this, CtxToSave};
881   LocalInstantiationScope Scope(*this, !ForOverloadResolution);
882   std::optional<MultiLevelTemplateArgumentList> MLTAL =
883       SetupConstraintCheckingTemplateArgumentsAndScope(
884           const_cast<FunctionDecl *>(FD), {}, Scope);
885 
886   if (!MLTAL)
887     return true;
888 
889   Qualifiers ThisQuals;
890   CXXRecordDecl *Record = nullptr;
891   if (auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
892     ThisQuals = Method->getMethodQualifiers();
893     Record = const_cast<CXXRecordDecl *>(Method->getParent());
894   }
895   CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
896 
897   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
898       *this, const_cast<FunctionDecl *>(FD), *MLTAL, Scope,
899       ForOverloadResolution);
900 
901   return CheckConstraintSatisfaction(
902       FD, {FD->getTrailingRequiresClause()}, *MLTAL,
903       SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
904       Satisfaction);
905 }
906 
907 
908 // Figure out the to-translation-unit depth for this function declaration for
909 // the purpose of seeing if they differ by constraints. This isn't the same as
910 // getTemplateDepth, because it includes already instantiated parents.
911 static unsigned
912 CalculateTemplateDepthForConstraints(Sema &S, const NamedDecl *ND,
913                                      bool SkipForSpecialization = false) {
914   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
915       ND, ND->getLexicalDeclContext(), /*Final=*/false,
916       /*Innermost=*/std::nullopt,
917       /*RelativeToPrimary=*/true,
918       /*Pattern=*/nullptr,
919       /*ForConstraintInstantiation=*/true, SkipForSpecialization);
920   return MLTAL.getNumLevels();
921 }
922 
923 namespace {
924   class AdjustConstraintDepth : public TreeTransform<AdjustConstraintDepth> {
925   unsigned TemplateDepth = 0;
926   public:
927   using inherited = TreeTransform<AdjustConstraintDepth>;
928   AdjustConstraintDepth(Sema &SemaRef, unsigned TemplateDepth)
929       : inherited(SemaRef), TemplateDepth(TemplateDepth) {}
930 
931   using inherited::TransformTemplateTypeParmType;
932   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
933                                          TemplateTypeParmTypeLoc TL, bool) {
934     const TemplateTypeParmType *T = TL.getTypePtr();
935 
936     TemplateTypeParmDecl *NewTTPDecl = nullptr;
937     if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
938       NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
939           TransformDecl(TL.getNameLoc(), OldTTPDecl));
940 
941     QualType Result = getSema().Context.getTemplateTypeParmType(
942         T->getDepth() + TemplateDepth, T->getIndex(), T->isParameterPack(),
943         NewTTPDecl);
944     TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
945     NewTL.setNameLoc(TL.getNameLoc());
946     return Result;
947   }
948   };
949 } // namespace
950 
951 static const Expr *SubstituteConstraintExpressionWithoutSatisfaction(
952     Sema &S, const Sema::TemplateCompareNewDeclInfo &DeclInfo,
953     const Expr *ConstrExpr) {
954   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
955       DeclInfo.getDecl(), DeclInfo.getLexicalDeclContext(), /*Final=*/false,
956       /*Innermost=*/std::nullopt,
957       /*RelativeToPrimary=*/true,
958       /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
959       /*SkipForSpecialization*/ false);
960 
961   if (MLTAL.getNumSubstitutedLevels() == 0)
962     return ConstrExpr;
963 
964   Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
965 
966   Sema::InstantiatingTemplate Inst(
967       S, DeclInfo.getLocation(),
968       Sema::InstantiatingTemplate::ConstraintNormalization{},
969       const_cast<NamedDecl *>(DeclInfo.getDecl()), SourceRange{});
970   if (Inst.isInvalid())
971     return nullptr;
972 
973   // Set up a dummy 'instantiation' scope in the case of reference to function
974   // parameters that the surrounding function hasn't been instantiated yet. Note
975   // this may happen while we're comparing two templates' constraint
976   // equivalence.
977   std::optional<LocalInstantiationScope> ScopeForParameters;
978   if (const NamedDecl *ND = DeclInfo.getDecl();
979       ND && ND->isFunctionOrFunctionTemplate()) {
980     ScopeForParameters.emplace(S, /*CombineWithOuterScope=*/true);
981     const FunctionDecl *FD = ND->getAsFunction();
982     for (auto *PVD : FD->parameters()) {
983       if (!PVD->isParameterPack()) {
984         ScopeForParameters->InstantiatedLocal(PVD, PVD);
985         continue;
986       }
987       // This is hacky: we're mapping the parameter pack to a size-of-1 argument
988       // to avoid building SubstTemplateTypeParmPackTypes for
989       // PackExpansionTypes. The SubstTemplateTypeParmPackType node would
990       // otherwise reference the AssociatedDecl of the template arguments, which
991       // is, in this case, the template declaration.
992       //
993       // However, as we are in the process of comparing potential
994       // re-declarations, the canonical declaration is the declaration itself at
995       // this point. So if we didn't expand these packs, we would end up with an
996       // incorrect profile difference because we will be profiling the
997       // canonical types!
998       //
999       // FIXME: Improve the "no-transform" machinery in FindInstantiatedDecl so
1000       // that we can eliminate the Scope in the cases where the declarations are
1001       // not necessarily instantiated. It would also benefit the noexcept
1002       // specifier comparison.
1003       ScopeForParameters->MakeInstantiatedLocalArgPack(PVD);
1004       ScopeForParameters->InstantiatedLocalPackArg(PVD, PVD);
1005     }
1006   }
1007 
1008   std::optional<Sema::CXXThisScopeRAII> ThisScope;
1009 
1010   // See TreeTransform::RebuildTemplateSpecializationType. A context scope is
1011   // essential for having an injected class as the canonical type for a template
1012   // specialization type at the rebuilding stage. This guarantees that, for
1013   // out-of-line definitions, injected class name types and their equivalent
1014   // template specializations can be profiled to the same value, which makes it
1015   // possible that e.g. constraints involving C<Class<T>> and C<Class> are
1016   // perceived identical.
1017   std::optional<Sema::ContextRAII> ContextScope;
1018   const DeclContext *DC = [&] {
1019     if (!DeclInfo.getDecl())
1020       return DeclInfo.getDeclContext();
1021     return DeclInfo.getDecl()->getFriendObjectKind()
1022                ? DeclInfo.getLexicalDeclContext()
1023                : DeclInfo.getDeclContext();
1024   }();
1025   if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
1026     ThisScope.emplace(S, const_cast<CXXRecordDecl *>(RD), Qualifiers());
1027     ContextScope.emplace(S, const_cast<DeclContext *>(cast<DeclContext>(RD)),
1028                          /*NewThisContext=*/false);
1029   }
1030   EnterExpressionEvaluationContext UnevaluatedContext(
1031       S, Sema::ExpressionEvaluationContext::Unevaluated,
1032       Sema::ReuseLambdaContextDecl);
1033   ExprResult SubstConstr = S.SubstConstraintExprWithoutSatisfaction(
1034       const_cast<clang::Expr *>(ConstrExpr), MLTAL);
1035   if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
1036     return nullptr;
1037   return SubstConstr.get();
1038 }
1039 
1040 bool Sema::AreConstraintExpressionsEqual(const NamedDecl *Old,
1041                                          const Expr *OldConstr,
1042                                          const TemplateCompareNewDeclInfo &New,
1043                                          const Expr *NewConstr) {
1044   if (OldConstr == NewConstr)
1045     return true;
1046   // C++ [temp.constr.decl]p4
1047   if (Old && !New.isInvalid() && !New.ContainsDecl(Old) &&
1048       Old->getLexicalDeclContext() != New.getLexicalDeclContext()) {
1049     if (const Expr *SubstConstr =
1050             SubstituteConstraintExpressionWithoutSatisfaction(*this, Old,
1051                                                               OldConstr))
1052       OldConstr = SubstConstr;
1053     else
1054       return false;
1055     if (const Expr *SubstConstr =
1056             SubstituteConstraintExpressionWithoutSatisfaction(*this, New,
1057                                                               NewConstr))
1058       NewConstr = SubstConstr;
1059     else
1060       return false;
1061   }
1062 
1063   llvm::FoldingSetNodeID ID1, ID2;
1064   OldConstr->Profile(ID1, Context, /*Canonical=*/true);
1065   NewConstr->Profile(ID2, Context, /*Canonical=*/true);
1066   return ID1 == ID2;
1067 }
1068 
1069 bool Sema::FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD) {
1070   assert(FD->getFriendObjectKind() && "Must be a friend!");
1071 
1072   // The logic for non-templates is handled in ASTContext::isSameEntity, so we
1073   // don't have to bother checking 'DependsOnEnclosingTemplate' for a
1074   // non-function-template.
1075   assert(FD->getDescribedFunctionTemplate() &&
1076          "Non-function templates don't need to be checked");
1077 
1078   SmallVector<const Expr *, 3> ACs;
1079   FD->getDescribedFunctionTemplate()->getAssociatedConstraints(ACs);
1080 
1081   unsigned OldTemplateDepth = CalculateTemplateDepthForConstraints(*this, FD);
1082   for (const Expr *Constraint : ACs)
1083     if (ConstraintExpressionDependsOnEnclosingTemplate(FD, OldTemplateDepth,
1084                                                        Constraint))
1085       return true;
1086 
1087   return false;
1088 }
1089 
1090 bool Sema::EnsureTemplateArgumentListConstraints(
1091     TemplateDecl *TD, const MultiLevelTemplateArgumentList &TemplateArgsLists,
1092     SourceRange TemplateIDRange) {
1093   ConstraintSatisfaction Satisfaction;
1094   llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
1095   TD->getAssociatedConstraints(AssociatedConstraints);
1096   if (CheckConstraintSatisfaction(TD, AssociatedConstraints, TemplateArgsLists,
1097                                   TemplateIDRange, Satisfaction))
1098     return true;
1099 
1100   if (!Satisfaction.IsSatisfied) {
1101     SmallString<128> TemplateArgString;
1102     TemplateArgString = " ";
1103     TemplateArgString += getTemplateArgumentBindingsText(
1104         TD->getTemplateParameters(), TemplateArgsLists.getInnermost().data(),
1105         TemplateArgsLists.getInnermost().size());
1106 
1107     Diag(TemplateIDRange.getBegin(),
1108          diag::err_template_arg_list_constraints_not_satisfied)
1109         << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << TD
1110         << TemplateArgString << TemplateIDRange;
1111     DiagnoseUnsatisfiedConstraint(Satisfaction);
1112     return true;
1113   }
1114   return false;
1115 }
1116 
1117 bool Sema::CheckInstantiatedFunctionTemplateConstraints(
1118     SourceLocation PointOfInstantiation, FunctionDecl *Decl,
1119     ArrayRef<TemplateArgument> TemplateArgs,
1120     ConstraintSatisfaction &Satisfaction) {
1121   // In most cases we're not going to have constraints, so check for that first.
1122   FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
1123   // Note - code synthesis context for the constraints check is created
1124   // inside CheckConstraintsSatisfaction.
1125   SmallVector<const Expr *, 3> TemplateAC;
1126   Template->getAssociatedConstraints(TemplateAC);
1127   if (TemplateAC.empty()) {
1128     Satisfaction.IsSatisfied = true;
1129     return false;
1130   }
1131 
1132   // Enter the scope of this instantiation. We don't use
1133   // PushDeclContext because we don't have a scope.
1134   Sema::ContextRAII savedContext(*this, Decl);
1135   LocalInstantiationScope Scope(*this);
1136 
1137   std::optional<MultiLevelTemplateArgumentList> MLTAL =
1138       SetupConstraintCheckingTemplateArgumentsAndScope(Decl, TemplateArgs,
1139                                                        Scope);
1140 
1141   if (!MLTAL)
1142     return true;
1143 
1144   Qualifiers ThisQuals;
1145   CXXRecordDecl *Record = nullptr;
1146   if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
1147     ThisQuals = Method->getMethodQualifiers();
1148     Record = Method->getParent();
1149   }
1150 
1151   CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
1152   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
1153       *this, const_cast<FunctionDecl *>(Decl), *MLTAL, Scope);
1154 
1155   llvm::SmallVector<Expr *, 1> Converted;
1156   return CheckConstraintSatisfaction(Template, TemplateAC, Converted, *MLTAL,
1157                                      PointOfInstantiation, Satisfaction);
1158 }
1159 
1160 static void diagnoseUnsatisfiedRequirement(Sema &S,
1161                                            concepts::ExprRequirement *Req,
1162                                            bool First) {
1163   assert(!Req->isSatisfied()
1164          && "Diagnose() can only be used on an unsatisfied requirement");
1165   switch (Req->getSatisfactionStatus()) {
1166     case concepts::ExprRequirement::SS_Dependent:
1167       llvm_unreachable("Diagnosing a dependent requirement");
1168       break;
1169     case concepts::ExprRequirement::SS_ExprSubstitutionFailure: {
1170       auto *SubstDiag = Req->getExprSubstitutionDiagnostic();
1171       if (!SubstDiag->DiagMessage.empty())
1172         S.Diag(SubstDiag->DiagLoc,
1173                diag::note_expr_requirement_expr_substitution_error)
1174                << (int)First << SubstDiag->SubstitutedEntity
1175                << SubstDiag->DiagMessage;
1176       else
1177         S.Diag(SubstDiag->DiagLoc,
1178                diag::note_expr_requirement_expr_unknown_substitution_error)
1179             << (int)First << SubstDiag->SubstitutedEntity;
1180       break;
1181     }
1182     case concepts::ExprRequirement::SS_NoexceptNotMet:
1183       S.Diag(Req->getNoexceptLoc(),
1184              diag::note_expr_requirement_noexcept_not_met)
1185           << (int)First << Req->getExpr();
1186       break;
1187     case concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure: {
1188       auto *SubstDiag =
1189           Req->getReturnTypeRequirement().getSubstitutionDiagnostic();
1190       if (!SubstDiag->DiagMessage.empty())
1191         S.Diag(SubstDiag->DiagLoc,
1192                diag::note_expr_requirement_type_requirement_substitution_error)
1193             << (int)First << SubstDiag->SubstitutedEntity
1194             << SubstDiag->DiagMessage;
1195       else
1196         S.Diag(SubstDiag->DiagLoc,
1197                diag::note_expr_requirement_type_requirement_unknown_substitution_error)
1198             << (int)First << SubstDiag->SubstitutedEntity;
1199       break;
1200     }
1201     case concepts::ExprRequirement::SS_ConstraintsNotSatisfied: {
1202       ConceptSpecializationExpr *ConstraintExpr =
1203           Req->getReturnTypeRequirementSubstitutedConstraintExpr();
1204       if (ConstraintExpr->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
1205         // A simple case - expr type is the type being constrained and the concept
1206         // was not provided arguments.
1207         Expr *e = Req->getExpr();
1208         S.Diag(e->getBeginLoc(),
1209                diag::note_expr_requirement_constraints_not_satisfied_simple)
1210             << (int)First << S.Context.getReferenceQualifiedType(e)
1211             << ConstraintExpr->getNamedConcept();
1212       } else {
1213         S.Diag(ConstraintExpr->getBeginLoc(),
1214                diag::note_expr_requirement_constraints_not_satisfied)
1215             << (int)First << ConstraintExpr;
1216       }
1217       S.DiagnoseUnsatisfiedConstraint(ConstraintExpr->getSatisfaction());
1218       break;
1219     }
1220     case concepts::ExprRequirement::SS_Satisfied:
1221       llvm_unreachable("We checked this above");
1222   }
1223 }
1224 
1225 static void diagnoseUnsatisfiedRequirement(Sema &S,
1226                                            concepts::TypeRequirement *Req,
1227                                            bool First) {
1228   assert(!Req->isSatisfied()
1229          && "Diagnose() can only be used on an unsatisfied requirement");
1230   switch (Req->getSatisfactionStatus()) {
1231   case concepts::TypeRequirement::SS_Dependent:
1232     llvm_unreachable("Diagnosing a dependent requirement");
1233     return;
1234   case concepts::TypeRequirement::SS_SubstitutionFailure: {
1235     auto *SubstDiag = Req->getSubstitutionDiagnostic();
1236     if (!SubstDiag->DiagMessage.empty())
1237       S.Diag(SubstDiag->DiagLoc,
1238              diag::note_type_requirement_substitution_error) << (int)First
1239           << SubstDiag->SubstitutedEntity << SubstDiag->DiagMessage;
1240     else
1241       S.Diag(SubstDiag->DiagLoc,
1242              diag::note_type_requirement_unknown_substitution_error)
1243           << (int)First << SubstDiag->SubstitutedEntity;
1244     return;
1245   }
1246   default:
1247     llvm_unreachable("Unknown satisfaction status");
1248     return;
1249   }
1250 }
1251 static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S,
1252                                                         Expr *SubstExpr,
1253                                                         bool First = true);
1254 
1255 static void diagnoseUnsatisfiedRequirement(Sema &S,
1256                                            concepts::NestedRequirement *Req,
1257                                            bool First) {
1258   using SubstitutionDiagnostic = std::pair<SourceLocation, StringRef>;
1259   for (auto &Record : Req->getConstraintSatisfaction()) {
1260     if (auto *SubstDiag = Record.dyn_cast<SubstitutionDiagnostic *>())
1261       S.Diag(SubstDiag->first, diag::note_nested_requirement_substitution_error)
1262           << (int)First << Req->getInvalidConstraintEntity()
1263           << SubstDiag->second;
1264     else
1265       diagnoseWellFormedUnsatisfiedConstraintExpr(S, Record.dyn_cast<Expr *>(),
1266                                                   First);
1267     First = false;
1268   }
1269 }
1270 
1271 static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S,
1272                                                         Expr *SubstExpr,
1273                                                         bool First) {
1274   SubstExpr = SubstExpr->IgnoreParenImpCasts();
1275   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SubstExpr)) {
1276     switch (BO->getOpcode()) {
1277     // These two cases will in practice only be reached when using fold
1278     // expressions with || and &&, since otherwise the || and && will have been
1279     // broken down into atomic constraints during satisfaction checking.
1280     case BO_LOr:
1281       // Or evaluated to false - meaning both RHS and LHS evaluated to false.
1282       diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
1283       diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
1284                                                   /*First=*/false);
1285       return;
1286     case BO_LAnd: {
1287       bool LHSSatisfied =
1288           BO->getLHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1289       if (LHSSatisfied) {
1290         // LHS is true, so RHS must be false.
1291         diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(), First);
1292         return;
1293       }
1294       // LHS is false
1295       diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
1296 
1297       // RHS might also be false
1298       bool RHSSatisfied =
1299           BO->getRHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1300       if (!RHSSatisfied)
1301         diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
1302                                                     /*First=*/false);
1303       return;
1304     }
1305     case BO_GE:
1306     case BO_LE:
1307     case BO_GT:
1308     case BO_LT:
1309     case BO_EQ:
1310     case BO_NE:
1311       if (BO->getLHS()->getType()->isIntegerType() &&
1312           BO->getRHS()->getType()->isIntegerType()) {
1313         Expr::EvalResult SimplifiedLHS;
1314         Expr::EvalResult SimplifiedRHS;
1315         BO->getLHS()->EvaluateAsInt(SimplifiedLHS, S.Context,
1316                                     Expr::SE_NoSideEffects,
1317                                     /*InConstantContext=*/true);
1318         BO->getRHS()->EvaluateAsInt(SimplifiedRHS, S.Context,
1319                                     Expr::SE_NoSideEffects,
1320                                     /*InConstantContext=*/true);
1321         if (!SimplifiedLHS.Diag && ! SimplifiedRHS.Diag) {
1322           S.Diag(SubstExpr->getBeginLoc(),
1323                  diag::note_atomic_constraint_evaluated_to_false_elaborated)
1324               << (int)First << SubstExpr
1325               << toString(SimplifiedLHS.Val.getInt(), 10)
1326               << BinaryOperator::getOpcodeStr(BO->getOpcode())
1327               << toString(SimplifiedRHS.Val.getInt(), 10);
1328           return;
1329         }
1330       }
1331       break;
1332 
1333     default:
1334       break;
1335     }
1336   } else if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(SubstExpr)) {
1337     if (CSE->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
1338       S.Diag(
1339           CSE->getSourceRange().getBegin(),
1340           diag::
1341           note_single_arg_concept_specialization_constraint_evaluated_to_false)
1342           << (int)First
1343           << CSE->getTemplateArgsAsWritten()->arguments()[0].getArgument()
1344           << CSE->getNamedConcept();
1345     } else {
1346       S.Diag(SubstExpr->getSourceRange().getBegin(),
1347              diag::note_concept_specialization_constraint_evaluated_to_false)
1348           << (int)First << CSE;
1349     }
1350     S.DiagnoseUnsatisfiedConstraint(CSE->getSatisfaction());
1351     return;
1352   } else if (auto *RE = dyn_cast<RequiresExpr>(SubstExpr)) {
1353     // FIXME: RequiresExpr should store dependent diagnostics.
1354     for (concepts::Requirement *Req : RE->getRequirements())
1355       if (!Req->isDependent() && !Req->isSatisfied()) {
1356         if (auto *E = dyn_cast<concepts::ExprRequirement>(Req))
1357           diagnoseUnsatisfiedRequirement(S, E, First);
1358         else if (auto *T = dyn_cast<concepts::TypeRequirement>(Req))
1359           diagnoseUnsatisfiedRequirement(S, T, First);
1360         else
1361           diagnoseUnsatisfiedRequirement(
1362               S, cast<concepts::NestedRequirement>(Req), First);
1363         break;
1364       }
1365     return;
1366   } else if (auto *TTE = dyn_cast<TypeTraitExpr>(SubstExpr);
1367              TTE && TTE->getTrait() == clang::TypeTrait::BTT_IsDeducible) {
1368     assert(TTE->getNumArgs() == 2);
1369     S.Diag(SubstExpr->getSourceRange().getBegin(),
1370            diag::note_is_deducible_constraint_evaluated_to_false)
1371         << TTE->getArg(0)->getType() << TTE->getArg(1)->getType();
1372     return;
1373   }
1374 
1375   S.Diag(SubstExpr->getSourceRange().getBegin(),
1376          diag::note_atomic_constraint_evaluated_to_false)
1377       << (int)First << SubstExpr;
1378 }
1379 
1380 template <typename SubstitutionDiagnostic>
1381 static void diagnoseUnsatisfiedConstraintExpr(
1382     Sema &S, const llvm::PointerUnion<Expr *, SubstitutionDiagnostic *> &Record,
1383     bool First = true) {
1384   if (auto *Diag = Record.template dyn_cast<SubstitutionDiagnostic *>()) {
1385     S.Diag(Diag->first, diag::note_substituted_constraint_expr_is_ill_formed)
1386         << Diag->second;
1387     return;
1388   }
1389 
1390   diagnoseWellFormedUnsatisfiedConstraintExpr(S, cast<Expr *>(Record), First);
1391 }
1392 
1393 void
1394 Sema::DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction& Satisfaction,
1395                                     bool First) {
1396   assert(!Satisfaction.IsSatisfied &&
1397          "Attempted to diagnose a satisfied constraint");
1398   for (auto &Record : Satisfaction.Details) {
1399     diagnoseUnsatisfiedConstraintExpr(*this, Record, First);
1400     First = false;
1401   }
1402 }
1403 
1404 void Sema::DiagnoseUnsatisfiedConstraint(
1405     const ASTConstraintSatisfaction &Satisfaction,
1406     bool First) {
1407   assert(!Satisfaction.IsSatisfied &&
1408          "Attempted to diagnose a satisfied constraint");
1409   for (auto &Record : Satisfaction) {
1410     diagnoseUnsatisfiedConstraintExpr(*this, Record, First);
1411     First = false;
1412   }
1413 }
1414 
1415 const NormalizedConstraint *
1416 Sema::getNormalizedAssociatedConstraints(
1417     NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints) {
1418   // In case the ConstrainedDecl comes from modules, it is necessary to use
1419   // the canonical decl to avoid different atomic constraints with the 'same'
1420   // declarations.
1421   ConstrainedDecl = cast<NamedDecl>(ConstrainedDecl->getCanonicalDecl());
1422 
1423   auto CacheEntry = NormalizationCache.find(ConstrainedDecl);
1424   if (CacheEntry == NormalizationCache.end()) {
1425     auto Normalized =
1426         NormalizedConstraint::fromConstraintExprs(*this, ConstrainedDecl,
1427                                                   AssociatedConstraints);
1428     CacheEntry =
1429         NormalizationCache
1430             .try_emplace(ConstrainedDecl,
1431                          Normalized
1432                              ? new (Context) NormalizedConstraint(
1433                                  std::move(*Normalized))
1434                              : nullptr)
1435             .first;
1436   }
1437   return CacheEntry->second;
1438 }
1439 
1440 const NormalizedConstraint *clang::getNormalizedAssociatedConstraints(
1441     Sema &S, NamedDecl *ConstrainedDecl,
1442     ArrayRef<const Expr *> AssociatedConstraints) {
1443   return S.getNormalizedAssociatedConstraints(ConstrainedDecl,
1444                                               AssociatedConstraints);
1445 }
1446 
1447 static bool
1448 substituteParameterMappings(Sema &S, NormalizedConstraint &N,
1449                             ConceptDecl *Concept,
1450                             const MultiLevelTemplateArgumentList &MLTAL,
1451                             const ASTTemplateArgumentListInfo *ArgsAsWritten) {
1452 
1453   if (N.isCompound()) {
1454     if (substituteParameterMappings(S, N.getLHS(), Concept, MLTAL,
1455                                     ArgsAsWritten))
1456       return true;
1457     return substituteParameterMappings(S, N.getRHS(), Concept, MLTAL,
1458                                        ArgsAsWritten);
1459   }
1460 
1461   if (N.isFoldExpanded()) {
1462     Sema::ArgumentPackSubstitutionIndexRAII _(S, -1);
1463     return substituteParameterMappings(
1464         S, N.getFoldExpandedConstraint()->Constraint, Concept, MLTAL,
1465         ArgsAsWritten);
1466   }
1467 
1468   TemplateParameterList *TemplateParams = Concept->getTemplateParameters();
1469 
1470   AtomicConstraint &Atomic = *N.getAtomicConstraint();
1471   TemplateArgumentListInfo SubstArgs;
1472   if (!Atomic.ParameterMapping) {
1473     llvm::SmallBitVector OccurringIndices(TemplateParams->size());
1474     S.MarkUsedTemplateParameters(Atomic.ConstraintExpr, /*OnlyDeduced=*/false,
1475                                  /*Depth=*/0, OccurringIndices);
1476     TemplateArgumentLoc *TempArgs =
1477         new (S.Context) TemplateArgumentLoc[OccurringIndices.count()];
1478     for (unsigned I = 0, J = 0, C = TemplateParams->size(); I != C; ++I)
1479       if (OccurringIndices[I])
1480         new (&(TempArgs)[J++])
1481             TemplateArgumentLoc(S.getIdentityTemplateArgumentLoc(
1482                 TemplateParams->begin()[I],
1483                 // Here we assume we do not support things like
1484                 // template<typename A, typename B>
1485                 // concept C = ...;
1486                 //
1487                 // template<typename... Ts> requires C<Ts...>
1488                 // struct S { };
1489                 // The above currently yields a diagnostic.
1490                 // We still might have default arguments for concept parameters.
1491                 ArgsAsWritten->NumTemplateArgs > I
1492                     ? ArgsAsWritten->arguments()[I].getLocation()
1493                     : SourceLocation()));
1494     Atomic.ParameterMapping.emplace(TempArgs,  OccurringIndices.count());
1495   }
1496   SourceLocation InstLocBegin =
1497       ArgsAsWritten->arguments().empty()
1498           ? ArgsAsWritten->getLAngleLoc()
1499           : ArgsAsWritten->arguments().front().getSourceRange().getBegin();
1500   SourceLocation InstLocEnd =
1501       ArgsAsWritten->arguments().empty()
1502           ? ArgsAsWritten->getRAngleLoc()
1503           : ArgsAsWritten->arguments().front().getSourceRange().getEnd();
1504   Sema::InstantiatingTemplate Inst(
1505       S, InstLocBegin,
1506       Sema::InstantiatingTemplate::ParameterMappingSubstitution{},
1507       Atomic.ConstraintDecl, {InstLocBegin, InstLocEnd});
1508   if (Inst.isInvalid())
1509     return true;
1510   if (S.SubstTemplateArguments(*Atomic.ParameterMapping, MLTAL, SubstArgs))
1511     return true;
1512 
1513   TemplateArgumentLoc *TempArgs =
1514       new (S.Context) TemplateArgumentLoc[SubstArgs.size()];
1515   std::copy(SubstArgs.arguments().begin(), SubstArgs.arguments().end(),
1516             TempArgs);
1517   Atomic.ParameterMapping.emplace(TempArgs, SubstArgs.size());
1518   return false;
1519 }
1520 
1521 static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N,
1522                                         const ConceptSpecializationExpr *CSE) {
1523   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
1524       CSE->getNamedConcept(), CSE->getNamedConcept()->getLexicalDeclContext(),
1525       /*Final=*/false, CSE->getTemplateArguments(),
1526       /*RelativeToPrimary=*/true,
1527       /*Pattern=*/nullptr,
1528       /*ForConstraintInstantiation=*/true);
1529 
1530   return substituteParameterMappings(S, N, CSE->getNamedConcept(), MLTAL,
1531                                      CSE->getTemplateArgsAsWritten());
1532 }
1533 
1534 NormalizedConstraint::NormalizedConstraint(ASTContext &C,
1535                                            NormalizedConstraint LHS,
1536                                            NormalizedConstraint RHS,
1537                                            CompoundConstraintKind Kind)
1538     : Constraint{CompoundConstraint{
1539           new(C) NormalizedConstraintPair{std::move(LHS), std::move(RHS)},
1540           Kind}} {}
1541 
1542 NormalizedConstraint::NormalizedConstraint(ASTContext &C,
1543                                            const NormalizedConstraint &Other) {
1544   if (Other.isAtomic()) {
1545     Constraint = new (C) AtomicConstraint(*Other.getAtomicConstraint());
1546   } else if (Other.isFoldExpanded()) {
1547     Constraint = new (C) FoldExpandedConstraint(
1548         Other.getFoldExpandedConstraint()->Kind,
1549         NormalizedConstraint(C, Other.getFoldExpandedConstraint()->Constraint),
1550         Other.getFoldExpandedConstraint()->Pattern);
1551   } else {
1552     Constraint = CompoundConstraint(
1553         new (C)
1554             NormalizedConstraintPair{NormalizedConstraint(C, Other.getLHS()),
1555                                      NormalizedConstraint(C, Other.getRHS())},
1556         Other.getCompoundKind());
1557   }
1558 }
1559 
1560 NormalizedConstraint &NormalizedConstraint::getLHS() const {
1561   assert(isCompound() && "getLHS called on a non-compound constraint.");
1562   return cast<CompoundConstraint>(Constraint).getPointer()->LHS;
1563 }
1564 
1565 NormalizedConstraint &NormalizedConstraint::getRHS() const {
1566   assert(isCompound() && "getRHS called on a non-compound constraint.");
1567   return cast<CompoundConstraint>(Constraint).getPointer()->RHS;
1568 }
1569 
1570 std::optional<NormalizedConstraint>
1571 NormalizedConstraint::fromConstraintExprs(Sema &S, NamedDecl *D,
1572                                           ArrayRef<const Expr *> E) {
1573   assert(E.size() != 0);
1574   auto Conjunction = fromConstraintExpr(S, D, E[0]);
1575   if (!Conjunction)
1576     return std::nullopt;
1577   for (unsigned I = 1; I < E.size(); ++I) {
1578     auto Next = fromConstraintExpr(S, D, E[I]);
1579     if (!Next)
1580       return std::nullopt;
1581     *Conjunction = NormalizedConstraint(S.Context, std::move(*Conjunction),
1582                                         std::move(*Next), CCK_Conjunction);
1583   }
1584   return Conjunction;
1585 }
1586 
1587 std::optional<NormalizedConstraint>
1588 NormalizedConstraint::fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E) {
1589   assert(E != nullptr);
1590 
1591   // C++ [temp.constr.normal]p1.1
1592   // [...]
1593   // - The normal form of an expression (E) is the normal form of E.
1594   // [...]
1595   E = E->IgnoreParenImpCasts();
1596 
1597   // C++2a [temp.param]p4:
1598   //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1599   // Fold expression is considered atomic constraints per current wording.
1600   // See http://cplusplus.github.io/concepts-ts/ts-active.html#28
1601 
1602   if (LogicalBinOp BO = E) {
1603     auto LHS = fromConstraintExpr(S, D, BO.getLHS());
1604     if (!LHS)
1605       return std::nullopt;
1606     auto RHS = fromConstraintExpr(S, D, BO.getRHS());
1607     if (!RHS)
1608       return std::nullopt;
1609 
1610     return NormalizedConstraint(S.Context, std::move(*LHS), std::move(*RHS),
1611                                 BO.isAnd() ? CCK_Conjunction : CCK_Disjunction);
1612   } else if (auto *CSE = dyn_cast<const ConceptSpecializationExpr>(E)) {
1613     const NormalizedConstraint *SubNF;
1614     {
1615       Sema::InstantiatingTemplate Inst(
1616           S, CSE->getExprLoc(),
1617           Sema::InstantiatingTemplate::ConstraintNormalization{}, D,
1618           CSE->getSourceRange());
1619       if (Inst.isInvalid())
1620         return std::nullopt;
1621       // C++ [temp.constr.normal]p1.1
1622       // [...]
1623       // The normal form of an id-expression of the form C<A1, A2, ..., AN>,
1624       // where C names a concept, is the normal form of the
1625       // constraint-expression of C, after substituting A1, A2, ..., AN for C’s
1626       // respective template parameters in the parameter mappings in each atomic
1627       // constraint. If any such substitution results in an invalid type or
1628       // expression, the program is ill-formed; no diagnostic is required.
1629       // [...]
1630       ConceptDecl *CD = CSE->getNamedConcept();
1631       SubNF = S.getNormalizedAssociatedConstraints(CD,
1632                                                    {CD->getConstraintExpr()});
1633       if (!SubNF)
1634         return std::nullopt;
1635     }
1636 
1637     std::optional<NormalizedConstraint> New;
1638     New.emplace(S.Context, *SubNF);
1639 
1640     if (substituteParameterMappings(S, *New, CSE))
1641       return std::nullopt;
1642 
1643     return New;
1644   } else if (auto *FE = dyn_cast<const CXXFoldExpr>(E);
1645              FE && S.getLangOpts().CPlusPlus26 &&
1646              (FE->getOperator() == BinaryOperatorKind::BO_LAnd ||
1647               FE->getOperator() == BinaryOperatorKind::BO_LOr)) {
1648 
1649     // Normalize fold expressions in C++26.
1650 
1651     FoldExpandedConstraint::FoldOperatorKind Kind =
1652         FE->getOperator() == BinaryOperatorKind::BO_LAnd
1653             ? FoldExpandedConstraint::FoldOperatorKind::And
1654             : FoldExpandedConstraint::FoldOperatorKind::Or;
1655 
1656     if (FE->getInit()) {
1657       auto LHS = fromConstraintExpr(S, D, FE->getLHS());
1658       auto RHS = fromConstraintExpr(S, D, FE->getRHS());
1659       if (!LHS || !RHS)
1660         return std::nullopt;
1661 
1662       if (FE->isRightFold())
1663         RHS = NormalizedConstraint{new (S.Context) FoldExpandedConstraint{
1664             Kind, std::move(*RHS), FE->getPattern()}};
1665       else
1666         LHS = NormalizedConstraint{new (S.Context) FoldExpandedConstraint{
1667             Kind, std::move(*LHS), FE->getPattern()}};
1668 
1669       return NormalizedConstraint(
1670           S.Context, std::move(*LHS), std::move(*RHS),
1671           FE->getOperator() == BinaryOperatorKind::BO_LAnd ? CCK_Conjunction
1672                                                            : CCK_Disjunction);
1673     }
1674     auto Sub = fromConstraintExpr(S, D, FE->getPattern());
1675     if (!Sub)
1676       return std::nullopt;
1677     return NormalizedConstraint{new (S.Context) FoldExpandedConstraint{
1678         Kind, std::move(*Sub), FE->getPattern()}};
1679   }
1680 
1681   return NormalizedConstraint{new (S.Context) AtomicConstraint(E, D)};
1682 }
1683 
1684 bool FoldExpandedConstraint::AreCompatibleForSubsumption(
1685     const FoldExpandedConstraint &A, const FoldExpandedConstraint &B) {
1686 
1687   // [C++26] [temp.constr.fold]
1688   // Two fold expanded constraints are compatible for subsumption
1689   // if their respective constraints both contain an equivalent unexpanded pack.
1690 
1691   llvm::SmallVector<UnexpandedParameterPack> APacks, BPacks;
1692   Sema::collectUnexpandedParameterPacks(const_cast<Expr *>(A.Pattern), APacks);
1693   Sema::collectUnexpandedParameterPacks(const_cast<Expr *>(B.Pattern), BPacks);
1694 
1695   for (const UnexpandedParameterPack &APack : APacks) {
1696     std::pair<unsigned, unsigned> DepthAndIndex = getDepthAndIndex(APack);
1697     auto it = llvm::find_if(BPacks, [&](const UnexpandedParameterPack &BPack) {
1698       return getDepthAndIndex(BPack) == DepthAndIndex;
1699     });
1700     if (it != BPacks.end())
1701       return true;
1702   }
1703   return false;
1704 }
1705 
1706 NormalForm clang::makeCNF(const NormalizedConstraint &Normalized) {
1707   if (Normalized.isAtomic())
1708     return {{Normalized.getAtomicConstraint()}};
1709 
1710   else if (Normalized.isFoldExpanded())
1711     return {{Normalized.getFoldExpandedConstraint()}};
1712 
1713   NormalForm LCNF = makeCNF(Normalized.getLHS());
1714   NormalForm RCNF = makeCNF(Normalized.getRHS());
1715   if (Normalized.getCompoundKind() == NormalizedConstraint::CCK_Conjunction) {
1716     LCNF.reserve(LCNF.size() + RCNF.size());
1717     while (!RCNF.empty())
1718       LCNF.push_back(RCNF.pop_back_val());
1719     return LCNF;
1720   }
1721 
1722   // Disjunction
1723   NormalForm Res;
1724   Res.reserve(LCNF.size() * RCNF.size());
1725   for (auto &LDisjunction : LCNF)
1726     for (auto &RDisjunction : RCNF) {
1727       NormalForm::value_type Combined;
1728       Combined.reserve(LDisjunction.size() + RDisjunction.size());
1729       std::copy(LDisjunction.begin(), LDisjunction.end(),
1730                 std::back_inserter(Combined));
1731       std::copy(RDisjunction.begin(), RDisjunction.end(),
1732                 std::back_inserter(Combined));
1733       Res.emplace_back(Combined);
1734     }
1735   return Res;
1736 }
1737 
1738 NormalForm clang::makeDNF(const NormalizedConstraint &Normalized) {
1739   if (Normalized.isAtomic())
1740     return {{Normalized.getAtomicConstraint()}};
1741 
1742   else if (Normalized.isFoldExpanded())
1743     return {{Normalized.getFoldExpandedConstraint()}};
1744 
1745   NormalForm LDNF = makeDNF(Normalized.getLHS());
1746   NormalForm RDNF = makeDNF(Normalized.getRHS());
1747   if (Normalized.getCompoundKind() == NormalizedConstraint::CCK_Disjunction) {
1748     LDNF.reserve(LDNF.size() + RDNF.size());
1749     while (!RDNF.empty())
1750       LDNF.push_back(RDNF.pop_back_val());
1751     return LDNF;
1752   }
1753 
1754   // Conjunction
1755   NormalForm Res;
1756   Res.reserve(LDNF.size() * RDNF.size());
1757   for (auto &LConjunction : LDNF) {
1758     for (auto &RConjunction : RDNF) {
1759       NormalForm::value_type Combined;
1760       Combined.reserve(LConjunction.size() + RConjunction.size());
1761       std::copy(LConjunction.begin(), LConjunction.end(),
1762                 std::back_inserter(Combined));
1763       std::copy(RConjunction.begin(), RConjunction.end(),
1764                 std::back_inserter(Combined));
1765       Res.emplace_back(Combined);
1766     }
1767   }
1768   return Res;
1769 }
1770 
1771 bool Sema::IsAtLeastAsConstrained(NamedDecl *D1,
1772                                   MutableArrayRef<const Expr *> AC1,
1773                                   NamedDecl *D2,
1774                                   MutableArrayRef<const Expr *> AC2,
1775                                   bool &Result) {
1776   if (const auto *FD1 = dyn_cast<FunctionDecl>(D1)) {
1777     auto IsExpectedEntity = [](const FunctionDecl *FD) {
1778       FunctionDecl::TemplatedKind Kind = FD->getTemplatedKind();
1779       return Kind == FunctionDecl::TK_NonTemplate ||
1780              Kind == FunctionDecl::TK_FunctionTemplate;
1781     };
1782     const auto *FD2 = dyn_cast<FunctionDecl>(D2);
1783     (void)IsExpectedEntity;
1784     (void)FD1;
1785     (void)FD2;
1786     assert(IsExpectedEntity(FD1) && FD2 && IsExpectedEntity(FD2) &&
1787            "use non-instantiated function declaration for constraints partial "
1788            "ordering");
1789   }
1790 
1791   if (AC1.empty()) {
1792     Result = AC2.empty();
1793     return false;
1794   }
1795   if (AC2.empty()) {
1796     // TD1 has associated constraints and TD2 does not.
1797     Result = true;
1798     return false;
1799   }
1800 
1801   std::pair<NamedDecl *, NamedDecl *> Key{D1, D2};
1802   auto CacheEntry = SubsumptionCache.find(Key);
1803   if (CacheEntry != SubsumptionCache.end()) {
1804     Result = CacheEntry->second;
1805     return false;
1806   }
1807 
1808   unsigned Depth1 = CalculateTemplateDepthForConstraints(*this, D1, true);
1809   unsigned Depth2 = CalculateTemplateDepthForConstraints(*this, D2, true);
1810 
1811   for (size_t I = 0; I != AC1.size() && I != AC2.size(); ++I) {
1812     if (Depth2 > Depth1) {
1813       AC1[I] = AdjustConstraintDepth(*this, Depth2 - Depth1)
1814                    .TransformExpr(const_cast<Expr *>(AC1[I]))
1815                    .get();
1816     } else if (Depth1 > Depth2) {
1817       AC2[I] = AdjustConstraintDepth(*this, Depth1 - Depth2)
1818                    .TransformExpr(const_cast<Expr *>(AC2[I]))
1819                    .get();
1820     }
1821   }
1822 
1823   if (clang::subsumes(
1824           *this, D1, AC1, D2, AC2, Result,
1825           [this](const AtomicConstraint &A, const AtomicConstraint &B) {
1826             return A.subsumes(Context, B);
1827           }))
1828     return true;
1829   SubsumptionCache.try_emplace(Key, Result);
1830   return false;
1831 }
1832 
1833 bool Sema::MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
1834     ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2) {
1835   if (isSFINAEContext())
1836     // No need to work here because our notes would be discarded.
1837     return false;
1838 
1839   if (AC1.empty() || AC2.empty())
1840     return false;
1841 
1842   auto NormalExprEvaluator =
1843       [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
1844         return A.subsumes(Context, B);
1845       };
1846 
1847   const Expr *AmbiguousAtomic1 = nullptr, *AmbiguousAtomic2 = nullptr;
1848   auto IdenticalExprEvaluator =
1849       [&] (const AtomicConstraint &A, const AtomicConstraint &B) {
1850         if (!A.hasMatchingParameterMapping(Context, B))
1851           return false;
1852         const Expr *EA = A.ConstraintExpr, *EB = B.ConstraintExpr;
1853         if (EA == EB)
1854           return true;
1855 
1856         // Not the same source level expression - are the expressions
1857         // identical?
1858         llvm::FoldingSetNodeID IDA, IDB;
1859         EA->Profile(IDA, Context, /*Canonical=*/true);
1860         EB->Profile(IDB, Context, /*Canonical=*/true);
1861         if (IDA != IDB)
1862           return false;
1863 
1864         AmbiguousAtomic1 = EA;
1865         AmbiguousAtomic2 = EB;
1866         return true;
1867       };
1868 
1869   {
1870     // The subsumption checks might cause diagnostics
1871     SFINAETrap Trap(*this);
1872     auto *Normalized1 = getNormalizedAssociatedConstraints(D1, AC1);
1873     if (!Normalized1)
1874       return false;
1875     const NormalForm DNF1 = makeDNF(*Normalized1);
1876     const NormalForm CNF1 = makeCNF(*Normalized1);
1877 
1878     auto *Normalized2 = getNormalizedAssociatedConstraints(D2, AC2);
1879     if (!Normalized2)
1880       return false;
1881     const NormalForm DNF2 = makeDNF(*Normalized2);
1882     const NormalForm CNF2 = makeCNF(*Normalized2);
1883 
1884     bool Is1AtLeastAs2Normally =
1885         clang::subsumes(DNF1, CNF2, NormalExprEvaluator);
1886     bool Is2AtLeastAs1Normally =
1887         clang::subsumes(DNF2, CNF1, NormalExprEvaluator);
1888     bool Is1AtLeastAs2 = clang::subsumes(DNF1, CNF2, IdenticalExprEvaluator);
1889     bool Is2AtLeastAs1 = clang::subsumes(DNF2, CNF1, IdenticalExprEvaluator);
1890     if (Is1AtLeastAs2 == Is1AtLeastAs2Normally &&
1891         Is2AtLeastAs1 == Is2AtLeastAs1Normally)
1892       // Same result - no ambiguity was caused by identical atomic expressions.
1893       return false;
1894   }
1895 
1896   // A different result! Some ambiguous atomic constraint(s) caused a difference
1897   assert(AmbiguousAtomic1 && AmbiguousAtomic2);
1898 
1899   Diag(AmbiguousAtomic1->getBeginLoc(), diag::note_ambiguous_atomic_constraints)
1900       << AmbiguousAtomic1->getSourceRange();
1901   Diag(AmbiguousAtomic2->getBeginLoc(),
1902        diag::note_ambiguous_atomic_constraints_similar_expression)
1903       << AmbiguousAtomic2->getSourceRange();
1904   return true;
1905 }
1906 
1907 concepts::ExprRequirement::ExprRequirement(
1908     Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
1909     ReturnTypeRequirement Req, SatisfactionStatus Status,
1910     ConceptSpecializationExpr *SubstitutedConstraintExpr) :
1911     Requirement(IsSimple ? RK_Simple : RK_Compound, Status == SS_Dependent,
1912                 Status == SS_Dependent &&
1913                 (E->containsUnexpandedParameterPack() ||
1914                  Req.containsUnexpandedParameterPack()),
1915                 Status == SS_Satisfied), Value(E), NoexceptLoc(NoexceptLoc),
1916     TypeReq(Req), SubstitutedConstraintExpr(SubstitutedConstraintExpr),
1917     Status(Status) {
1918   assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
1919          "Simple requirement must not have a return type requirement or a "
1920          "noexcept specification");
1921   assert((Status > SS_TypeRequirementSubstitutionFailure && Req.isTypeConstraint()) ==
1922          (SubstitutedConstraintExpr != nullptr));
1923 }
1924 
1925 concepts::ExprRequirement::ExprRequirement(
1926     SubstitutionDiagnostic *ExprSubstDiag, bool IsSimple,
1927     SourceLocation NoexceptLoc, ReturnTypeRequirement Req) :
1928     Requirement(IsSimple ? RK_Simple : RK_Compound, Req.isDependent(),
1929                 Req.containsUnexpandedParameterPack(), /*IsSatisfied=*/false),
1930     Value(ExprSubstDiag), NoexceptLoc(NoexceptLoc), TypeReq(Req),
1931     Status(SS_ExprSubstitutionFailure) {
1932   assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
1933          "Simple requirement must not have a return type requirement or a "
1934          "noexcept specification");
1935 }
1936 
1937 concepts::ExprRequirement::ReturnTypeRequirement::
1938 ReturnTypeRequirement(TemplateParameterList *TPL) :
1939     TypeConstraintInfo(TPL, false) {
1940   assert(TPL->size() == 1);
1941   const TypeConstraint *TC =
1942       cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint();
1943   assert(TC &&
1944          "TPL must have a template type parameter with a type constraint");
1945   auto *Constraint =
1946       cast<ConceptSpecializationExpr>(TC->getImmediatelyDeclaredConstraint());
1947   bool Dependent =
1948       Constraint->getTemplateArgsAsWritten() &&
1949       TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
1950           Constraint->getTemplateArgsAsWritten()->arguments().drop_front(1));
1951   TypeConstraintInfo.setInt(Dependent ? true : false);
1952 }
1953 
1954 concepts::TypeRequirement::TypeRequirement(TypeSourceInfo *T) :
1955     Requirement(RK_Type, T->getType()->isInstantiationDependentType(),
1956                 T->getType()->containsUnexpandedParameterPack(),
1957                 // We reach this ctor with either dependent types (in which
1958                 // IsSatisfied doesn't matter) or with non-dependent type in
1959                 // which the existence of the type indicates satisfaction.
1960                 /*IsSatisfied=*/true),
1961     Value(T),
1962     Status(T->getType()->isInstantiationDependentType() ? SS_Dependent
1963                                                         : SS_Satisfied) {}
1964 
1965 NormalizedConstraint::CompoundConstraintKind
1966 NormalizedConstraint::getCompoundKind() const {
1967   assert(isCompound() && "getCompoundKind on a non-compound constraint..");
1968   return cast<CompoundConstraint>(Constraint).getInt();
1969 }
1970 
1971 AtomicConstraint *NormalizedConstraint::getAtomicConstraint() const {
1972   assert(isAtomic() && "getAtomicConstraint called on non-atomic constraint.");
1973   return cast<AtomicConstraint *>(Constraint);
1974 }
1975 
1976 FoldExpandedConstraint *
1977 NormalizedConstraint::getFoldExpandedConstraint() const {
1978   assert(isFoldExpanded() &&
1979          "getFoldExpandedConstraint called on non-fold-expanded constraint.");
1980   return cast<FoldExpandedConstraint *>(Constraint);
1981 }
1982