xref: /freebsd-src/contrib/llvm-project/clang/lib/Sema/SemaConcept.cpp (revision feb5b0c76f9c7b510583b0489918300cbf966e0f)
1a7dea167SDimitry Andric //===-- SemaConcept.cpp - Semantic Analysis for Constraints and Concepts --===//
2a7dea167SDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a7dea167SDimitry Andric //
7a7dea167SDimitry Andric //===----------------------------------------------------------------------===//
8a7dea167SDimitry Andric //
9a7dea167SDimitry Andric //  This file implements semantic analysis for C++ constraints and concepts.
10a7dea167SDimitry Andric //
11a7dea167SDimitry Andric //===----------------------------------------------------------------------===//
12a7dea167SDimitry Andric 
13480093f4SDimitry Andric #include "clang/Sema/SemaConcept.h"
1406c3fb27SDimitry Andric #include "TreeTransform.h"
15bdd1243dSDimitry Andric #include "clang/AST/ASTLambda.h"
16*feb5b0c7SDimitry Andric #include "clang/AST/DeclCXX.h"
1755e4f9d5SDimitry Andric #include "clang/AST/ExprConcepts.h"
18480093f4SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
19480093f4SDimitry Andric #include "clang/Basic/OperatorPrecedence.h"
2006c3fb27SDimitry Andric #include "clang/Sema/EnterExpressionEvaluationContext.h"
2106c3fb27SDimitry Andric #include "clang/Sema/Initialization.h"
2206c3fb27SDimitry Andric #include "clang/Sema/Overload.h"
23*feb5b0c7SDimitry Andric #include "clang/Sema/ScopeInfo.h"
2406c3fb27SDimitry Andric #include "clang/Sema/Sema.h"
2506c3fb27SDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
2606c3fb27SDimitry Andric #include "clang/Sema/SemaInternal.h"
2706c3fb27SDimitry Andric #include "clang/Sema/Template.h"
2806c3fb27SDimitry Andric #include "clang/Sema/TemplateDeduction.h"
29480093f4SDimitry Andric #include "llvm/ADT/DenseMap.h"
30480093f4SDimitry Andric #include "llvm/ADT/PointerUnion.h"
31fe6060f1SDimitry Andric #include "llvm/ADT/StringExtras.h"
32bdd1243dSDimitry Andric #include <optional>
33fe6060f1SDimitry Andric 
34a7dea167SDimitry Andric using namespace clang;
35a7dea167SDimitry Andric using namespace sema;
36a7dea167SDimitry Andric 
375ffd83dbSDimitry Andric namespace {
385ffd83dbSDimitry Andric class LogicalBinOp {
39bdd1243dSDimitry Andric   SourceLocation Loc;
405ffd83dbSDimitry Andric   OverloadedOperatorKind Op = OO_None;
415ffd83dbSDimitry Andric   const Expr *LHS = nullptr;
425ffd83dbSDimitry Andric   const Expr *RHS = nullptr;
435ffd83dbSDimitry Andric 
445ffd83dbSDimitry Andric public:
455ffd83dbSDimitry Andric   LogicalBinOp(const Expr *E) {
465ffd83dbSDimitry Andric     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
475ffd83dbSDimitry Andric       Op = BinaryOperator::getOverloadedOperator(BO->getOpcode());
485ffd83dbSDimitry Andric       LHS = BO->getLHS();
495ffd83dbSDimitry Andric       RHS = BO->getRHS();
50bdd1243dSDimitry Andric       Loc = BO->getExprLoc();
515ffd83dbSDimitry Andric     } else if (auto *OO = dyn_cast<CXXOperatorCallExpr>(E)) {
52fe6060f1SDimitry Andric       // If OO is not || or && it might not have exactly 2 arguments.
53fe6060f1SDimitry Andric       if (OO->getNumArgs() == 2) {
545ffd83dbSDimitry Andric         Op = OO->getOperator();
555ffd83dbSDimitry Andric         LHS = OO->getArg(0);
565ffd83dbSDimitry Andric         RHS = OO->getArg(1);
57bdd1243dSDimitry Andric         Loc = OO->getOperatorLoc();
585ffd83dbSDimitry Andric       }
595ffd83dbSDimitry Andric     }
60fe6060f1SDimitry Andric   }
615ffd83dbSDimitry Andric 
625ffd83dbSDimitry Andric   bool isAnd() const { return Op == OO_AmpAmp; }
635ffd83dbSDimitry Andric   bool isOr() const { return Op == OO_PipePipe; }
645ffd83dbSDimitry Andric   explicit operator bool() const { return isAnd() || isOr(); }
655ffd83dbSDimitry Andric 
665ffd83dbSDimitry Andric   const Expr *getLHS() const { return LHS; }
675ffd83dbSDimitry Andric   const Expr *getRHS() const { return RHS; }
68bdd1243dSDimitry Andric 
69bdd1243dSDimitry Andric   ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS) const {
70bdd1243dSDimitry Andric     return recreateBinOp(SemaRef, LHS, const_cast<Expr *>(getRHS()));
71bdd1243dSDimitry Andric   }
72bdd1243dSDimitry Andric 
73bdd1243dSDimitry Andric   ExprResult recreateBinOp(Sema &SemaRef, ExprResult LHS,
74bdd1243dSDimitry Andric                            ExprResult RHS) const {
75bdd1243dSDimitry Andric     assert((isAnd() || isOr()) && "Not the right kind of op?");
76bdd1243dSDimitry Andric     assert((!LHS.isInvalid() && !RHS.isInvalid()) && "not good expressions?");
77bdd1243dSDimitry Andric 
78bdd1243dSDimitry Andric     if (!LHS.isUsable() || !RHS.isUsable())
79bdd1243dSDimitry Andric       return ExprEmpty();
80bdd1243dSDimitry Andric 
81bdd1243dSDimitry Andric     // We should just be able to 'normalize' these to the builtin Binary
82bdd1243dSDimitry Andric     // Operator, since that is how they are evaluated in constriant checks.
83bdd1243dSDimitry Andric     return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
84bdd1243dSDimitry Andric                                   BinaryOperator::getOverloadedOpcode(Op),
85bdd1243dSDimitry Andric                                   SemaRef.Context.BoolTy, VK_PRValue,
86bdd1243dSDimitry Andric                                   OK_Ordinary, Loc, FPOptionsOverride{});
87bdd1243dSDimitry Andric   }
885ffd83dbSDimitry Andric };
895ffd83dbSDimitry Andric }
905ffd83dbSDimitry Andric 
915ffd83dbSDimitry Andric bool Sema::CheckConstraintExpression(const Expr *ConstraintExpression,
925ffd83dbSDimitry Andric                                      Token NextToken, bool *PossibleNonPrimary,
93480093f4SDimitry Andric                                      bool IsTrailingRequiresClause) {
94a7dea167SDimitry Andric   // C++2a [temp.constr.atomic]p1
95a7dea167SDimitry Andric   // ..E shall be a constant expression of type bool.
96a7dea167SDimitry Andric 
97a7dea167SDimitry Andric   ConstraintExpression = ConstraintExpression->IgnoreParenImpCasts();
98a7dea167SDimitry Andric 
995ffd83dbSDimitry Andric   if (LogicalBinOp BO = ConstraintExpression) {
1005ffd83dbSDimitry Andric     return CheckConstraintExpression(BO.getLHS(), NextToken,
101480093f4SDimitry Andric                                      PossibleNonPrimary) &&
1025ffd83dbSDimitry Andric            CheckConstraintExpression(BO.getRHS(), NextToken,
103480093f4SDimitry Andric                                      PossibleNonPrimary);
104a7dea167SDimitry Andric   } else if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpression))
105480093f4SDimitry Andric     return CheckConstraintExpression(C->getSubExpr(), NextToken,
106480093f4SDimitry Andric                                      PossibleNonPrimary);
107a7dea167SDimitry Andric 
108a7dea167SDimitry Andric   QualType Type = ConstraintExpression->getType();
109480093f4SDimitry Andric 
110480093f4SDimitry Andric   auto CheckForNonPrimary = [&] {
11106c3fb27SDimitry Andric     if (!PossibleNonPrimary)
11206c3fb27SDimitry Andric       return;
11306c3fb27SDimitry Andric 
114480093f4SDimitry Andric     *PossibleNonPrimary =
115480093f4SDimitry Andric         // We have the following case:
116480093f4SDimitry Andric         // template<typename> requires func(0) struct S { };
117480093f4SDimitry Andric         // The user probably isn't aware of the parentheses required around
118480093f4SDimitry Andric         // the function call, and we're only going to parse 'func' as the
119480093f4SDimitry Andric         // primary-expression, and complain that it is of non-bool type.
12006c3fb27SDimitry Andric         //
12106c3fb27SDimitry Andric         // However, if we're in a lambda, this might also be:
12206c3fb27SDimitry Andric         // []<typename> requires var () {};
12306c3fb27SDimitry Andric         // Which also looks like a function call due to the lambda parentheses,
12406c3fb27SDimitry Andric         // but unlike the first case, isn't an error, so this check is skipped.
125480093f4SDimitry Andric         (NextToken.is(tok::l_paren) &&
126480093f4SDimitry Andric          (IsTrailingRequiresClause ||
127480093f4SDimitry Andric           (Type->isDependentType() &&
12806c3fb27SDimitry Andric            isa<UnresolvedLookupExpr>(ConstraintExpression) &&
12906c3fb27SDimitry Andric            !dyn_cast_if_present<LambdaScopeInfo>(getCurFunction())) ||
130480093f4SDimitry Andric           Type->isFunctionType() ||
131480093f4SDimitry Andric           Type->isSpecificBuiltinType(BuiltinType::Overload))) ||
132480093f4SDimitry Andric         // We have the following case:
133480093f4SDimitry Andric         // template<typename T> requires size_<T> == 0 struct S { };
134480093f4SDimitry Andric         // The user probably isn't aware of the parentheses required around
135480093f4SDimitry Andric         // the binary operator, and we're only going to parse 'func' as the
136480093f4SDimitry Andric         // first operand, and complain that it is of non-bool type.
137480093f4SDimitry Andric         getBinOpPrecedence(NextToken.getKind(),
138480093f4SDimitry Andric                            /*GreaterThanIsOperator=*/true,
139480093f4SDimitry Andric                            getLangOpts().CPlusPlus11) > prec::LogicalAnd;
140480093f4SDimitry Andric   };
141480093f4SDimitry Andric 
142480093f4SDimitry Andric   // An atomic constraint!
143480093f4SDimitry Andric   if (ConstraintExpression->isTypeDependent()) {
144480093f4SDimitry Andric     CheckForNonPrimary();
145480093f4SDimitry Andric     return true;
146480093f4SDimitry Andric   }
147480093f4SDimitry Andric 
148a7dea167SDimitry Andric   if (!Context.hasSameUnqualifiedType(Type, Context.BoolTy)) {
149a7dea167SDimitry Andric     Diag(ConstraintExpression->getExprLoc(),
150a7dea167SDimitry Andric          diag::err_non_bool_atomic_constraint) << Type
151a7dea167SDimitry Andric         << ConstraintExpression->getSourceRange();
152480093f4SDimitry Andric     CheckForNonPrimary();
153a7dea167SDimitry Andric     return false;
154a7dea167SDimitry Andric   }
155480093f4SDimitry Andric 
156480093f4SDimitry Andric   if (PossibleNonPrimary)
157480093f4SDimitry Andric       *PossibleNonPrimary = false;
158a7dea167SDimitry Andric   return true;
159a7dea167SDimitry Andric }
160a7dea167SDimitry Andric 
161bdd1243dSDimitry Andric namespace {
162bdd1243dSDimitry Andric struct SatisfactionStackRAII {
163bdd1243dSDimitry Andric   Sema &SemaRef;
1641ac55f4cSDimitry Andric   bool Inserted = false;
1651ac55f4cSDimitry Andric   SatisfactionStackRAII(Sema &SemaRef, const NamedDecl *ND,
16606c3fb27SDimitry Andric                         const llvm::FoldingSetNodeID &FSNID)
167bdd1243dSDimitry Andric       : SemaRef(SemaRef) {
1681ac55f4cSDimitry Andric       if (ND) {
1691ac55f4cSDimitry Andric       SemaRef.PushSatisfactionStackEntry(ND, FSNID);
1701ac55f4cSDimitry Andric       Inserted = true;
171bdd1243dSDimitry Andric       }
1721ac55f4cSDimitry Andric   }
1731ac55f4cSDimitry Andric   ~SatisfactionStackRAII() {
1741ac55f4cSDimitry Andric         if (Inserted)
1751ac55f4cSDimitry Andric           SemaRef.PopSatisfactionStackEntry();
1761ac55f4cSDimitry Andric   }
177bdd1243dSDimitry Andric };
178bdd1243dSDimitry Andric } // namespace
179bdd1243dSDimitry Andric 
180480093f4SDimitry Andric template <typename AtomicEvaluator>
181bdd1243dSDimitry Andric static ExprResult
182480093f4SDimitry Andric calculateConstraintSatisfaction(Sema &S, const Expr *ConstraintExpr,
183480093f4SDimitry Andric                                 ConstraintSatisfaction &Satisfaction,
184480093f4SDimitry Andric                                 AtomicEvaluator &&Evaluator) {
185a7dea167SDimitry Andric   ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
186a7dea167SDimitry Andric 
1875ffd83dbSDimitry Andric   if (LogicalBinOp BO = ConstraintExpr) {
188bdd1243dSDimitry Andric     ExprResult LHSRes = calculateConstraintSatisfaction(
189bdd1243dSDimitry Andric         S, BO.getLHS(), Satisfaction, Evaluator);
190bdd1243dSDimitry Andric 
191bdd1243dSDimitry Andric     if (LHSRes.isInvalid())
192bdd1243dSDimitry Andric       return ExprError();
193480093f4SDimitry Andric 
194480093f4SDimitry Andric     bool IsLHSSatisfied = Satisfaction.IsSatisfied;
195480093f4SDimitry Andric 
1965ffd83dbSDimitry Andric     if (BO.isOr() && IsLHSSatisfied)
197480093f4SDimitry Andric       // [temp.constr.op] p3
198480093f4SDimitry Andric       //    A disjunction is a constraint taking two operands. To determine if
199480093f4SDimitry Andric       //    a disjunction is satisfied, the satisfaction of the first operand
200480093f4SDimitry Andric       //    is checked. If that is satisfied, the disjunction is satisfied.
201480093f4SDimitry Andric       //    Otherwise, the disjunction is satisfied if and only if the second
202480093f4SDimitry Andric       //    operand is satisfied.
203bdd1243dSDimitry Andric       // LHS is instantiated while RHS is not. Skip creating invalid BinaryOp.
204bdd1243dSDimitry Andric       return LHSRes;
205480093f4SDimitry Andric 
2065ffd83dbSDimitry Andric     if (BO.isAnd() && !IsLHSSatisfied)
207480093f4SDimitry Andric       // [temp.constr.op] p2
208480093f4SDimitry Andric       //    A conjunction is a constraint taking two operands. To determine if
209480093f4SDimitry Andric       //    a conjunction is satisfied, the satisfaction of the first operand
210480093f4SDimitry Andric       //    is checked. If that is not satisfied, the conjunction is not
211480093f4SDimitry Andric       //    satisfied. Otherwise, the conjunction is satisfied if and only if
212480093f4SDimitry Andric       //    the second operand is satisfied.
213bdd1243dSDimitry Andric       // LHS is instantiated while RHS is not. Skip creating invalid BinaryOp.
214bdd1243dSDimitry Andric       return LHSRes;
215480093f4SDimitry Andric 
216bdd1243dSDimitry Andric     ExprResult RHSRes = calculateConstraintSatisfaction(
2175ffd83dbSDimitry Andric         S, BO.getRHS(), Satisfaction, std::forward<AtomicEvaluator>(Evaluator));
218bdd1243dSDimitry Andric     if (RHSRes.isInvalid())
219bdd1243dSDimitry Andric       return ExprError();
220bdd1243dSDimitry Andric 
221bdd1243dSDimitry Andric     return BO.recreateBinOp(S, LHSRes, RHSRes);
222bdd1243dSDimitry Andric   }
223bdd1243dSDimitry Andric 
224bdd1243dSDimitry Andric   if (auto *C = dyn_cast<ExprWithCleanups>(ConstraintExpr)) {
225bdd1243dSDimitry Andric     // These aren't evaluated, so we don't care about cleanups, so we can just
226bdd1243dSDimitry Andric     // evaluate these as if the cleanups didn't exist.
227bdd1243dSDimitry Andric     return calculateConstraintSatisfaction(
228bdd1243dSDimitry Andric         S, C->getSubExpr(), Satisfaction,
229480093f4SDimitry Andric         std::forward<AtomicEvaluator>(Evaluator));
2305ffd83dbSDimitry Andric   }
231480093f4SDimitry Andric 
232480093f4SDimitry Andric   // An atomic constraint expression
233480093f4SDimitry Andric   ExprResult SubstitutedAtomicExpr = Evaluator(ConstraintExpr);
234480093f4SDimitry Andric 
235480093f4SDimitry Andric   if (SubstitutedAtomicExpr.isInvalid())
236bdd1243dSDimitry Andric     return ExprError();
237480093f4SDimitry Andric 
238480093f4SDimitry Andric   if (!SubstitutedAtomicExpr.isUsable())
239480093f4SDimitry Andric     // Evaluator has decided satisfaction without yielding an expression.
240bdd1243dSDimitry Andric     return ExprEmpty();
241bdd1243dSDimitry Andric 
242bdd1243dSDimitry Andric   // We don't have the ability to evaluate this, since it contains a
243bdd1243dSDimitry Andric   // RecoveryExpr, so we want to fail overload resolution.  Otherwise,
244bdd1243dSDimitry Andric   // we'd potentially pick up a different overload, and cause confusing
245bdd1243dSDimitry Andric   // diagnostics. SO, add a failure detail that will cause us to make this
246bdd1243dSDimitry Andric   // overload set not viable.
247bdd1243dSDimitry Andric   if (SubstitutedAtomicExpr.get()->containsErrors()) {
248bdd1243dSDimitry Andric     Satisfaction.IsSatisfied = false;
249bdd1243dSDimitry Andric     Satisfaction.ContainsErrors = true;
250bdd1243dSDimitry Andric 
251bdd1243dSDimitry Andric     PartialDiagnostic Msg = S.PDiag(diag::note_constraint_references_error);
252bdd1243dSDimitry Andric     SmallString<128> DiagString;
253bdd1243dSDimitry Andric     DiagString = ": ";
254bdd1243dSDimitry Andric     Msg.EmitToString(S.getDiagnostics(), DiagString);
255bdd1243dSDimitry Andric     unsigned MessageSize = DiagString.size();
256bdd1243dSDimitry Andric     char *Mem = new (S.Context) char[MessageSize];
257bdd1243dSDimitry Andric     memcpy(Mem, DiagString.c_str(), MessageSize);
258bdd1243dSDimitry Andric     Satisfaction.Details.emplace_back(
259bdd1243dSDimitry Andric         ConstraintExpr,
260bdd1243dSDimitry Andric         new (S.Context) ConstraintSatisfaction::SubstitutionDiagnostic{
261bdd1243dSDimitry Andric             SubstitutedAtomicExpr.get()->getBeginLoc(),
262bdd1243dSDimitry Andric             StringRef(Mem, MessageSize)});
263bdd1243dSDimitry Andric     return SubstitutedAtomicExpr;
264bdd1243dSDimitry Andric   }
265a7dea167SDimitry Andric 
266a7dea167SDimitry Andric   EnterExpressionEvaluationContext ConstantEvaluated(
267480093f4SDimitry Andric       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
268a7dea167SDimitry Andric   SmallVector<PartialDiagnosticAt, 2> EvaluationDiags;
269a7dea167SDimitry Andric   Expr::EvalResult EvalResult;
270a7dea167SDimitry Andric   EvalResult.Diag = &EvaluationDiags;
271fe6060f1SDimitry Andric   if (!SubstitutedAtomicExpr.get()->EvaluateAsConstantExpr(EvalResult,
272fe6060f1SDimitry Andric                                                            S.Context) ||
273fe6060f1SDimitry Andric       !EvaluationDiags.empty()) {
274a7dea167SDimitry Andric     // C++2a [temp.constr.atomic]p1
275a7dea167SDimitry Andric     //   ...E shall be a constant expression of type bool.
276480093f4SDimitry Andric     S.Diag(SubstitutedAtomicExpr.get()->getBeginLoc(),
277a7dea167SDimitry Andric            diag::err_non_constant_constraint_expression)
278480093f4SDimitry Andric         << SubstitutedAtomicExpr.get()->getSourceRange();
279a7dea167SDimitry Andric     for (const PartialDiagnosticAt &PDiag : EvaluationDiags)
280480093f4SDimitry Andric       S.Diag(PDiag.first, PDiag.second);
281bdd1243dSDimitry Andric     return ExprError();
282a7dea167SDimitry Andric   }
283a7dea167SDimitry Andric 
284fe6060f1SDimitry Andric   assert(EvalResult.Val.isInt() &&
285fe6060f1SDimitry Andric          "evaluating bool expression didn't produce int");
286480093f4SDimitry Andric   Satisfaction.IsSatisfied = EvalResult.Val.getInt().getBoolValue();
287480093f4SDimitry Andric   if (!Satisfaction.IsSatisfied)
288480093f4SDimitry Andric     Satisfaction.Details.emplace_back(ConstraintExpr,
289480093f4SDimitry Andric                                       SubstitutedAtomicExpr.get());
290a7dea167SDimitry Andric 
291bdd1243dSDimitry Andric   return SubstitutedAtomicExpr;
292bdd1243dSDimitry Andric }
293bdd1243dSDimitry Andric 
294bdd1243dSDimitry Andric static bool
2951ac55f4cSDimitry Andric DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID &ID,
2961ac55f4cSDimitry Andric                             const NamedDecl *Templ, const Expr *E,
297bdd1243dSDimitry Andric                             const MultiLevelTemplateArgumentList &MLTAL) {
298bdd1243dSDimitry Andric   E->Profile(ID, S.Context, /*Canonical=*/true);
299bdd1243dSDimitry Andric   for (const auto &List : MLTAL)
300bdd1243dSDimitry Andric     for (const auto &TemplateArg : List.Args)
301bdd1243dSDimitry Andric       TemplateArg.Profile(ID, S.Context);
302bdd1243dSDimitry Andric 
303bdd1243dSDimitry Andric   // Note that we have to do this with our own collection, because there are
304bdd1243dSDimitry Andric   // times where a constraint-expression check can cause us to need to evaluate
305bdd1243dSDimitry Andric   // other constriants that are unrelated, such as when evaluating a recovery
306bdd1243dSDimitry Andric   // expression, or when trying to determine the constexpr-ness of special
307bdd1243dSDimitry Andric   // members. Otherwise we could just use the
308bdd1243dSDimitry Andric   // Sema::InstantiatingTemplate::isAlreadyBeingInstantiated function.
3091ac55f4cSDimitry Andric   if (S.SatisfactionStackContains(Templ, ID)) {
310bdd1243dSDimitry Andric     S.Diag(E->getExprLoc(), diag::err_constraint_depends_on_self)
311bdd1243dSDimitry Andric         << const_cast<Expr *>(E) << E->getSourceRange();
312bdd1243dSDimitry Andric     return true;
313bdd1243dSDimitry Andric   }
314bdd1243dSDimitry Andric 
315a7dea167SDimitry Andric   return false;
316a7dea167SDimitry Andric }
317480093f4SDimitry Andric 
318bdd1243dSDimitry Andric static ExprResult calculateConstraintSatisfaction(
319bdd1243dSDimitry Andric     Sema &S, const NamedDecl *Template, SourceLocation TemplateNameLoc,
320bdd1243dSDimitry Andric     const MultiLevelTemplateArgumentList &MLTAL, const Expr *ConstraintExpr,
321bdd1243dSDimitry Andric     ConstraintSatisfaction &Satisfaction) {
322480093f4SDimitry Andric   return calculateConstraintSatisfaction(
323480093f4SDimitry Andric       S, ConstraintExpr, Satisfaction, [&](const Expr *AtomicExpr) {
324480093f4SDimitry Andric         EnterExpressionEvaluationContext ConstantEvaluated(
325bdd1243dSDimitry Andric             S, Sema::ExpressionEvaluationContext::ConstantEvaluated,
326bdd1243dSDimitry Andric             Sema::ReuseLambdaContextDecl);
327480093f4SDimitry Andric 
328480093f4SDimitry Andric         // Atomic constraint - substitute arguments and check satisfaction.
329480093f4SDimitry Andric         ExprResult SubstitutedExpression;
330480093f4SDimitry Andric         {
331480093f4SDimitry Andric           TemplateDeductionInfo Info(TemplateNameLoc);
332480093f4SDimitry Andric           Sema::InstantiatingTemplate Inst(S, AtomicExpr->getBeginLoc(),
33313138422SDimitry Andric               Sema::InstantiatingTemplate::ConstraintSubstitution{},
33413138422SDimitry Andric               const_cast<NamedDecl *>(Template), Info,
33513138422SDimitry Andric               AtomicExpr->getSourceRange());
336480093f4SDimitry Andric           if (Inst.isInvalid())
337480093f4SDimitry Andric             return ExprError();
338bdd1243dSDimitry Andric 
339bdd1243dSDimitry Andric           llvm::FoldingSetNodeID ID;
3401ac55f4cSDimitry Andric           if (Template &&
3411ac55f4cSDimitry Andric               DiagRecursiveConstraintEval(S, ID, Template, AtomicExpr, MLTAL)) {
342bdd1243dSDimitry Andric             Satisfaction.IsSatisfied = false;
343bdd1243dSDimitry Andric             Satisfaction.ContainsErrors = true;
344bdd1243dSDimitry Andric             return ExprEmpty();
345bdd1243dSDimitry Andric           }
346bdd1243dSDimitry Andric 
3471ac55f4cSDimitry Andric           SatisfactionStackRAII StackRAII(S, Template, ID);
348bdd1243dSDimitry Andric 
349480093f4SDimitry Andric           // We do not want error diagnostics escaping here.
350480093f4SDimitry Andric           Sema::SFINAETrap Trap(S);
351fe6060f1SDimitry Andric           SubstitutedExpression =
352bdd1243dSDimitry Andric               S.SubstConstraintExpr(const_cast<Expr *>(AtomicExpr), MLTAL);
353bdd1243dSDimitry Andric 
354480093f4SDimitry Andric           if (SubstitutedExpression.isInvalid() || Trap.hasErrorOccurred()) {
355480093f4SDimitry Andric             // C++2a [temp.constr.atomic]p1
356480093f4SDimitry Andric             //   ...If substitution results in an invalid type or expression, the
357480093f4SDimitry Andric             //   constraint is not satisfied.
358480093f4SDimitry Andric             if (!Trap.hasErrorOccurred())
359349cc55cSDimitry Andric               // A non-SFINAE error has occurred as a result of this
360480093f4SDimitry Andric               // substitution.
361480093f4SDimitry Andric               return ExprError();
362480093f4SDimitry Andric 
363480093f4SDimitry Andric             PartialDiagnosticAt SubstDiag{SourceLocation(),
364480093f4SDimitry Andric                                           PartialDiagnostic::NullDiagnostic()};
365480093f4SDimitry Andric             Info.takeSFINAEDiagnostic(SubstDiag);
366480093f4SDimitry Andric             // FIXME: Concepts: This is an unfortunate consequence of there
367480093f4SDimitry Andric             //  being no serialization code for PartialDiagnostics and the fact
368480093f4SDimitry Andric             //  that serializing them would likely take a lot more storage than
369480093f4SDimitry Andric             //  just storing them as strings. We would still like, in the
370480093f4SDimitry Andric             //  future, to serialize the proper PartialDiagnostic as serializing
371480093f4SDimitry Andric             //  it as a string defeats the purpose of the diagnostic mechanism.
372480093f4SDimitry Andric             SmallString<128> DiagString;
373480093f4SDimitry Andric             DiagString = ": ";
374480093f4SDimitry Andric             SubstDiag.second.EmitToString(S.getDiagnostics(), DiagString);
375480093f4SDimitry Andric             unsigned MessageSize = DiagString.size();
376480093f4SDimitry Andric             char *Mem = new (S.Context) char[MessageSize];
377480093f4SDimitry Andric             memcpy(Mem, DiagString.c_str(), MessageSize);
378480093f4SDimitry Andric             Satisfaction.Details.emplace_back(
379480093f4SDimitry Andric                 AtomicExpr,
380480093f4SDimitry Andric                 new (S.Context) ConstraintSatisfaction::SubstitutionDiagnostic{
381480093f4SDimitry Andric                         SubstDiag.first, StringRef(Mem, MessageSize)});
382480093f4SDimitry Andric             Satisfaction.IsSatisfied = false;
383480093f4SDimitry Andric             return ExprEmpty();
384480093f4SDimitry Andric           }
385480093f4SDimitry Andric         }
386480093f4SDimitry Andric 
387480093f4SDimitry Andric         if (!S.CheckConstraintExpression(SubstitutedExpression.get()))
388480093f4SDimitry Andric           return ExprError();
389480093f4SDimitry Andric 
390bdd1243dSDimitry Andric         // [temp.constr.atomic]p3: To determine if an atomic constraint is
391bdd1243dSDimitry Andric         // satisfied, the parameter mapping and template arguments are first
392bdd1243dSDimitry Andric         // substituted into its expression.  If substitution results in an
393bdd1243dSDimitry Andric         // invalid type or expression, the constraint is not satisfied.
394bdd1243dSDimitry Andric         // Otherwise, the lvalue-to-rvalue conversion is performed if necessary,
395bdd1243dSDimitry Andric         // and E shall be a constant expression of type bool.
396bdd1243dSDimitry Andric         //
397bdd1243dSDimitry Andric         // Perform the L to R Value conversion if necessary. We do so for all
398bdd1243dSDimitry Andric         // non-PRValue categories, else we fail to extend the lifetime of
399bdd1243dSDimitry Andric         // temporaries, and that fails the constant expression check.
400bdd1243dSDimitry Andric         if (!SubstitutedExpression.get()->isPRValue())
401bdd1243dSDimitry Andric           SubstitutedExpression = ImplicitCastExpr::Create(
402bdd1243dSDimitry Andric               S.Context, SubstitutedExpression.get()->getType(),
403bdd1243dSDimitry Andric               CK_LValueToRValue, SubstitutedExpression.get(),
404bdd1243dSDimitry Andric               /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
405bdd1243dSDimitry Andric 
406480093f4SDimitry Andric         return SubstitutedExpression;
407480093f4SDimitry Andric       });
408480093f4SDimitry Andric }
409480093f4SDimitry Andric 
410bdd1243dSDimitry Andric static bool CheckConstraintSatisfaction(
411bdd1243dSDimitry Andric     Sema &S, const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
412bdd1243dSDimitry Andric     llvm::SmallVectorImpl<Expr *> &Converted,
413bdd1243dSDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgsLists,
414bdd1243dSDimitry Andric     SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
415480093f4SDimitry Andric   if (ConstraintExprs.empty()) {
416480093f4SDimitry Andric     Satisfaction.IsSatisfied = true;
417480093f4SDimitry Andric     return false;
418480093f4SDimitry Andric   }
419480093f4SDimitry Andric 
420bdd1243dSDimitry Andric   if (TemplateArgsLists.isAnyArgInstantiationDependent()) {
421480093f4SDimitry Andric     // No need to check satisfaction for dependent constraint expressions.
422480093f4SDimitry Andric     Satisfaction.IsSatisfied = true;
423480093f4SDimitry Andric     return false;
424480093f4SDimitry Andric   }
425480093f4SDimitry Andric 
426bdd1243dSDimitry Andric   ArrayRef<TemplateArgument> TemplateArgs =
427bdd1243dSDimitry Andric       TemplateArgsLists.getNumSubstitutedLevels() > 0
428bdd1243dSDimitry Andric           ? TemplateArgsLists.getOutermost()
429bdd1243dSDimitry Andric           : ArrayRef<TemplateArgument> {};
430480093f4SDimitry Andric   Sema::InstantiatingTemplate Inst(S, TemplateIDRange.getBegin(),
43113138422SDimitry Andric       Sema::InstantiatingTemplate::ConstraintsCheck{},
43213138422SDimitry Andric       const_cast<NamedDecl *>(Template), TemplateArgs, TemplateIDRange);
433480093f4SDimitry Andric   if (Inst.isInvalid())
434480093f4SDimitry Andric     return true;
435480093f4SDimitry Andric 
436480093f4SDimitry Andric   for (const Expr *ConstraintExpr : ConstraintExprs) {
437bdd1243dSDimitry Andric     ExprResult Res = calculateConstraintSatisfaction(
438bdd1243dSDimitry Andric         S, Template, TemplateIDRange.getBegin(), TemplateArgsLists,
439bdd1243dSDimitry Andric         ConstraintExpr, Satisfaction);
440bdd1243dSDimitry Andric     if (Res.isInvalid())
441480093f4SDimitry Andric       return true;
442bdd1243dSDimitry Andric 
443bdd1243dSDimitry Andric     Converted.push_back(Res.get());
444bdd1243dSDimitry Andric     if (!Satisfaction.IsSatisfied) {
445bdd1243dSDimitry Andric       // Backfill the 'converted' list with nulls so we can keep the Converted
446bdd1243dSDimitry Andric       // and unconverted lists in sync.
447bdd1243dSDimitry Andric       Converted.append(ConstraintExprs.size() - Converted.size(), nullptr);
448480093f4SDimitry Andric       // [temp.constr.op] p2
449480093f4SDimitry Andric       // [...] To determine if a conjunction is satisfied, the satisfaction
450480093f4SDimitry Andric       // of the first operand is checked. If that is not satisfied, the
451480093f4SDimitry Andric       // conjunction is not satisfied. [...]
452480093f4SDimitry Andric       return false;
453480093f4SDimitry Andric     }
454bdd1243dSDimitry Andric   }
455480093f4SDimitry Andric   return false;
456480093f4SDimitry Andric }
457480093f4SDimitry Andric 
45855e4f9d5SDimitry Andric bool Sema::CheckConstraintSatisfaction(
45913138422SDimitry Andric     const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
460bdd1243dSDimitry Andric     llvm::SmallVectorImpl<Expr *> &ConvertedConstraints,
461bdd1243dSDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgsLists,
462bdd1243dSDimitry Andric     SourceRange TemplateIDRange, ConstraintSatisfaction &OutSatisfaction) {
46355e4f9d5SDimitry Andric   if (ConstraintExprs.empty()) {
46455e4f9d5SDimitry Andric     OutSatisfaction.IsSatisfied = true;
46555e4f9d5SDimitry Andric     return false;
466480093f4SDimitry Andric   }
46781ad6265SDimitry Andric   if (!Template) {
468bdd1243dSDimitry Andric     return ::CheckConstraintSatisfaction(
469bdd1243dSDimitry Andric         *this, nullptr, ConstraintExprs, ConvertedConstraints,
470bdd1243dSDimitry Andric         TemplateArgsLists, TemplateIDRange, OutSatisfaction);
47181ad6265SDimitry Andric   }
472bdd1243dSDimitry Andric 
473bdd1243dSDimitry Andric   // A list of the template argument list flattened in a predictible manner for
474bdd1243dSDimitry Andric   // the purposes of caching. The ConstraintSatisfaction type is in AST so it
475bdd1243dSDimitry Andric   // has no access to the MultiLevelTemplateArgumentList, so this has to happen
476bdd1243dSDimitry Andric   // here.
477bdd1243dSDimitry Andric   llvm::SmallVector<TemplateArgument, 4> FlattenedArgs;
478bdd1243dSDimitry Andric   for (auto List : TemplateArgsLists)
479bdd1243dSDimitry Andric     FlattenedArgs.insert(FlattenedArgs.end(), List.Args.begin(),
480bdd1243dSDimitry Andric                          List.Args.end());
481bdd1243dSDimitry Andric 
48255e4f9d5SDimitry Andric   llvm::FoldingSetNodeID ID;
483bdd1243dSDimitry Andric   ConstraintSatisfaction::Profile(ID, Context, Template, FlattenedArgs);
48481ad6265SDimitry Andric   void *InsertPos;
48581ad6265SDimitry Andric   if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
48681ad6265SDimitry Andric     OutSatisfaction = *Cached;
48755e4f9d5SDimitry Andric     return false;
48855e4f9d5SDimitry Andric   }
489bdd1243dSDimitry Andric 
49081ad6265SDimitry Andric   auto Satisfaction =
491bdd1243dSDimitry Andric       std::make_unique<ConstraintSatisfaction>(Template, FlattenedArgs);
49213138422SDimitry Andric   if (::CheckConstraintSatisfaction(*this, Template, ConstraintExprs,
493bdd1243dSDimitry Andric                                     ConvertedConstraints, TemplateArgsLists,
494bdd1243dSDimitry Andric                                     TemplateIDRange, *Satisfaction)) {
495bdd1243dSDimitry Andric     OutSatisfaction = *Satisfaction;
49655e4f9d5SDimitry Andric     return true;
497480093f4SDimitry Andric   }
498bdd1243dSDimitry Andric 
499bdd1243dSDimitry Andric   if (auto *Cached = SatisfactionCache.FindNodeOrInsertPos(ID, InsertPos)) {
500bdd1243dSDimitry Andric     // The evaluation of this constraint resulted in us trying to re-evaluate it
501bdd1243dSDimitry Andric     // recursively. This isn't really possible, except we try to form a
502bdd1243dSDimitry Andric     // RecoveryExpr as a part of the evaluation.  If this is the case, just
503bdd1243dSDimitry Andric     // return the 'cached' version (which will have the same result), and save
504bdd1243dSDimitry Andric     // ourselves the extra-insert. If it ever becomes possible to legitimately
505bdd1243dSDimitry Andric     // recursively check a constraint, we should skip checking the 'inner' one
506bdd1243dSDimitry Andric     // above, and replace the cached version with this one, as it would be more
507bdd1243dSDimitry Andric     // specific.
508bdd1243dSDimitry Andric     OutSatisfaction = *Cached;
509bdd1243dSDimitry Andric     return false;
510bdd1243dSDimitry Andric   }
511bdd1243dSDimitry Andric 
512bdd1243dSDimitry Andric   // Else we can simply add this satisfaction to the list.
51355e4f9d5SDimitry Andric   OutSatisfaction = *Satisfaction;
51481ad6265SDimitry Andric   // We cannot use InsertPos here because CheckConstraintSatisfaction might have
51581ad6265SDimitry Andric   // invalidated it.
51681ad6265SDimitry Andric   // Note that entries of SatisfactionCache are deleted in Sema's destructor.
51781ad6265SDimitry Andric   SatisfactionCache.InsertNode(Satisfaction.release());
51855e4f9d5SDimitry Andric   return false;
519480093f4SDimitry Andric }
520480093f4SDimitry Andric 
521480093f4SDimitry Andric bool Sema::CheckConstraintSatisfaction(const Expr *ConstraintExpr,
522480093f4SDimitry Andric                                        ConstraintSatisfaction &Satisfaction) {
523480093f4SDimitry Andric   return calculateConstraintSatisfaction(
524480093f4SDimitry Andric              *this, ConstraintExpr, Satisfaction,
52581ad6265SDimitry Andric              [this](const Expr *AtomicExpr) -> ExprResult {
52681ad6265SDimitry Andric                // We only do this to immitate lvalue-to-rvalue conversion.
527bdd1243dSDimitry Andric                return PerformContextuallyConvertToBool(
528bdd1243dSDimitry Andric                    const_cast<Expr *>(AtomicExpr));
529bdd1243dSDimitry Andric              })
530bdd1243dSDimitry Andric       .isInvalid();
531bdd1243dSDimitry Andric }
532bdd1243dSDimitry Andric 
53306c3fb27SDimitry Andric bool Sema::addInstantiatedCapturesToScope(
53406c3fb27SDimitry Andric     FunctionDecl *Function, const FunctionDecl *PatternDecl,
53506c3fb27SDimitry Andric     LocalInstantiationScope &Scope,
53606c3fb27SDimitry Andric     const MultiLevelTemplateArgumentList &TemplateArgs) {
53706c3fb27SDimitry Andric   const auto *LambdaClass = cast<CXXMethodDecl>(Function)->getParent();
53806c3fb27SDimitry Andric   const auto *LambdaPattern = cast<CXXMethodDecl>(PatternDecl)->getParent();
53906c3fb27SDimitry Andric 
54006c3fb27SDimitry Andric   unsigned Instantiated = 0;
54106c3fb27SDimitry Andric 
54206c3fb27SDimitry Andric   auto AddSingleCapture = [&](const ValueDecl *CapturedPattern,
54306c3fb27SDimitry Andric                               unsigned Index) {
54406c3fb27SDimitry Andric     ValueDecl *CapturedVar = LambdaClass->getCapture(Index)->getCapturedVar();
54506c3fb27SDimitry Andric     if (CapturedVar->isInitCapture())
54606c3fb27SDimitry Andric       Scope.InstantiatedLocal(CapturedPattern, CapturedVar);
54706c3fb27SDimitry Andric   };
54806c3fb27SDimitry Andric 
54906c3fb27SDimitry Andric   for (const LambdaCapture &CapturePattern : LambdaPattern->captures()) {
55006c3fb27SDimitry Andric     if (!CapturePattern.capturesVariable()) {
55106c3fb27SDimitry Andric       Instantiated++;
55206c3fb27SDimitry Andric       continue;
55306c3fb27SDimitry Andric     }
55406c3fb27SDimitry Andric     const ValueDecl *CapturedPattern = CapturePattern.getCapturedVar();
55506c3fb27SDimitry Andric     if (!CapturedPattern->isParameterPack()) {
55606c3fb27SDimitry Andric       AddSingleCapture(CapturedPattern, Instantiated++);
55706c3fb27SDimitry Andric     } else {
55806c3fb27SDimitry Andric       Scope.MakeInstantiatedLocalArgPack(CapturedPattern);
55906c3fb27SDimitry Andric       std::optional<unsigned> NumArgumentsInExpansion =
56006c3fb27SDimitry Andric           getNumArgumentsInExpansion(CapturedPattern->getType(), TemplateArgs);
56106c3fb27SDimitry Andric       if (!NumArgumentsInExpansion)
56206c3fb27SDimitry Andric         continue;
56306c3fb27SDimitry Andric       for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg)
56406c3fb27SDimitry Andric         AddSingleCapture(CapturedPattern, Instantiated++);
56506c3fb27SDimitry Andric     }
56606c3fb27SDimitry Andric   }
56706c3fb27SDimitry Andric   return false;
56806c3fb27SDimitry Andric }
56906c3fb27SDimitry Andric 
570bdd1243dSDimitry Andric bool Sema::SetupConstraintScope(
571bdd1243dSDimitry Andric     FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
572bdd1243dSDimitry Andric     MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope) {
573bdd1243dSDimitry Andric   if (FD->isTemplateInstantiation() && FD->getPrimaryTemplate()) {
574bdd1243dSDimitry Andric     FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
575bdd1243dSDimitry Andric     InstantiatingTemplate Inst(
576bdd1243dSDimitry Andric         *this, FD->getPointOfInstantiation(),
577bdd1243dSDimitry Andric         Sema::InstantiatingTemplate::ConstraintsCheck{}, PrimaryTemplate,
578bdd1243dSDimitry Andric         TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
579bdd1243dSDimitry Andric         SourceRange());
580bdd1243dSDimitry Andric     if (Inst.isInvalid())
581bdd1243dSDimitry Andric       return true;
582bdd1243dSDimitry Andric 
583bdd1243dSDimitry Andric     // addInstantiatedParametersToScope creates a map of 'uninstantiated' to
584bdd1243dSDimitry Andric     // 'instantiated' parameters and adds it to the context. For the case where
585bdd1243dSDimitry Andric     // this function is a template being instantiated NOW, we also need to add
586bdd1243dSDimitry Andric     // the list of current template arguments to the list so that they also can
587bdd1243dSDimitry Andric     // be picked out of the map.
588bdd1243dSDimitry Andric     if (auto *SpecArgs = FD->getTemplateSpecializationArgs()) {
589bdd1243dSDimitry Andric       MultiLevelTemplateArgumentList JustTemplArgs(FD, SpecArgs->asArray(),
590bdd1243dSDimitry Andric                                                    /*Final=*/false);
591bdd1243dSDimitry Andric       if (addInstantiatedParametersToScope(
592bdd1243dSDimitry Andric               FD, PrimaryTemplate->getTemplatedDecl(), Scope, JustTemplArgs))
593bdd1243dSDimitry Andric         return true;
594bdd1243dSDimitry Andric     }
595bdd1243dSDimitry Andric 
596bdd1243dSDimitry Andric     // If this is a member function, make sure we get the parameters that
597bdd1243dSDimitry Andric     // reference the original primary template.
598bdd1243dSDimitry Andric     if (const auto *FromMemTempl =
599bdd1243dSDimitry Andric             PrimaryTemplate->getInstantiatedFromMemberTemplate()) {
600bdd1243dSDimitry Andric       if (addInstantiatedParametersToScope(FD, FromMemTempl->getTemplatedDecl(),
601bdd1243dSDimitry Andric                                            Scope, MLTAL))
602bdd1243dSDimitry Andric         return true;
603bdd1243dSDimitry Andric     }
604bdd1243dSDimitry Andric 
605bdd1243dSDimitry Andric     return false;
606bdd1243dSDimitry Andric   }
607bdd1243dSDimitry Andric 
608bdd1243dSDimitry Andric   if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization ||
609bdd1243dSDimitry Andric       FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate) {
610bdd1243dSDimitry Andric     FunctionDecl *InstantiatedFrom =
611bdd1243dSDimitry Andric         FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization
612bdd1243dSDimitry Andric             ? FD->getInstantiatedFromMemberFunction()
613bdd1243dSDimitry Andric             : FD->getInstantiatedFromDecl();
614bdd1243dSDimitry Andric 
615bdd1243dSDimitry Andric     InstantiatingTemplate Inst(
616bdd1243dSDimitry Andric         *this, FD->getPointOfInstantiation(),
617bdd1243dSDimitry Andric         Sema::InstantiatingTemplate::ConstraintsCheck{}, InstantiatedFrom,
618bdd1243dSDimitry Andric         TemplateArgs ? *TemplateArgs : ArrayRef<TemplateArgument>{},
619bdd1243dSDimitry Andric         SourceRange());
620bdd1243dSDimitry Andric     if (Inst.isInvalid())
621bdd1243dSDimitry Andric       return true;
622bdd1243dSDimitry Andric 
623bdd1243dSDimitry Andric     // Case where this was not a template, but instantiated as a
624bdd1243dSDimitry Andric     // child-function.
625bdd1243dSDimitry Andric     if (addInstantiatedParametersToScope(FD, InstantiatedFrom, Scope, MLTAL))
626bdd1243dSDimitry Andric       return true;
627bdd1243dSDimitry Andric   }
628bdd1243dSDimitry Andric 
629bdd1243dSDimitry Andric   return false;
630bdd1243dSDimitry Andric }
631bdd1243dSDimitry Andric 
632bdd1243dSDimitry Andric // This function collects all of the template arguments for the purposes of
633bdd1243dSDimitry Andric // constraint-instantiation and checking.
634bdd1243dSDimitry Andric std::optional<MultiLevelTemplateArgumentList>
635bdd1243dSDimitry Andric Sema::SetupConstraintCheckingTemplateArgumentsAndScope(
636bdd1243dSDimitry Andric     FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
637bdd1243dSDimitry Andric     LocalInstantiationScope &Scope) {
638bdd1243dSDimitry Andric   MultiLevelTemplateArgumentList MLTAL;
639bdd1243dSDimitry Andric 
640bdd1243dSDimitry Andric   // Collect the list of template arguments relative to the 'primary' template.
641bdd1243dSDimitry Andric   // We need the entire list, since the constraint is completely uninstantiated
642bdd1243dSDimitry Andric   // at this point.
643bdd1243dSDimitry Andric   MLTAL =
644bdd1243dSDimitry Andric       getTemplateInstantiationArgs(FD, /*Final=*/false, /*Innermost=*/nullptr,
645bdd1243dSDimitry Andric                                    /*RelativeToPrimary=*/true,
646bdd1243dSDimitry Andric                                    /*Pattern=*/nullptr,
647bdd1243dSDimitry Andric                                    /*ForConstraintInstantiation=*/true);
648bdd1243dSDimitry Andric   if (SetupConstraintScope(FD, TemplateArgs, MLTAL, Scope))
649bdd1243dSDimitry Andric     return std::nullopt;
650bdd1243dSDimitry Andric 
651bdd1243dSDimitry Andric   return MLTAL;
652480093f4SDimitry Andric }
653480093f4SDimitry Andric 
65413138422SDimitry Andric bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
65513138422SDimitry Andric                                     ConstraintSatisfaction &Satisfaction,
656bdd1243dSDimitry Andric                                     SourceLocation UsageLoc,
657bdd1243dSDimitry Andric                                     bool ForOverloadResolution) {
658bdd1243dSDimitry Andric   // Don't check constraints if the function is dependent. Also don't check if
659bdd1243dSDimitry Andric   // this is a function template specialization, as the call to
660bdd1243dSDimitry Andric   // CheckinstantiatedFunctionTemplateConstraints after this will check it
661bdd1243dSDimitry Andric   // better.
662bdd1243dSDimitry Andric   if (FD->isDependentContext() ||
663bdd1243dSDimitry Andric       FD->getTemplatedKind() ==
664bdd1243dSDimitry Andric           FunctionDecl::TK_FunctionTemplateSpecialization) {
66513138422SDimitry Andric     Satisfaction.IsSatisfied = true;
66613138422SDimitry Andric     return false;
66713138422SDimitry Andric   }
668bdd1243dSDimitry Andric 
66906c3fb27SDimitry Andric   // A lambda conversion operator has the same constraints as the call operator
67006c3fb27SDimitry Andric   // and constraints checking relies on whether we are in a lambda call operator
67106c3fb27SDimitry Andric   // (and may refer to its parameters), so check the call operator instead.
67206c3fb27SDimitry Andric   if (const auto *MD = dyn_cast<CXXConversionDecl>(FD);
67306c3fb27SDimitry Andric       MD && isLambdaConversionOperator(const_cast<CXXConversionDecl *>(MD)))
67406c3fb27SDimitry Andric     return CheckFunctionConstraints(MD->getParent()->getLambdaCallOperator(),
67506c3fb27SDimitry Andric                                     Satisfaction, UsageLoc,
67606c3fb27SDimitry Andric                                     ForOverloadResolution);
67706c3fb27SDimitry Andric 
678bdd1243dSDimitry Andric   DeclContext *CtxToSave = const_cast<FunctionDecl *>(FD);
679bdd1243dSDimitry Andric 
680bdd1243dSDimitry Andric   while (isLambdaCallOperator(CtxToSave) || FD->isTransparentContext()) {
681bdd1243dSDimitry Andric     if (isLambdaCallOperator(CtxToSave))
682bdd1243dSDimitry Andric       CtxToSave = CtxToSave->getParent()->getParent();
683bdd1243dSDimitry Andric     else
684bdd1243dSDimitry Andric       CtxToSave = CtxToSave->getNonTransparentContext();
685bdd1243dSDimitry Andric   }
686bdd1243dSDimitry Andric 
687bdd1243dSDimitry Andric   ContextRAII SavedContext{*this, CtxToSave};
688bdd1243dSDimitry Andric   LocalInstantiationScope Scope(*this, !ForOverloadResolution ||
689bdd1243dSDimitry Andric                                            isLambdaCallOperator(FD));
690bdd1243dSDimitry Andric   std::optional<MultiLevelTemplateArgumentList> MLTAL =
691bdd1243dSDimitry Andric       SetupConstraintCheckingTemplateArgumentsAndScope(
692bdd1243dSDimitry Andric           const_cast<FunctionDecl *>(FD), {}, Scope);
693bdd1243dSDimitry Andric 
694bdd1243dSDimitry Andric   if (!MLTAL)
695bdd1243dSDimitry Andric     return true;
696bdd1243dSDimitry Andric 
69713138422SDimitry Andric   Qualifiers ThisQuals;
69813138422SDimitry Andric   CXXRecordDecl *Record = nullptr;
69913138422SDimitry Andric   if (auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
70013138422SDimitry Andric     ThisQuals = Method->getMethodQualifiers();
70113138422SDimitry Andric     Record = const_cast<CXXRecordDecl *>(Method->getParent());
70213138422SDimitry Andric   }
70313138422SDimitry Andric   CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
704*feb5b0c7SDimitry Andric 
705*feb5b0c7SDimitry Andric   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
706*feb5b0c7SDimitry Andric       *this, const_cast<FunctionDecl *>(FD), *MLTAL, Scope);
707*feb5b0c7SDimitry Andric 
70806c3fb27SDimitry Andric   return CheckConstraintSatisfaction(
70906c3fb27SDimitry Andric       FD, {FD->getTrailingRequiresClause()}, *MLTAL,
71013138422SDimitry Andric       SourceRange(UsageLoc.isValid() ? UsageLoc : FD->getLocation()),
71106c3fb27SDimitry Andric       Satisfaction);
712bdd1243dSDimitry Andric }
713bdd1243dSDimitry Andric 
714bdd1243dSDimitry Andric 
715bdd1243dSDimitry Andric // Figure out the to-translation-unit depth for this function declaration for
716bdd1243dSDimitry Andric // the purpose of seeing if they differ by constraints. This isn't the same as
717bdd1243dSDimitry Andric // getTemplateDepth, because it includes already instantiated parents.
718bdd1243dSDimitry Andric static unsigned
719bdd1243dSDimitry Andric CalculateTemplateDepthForConstraints(Sema &S, const NamedDecl *ND,
720bdd1243dSDimitry Andric                                      bool SkipForSpecialization = false) {
721bdd1243dSDimitry Andric   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
722bdd1243dSDimitry Andric       ND, /*Final=*/false, /*Innermost=*/nullptr, /*RelativeToPrimary=*/true,
723bdd1243dSDimitry Andric       /*Pattern=*/nullptr,
724bdd1243dSDimitry Andric       /*ForConstraintInstantiation=*/true, SkipForSpecialization);
72506c3fb27SDimitry Andric   return MLTAL.getNumLevels();
726bdd1243dSDimitry Andric }
727bdd1243dSDimitry Andric 
728bdd1243dSDimitry Andric namespace {
729bdd1243dSDimitry Andric   class AdjustConstraintDepth : public TreeTransform<AdjustConstraintDepth> {
730bdd1243dSDimitry Andric   unsigned TemplateDepth = 0;
731bdd1243dSDimitry Andric   public:
732bdd1243dSDimitry Andric   using inherited = TreeTransform<AdjustConstraintDepth>;
733bdd1243dSDimitry Andric   AdjustConstraintDepth(Sema &SemaRef, unsigned TemplateDepth)
734bdd1243dSDimitry Andric       : inherited(SemaRef), TemplateDepth(TemplateDepth) {}
735bdd1243dSDimitry Andric 
736bdd1243dSDimitry Andric   using inherited::TransformTemplateTypeParmType;
737bdd1243dSDimitry Andric   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
738bdd1243dSDimitry Andric                                          TemplateTypeParmTypeLoc TL, bool) {
739bdd1243dSDimitry Andric     const TemplateTypeParmType *T = TL.getTypePtr();
740bdd1243dSDimitry Andric 
741bdd1243dSDimitry Andric     TemplateTypeParmDecl *NewTTPDecl = nullptr;
742bdd1243dSDimitry Andric     if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
743bdd1243dSDimitry Andric       NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
744bdd1243dSDimitry Andric           TransformDecl(TL.getNameLoc(), OldTTPDecl));
745bdd1243dSDimitry Andric 
746bdd1243dSDimitry Andric     QualType Result = getSema().Context.getTemplateTypeParmType(
747bdd1243dSDimitry Andric         T->getDepth() + TemplateDepth, T->getIndex(), T->isParameterPack(),
748bdd1243dSDimitry Andric         NewTTPDecl);
749bdd1243dSDimitry Andric     TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
750bdd1243dSDimitry Andric     NewTL.setNameLoc(TL.getNameLoc());
751bdd1243dSDimitry Andric     return Result;
752bdd1243dSDimitry Andric   }
753bdd1243dSDimitry Andric   };
754bdd1243dSDimitry Andric } // namespace
755bdd1243dSDimitry Andric 
75606c3fb27SDimitry Andric static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
75706c3fb27SDimitry Andric                                                   const Expr *ConstrExpr) {
75806c3fb27SDimitry Andric   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
75906c3fb27SDimitry Andric       ND, /*Final=*/false, /*Innermost=*/nullptr,
76006c3fb27SDimitry Andric       /*RelativeToPrimary=*/true,
76106c3fb27SDimitry Andric       /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
76206c3fb27SDimitry Andric       /*SkipForSpecialization*/ false);
76306c3fb27SDimitry Andric   if (MLTAL.getNumSubstitutedLevels() == 0)
76406c3fb27SDimitry Andric     return ConstrExpr;
76506c3fb27SDimitry Andric 
76606c3fb27SDimitry Andric   Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
76706c3fb27SDimitry Andric 
76806c3fb27SDimitry Andric   Sema::InstantiatingTemplate Inst(
76906c3fb27SDimitry Andric       S, ND->getLocation(),
77006c3fb27SDimitry Andric       Sema::InstantiatingTemplate::ConstraintNormalization{},
77106c3fb27SDimitry Andric       const_cast<NamedDecl *>(ND), SourceRange{});
77206c3fb27SDimitry Andric 
77306c3fb27SDimitry Andric   if (Inst.isInvalid())
77406c3fb27SDimitry Andric     return nullptr;
77506c3fb27SDimitry Andric 
77606c3fb27SDimitry Andric   std::optional<Sema::CXXThisScopeRAII> ThisScope;
77706c3fb27SDimitry Andric   if (auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()))
77806c3fb27SDimitry Andric     ThisScope.emplace(S, const_cast<CXXRecordDecl *>(RD), Qualifiers());
77906c3fb27SDimitry Andric   ExprResult SubstConstr =
78006c3fb27SDimitry Andric       S.SubstConstraintExpr(const_cast<clang::Expr *>(ConstrExpr), MLTAL);
78106c3fb27SDimitry Andric   if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
78206c3fb27SDimitry Andric     return nullptr;
78306c3fb27SDimitry Andric   return SubstConstr.get();
78406c3fb27SDimitry Andric }
78506c3fb27SDimitry Andric 
786bdd1243dSDimitry Andric bool Sema::AreConstraintExpressionsEqual(const NamedDecl *Old,
787bdd1243dSDimitry Andric                                          const Expr *OldConstr,
788bdd1243dSDimitry Andric                                          const NamedDecl *New,
789bdd1243dSDimitry Andric                                          const Expr *NewConstr) {
79006c3fb27SDimitry Andric   if (OldConstr == NewConstr)
79106c3fb27SDimitry Andric     return true;
79206c3fb27SDimitry Andric   // C++ [temp.constr.decl]p4
79306c3fb27SDimitry Andric   if (Old && New && Old != New &&
79406c3fb27SDimitry Andric       Old->getLexicalDeclContext() != New->getLexicalDeclContext()) {
79506c3fb27SDimitry Andric     if (const Expr *SubstConstr =
79606c3fb27SDimitry Andric             SubstituteConstraintExpression(*this, Old, OldConstr))
79706c3fb27SDimitry Andric       OldConstr = SubstConstr;
79806c3fb27SDimitry Andric     else
79906c3fb27SDimitry Andric       return false;
80006c3fb27SDimitry Andric     if (const Expr *SubstConstr =
80106c3fb27SDimitry Andric             SubstituteConstraintExpression(*this, New, NewConstr))
80206c3fb27SDimitry Andric       NewConstr = SubstConstr;
80306c3fb27SDimitry Andric     else
80406c3fb27SDimitry Andric       return false;
805bdd1243dSDimitry Andric   }
806bdd1243dSDimitry Andric 
807bdd1243dSDimitry Andric   llvm::FoldingSetNodeID ID1, ID2;
808bdd1243dSDimitry Andric   OldConstr->Profile(ID1, Context, /*Canonical=*/true);
809bdd1243dSDimitry Andric   NewConstr->Profile(ID2, Context, /*Canonical=*/true);
810bdd1243dSDimitry Andric   return ID1 == ID2;
811bdd1243dSDimitry Andric }
812bdd1243dSDimitry Andric 
813bdd1243dSDimitry Andric bool Sema::FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD) {
814bdd1243dSDimitry Andric   assert(FD->getFriendObjectKind() && "Must be a friend!");
815bdd1243dSDimitry Andric 
816bdd1243dSDimitry Andric   // The logic for non-templates is handled in ASTContext::isSameEntity, so we
817bdd1243dSDimitry Andric   // don't have to bother checking 'DependsOnEnclosingTemplate' for a
818bdd1243dSDimitry Andric   // non-function-template.
819bdd1243dSDimitry Andric   assert(FD->getDescribedFunctionTemplate() &&
820bdd1243dSDimitry Andric          "Non-function templates don't need to be checked");
821bdd1243dSDimitry Andric 
822bdd1243dSDimitry Andric   SmallVector<const Expr *, 3> ACs;
823bdd1243dSDimitry Andric   FD->getDescribedFunctionTemplate()->getAssociatedConstraints(ACs);
824bdd1243dSDimitry Andric 
825bdd1243dSDimitry Andric   unsigned OldTemplateDepth = CalculateTemplateDepthForConstraints(*this, FD);
826bdd1243dSDimitry Andric   for (const Expr *Constraint : ACs)
827bdd1243dSDimitry Andric     if (ConstraintExpressionDependsOnEnclosingTemplate(FD, OldTemplateDepth,
828bdd1243dSDimitry Andric                                                        Constraint))
829bdd1243dSDimitry Andric       return true;
830bdd1243dSDimitry Andric 
831bdd1243dSDimitry Andric   return false;
83213138422SDimitry Andric }
83313138422SDimitry Andric 
834480093f4SDimitry Andric bool Sema::EnsureTemplateArgumentListConstraints(
835bdd1243dSDimitry Andric     TemplateDecl *TD, const MultiLevelTemplateArgumentList &TemplateArgsLists,
836480093f4SDimitry Andric     SourceRange TemplateIDRange) {
837480093f4SDimitry Andric   ConstraintSatisfaction Satisfaction;
838480093f4SDimitry Andric   llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
839480093f4SDimitry Andric   TD->getAssociatedConstraints(AssociatedConstraints);
840bdd1243dSDimitry Andric   if (CheckConstraintSatisfaction(TD, AssociatedConstraints, TemplateArgsLists,
841480093f4SDimitry Andric                                   TemplateIDRange, Satisfaction))
842480093f4SDimitry Andric     return true;
843480093f4SDimitry Andric 
844480093f4SDimitry Andric   if (!Satisfaction.IsSatisfied) {
845480093f4SDimitry Andric     SmallString<128> TemplateArgString;
846480093f4SDimitry Andric     TemplateArgString = " ";
847480093f4SDimitry Andric     TemplateArgString += getTemplateArgumentBindingsText(
848bdd1243dSDimitry Andric         TD->getTemplateParameters(), TemplateArgsLists.getInnermost().data(),
849bdd1243dSDimitry Andric         TemplateArgsLists.getInnermost().size());
850480093f4SDimitry Andric 
851480093f4SDimitry Andric     Diag(TemplateIDRange.getBegin(),
852480093f4SDimitry Andric          diag::err_template_arg_list_constraints_not_satisfied)
853480093f4SDimitry Andric         << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << TD
854480093f4SDimitry Andric         << TemplateArgString << TemplateIDRange;
855480093f4SDimitry Andric     DiagnoseUnsatisfiedConstraint(Satisfaction);
856480093f4SDimitry Andric     return true;
857480093f4SDimitry Andric   }
858480093f4SDimitry Andric   return false;
859480093f4SDimitry Andric }
860480093f4SDimitry Andric 
86181ad6265SDimitry Andric bool Sema::CheckInstantiatedFunctionTemplateConstraints(
86281ad6265SDimitry Andric     SourceLocation PointOfInstantiation, FunctionDecl *Decl,
86381ad6265SDimitry Andric     ArrayRef<TemplateArgument> TemplateArgs,
86481ad6265SDimitry Andric     ConstraintSatisfaction &Satisfaction) {
86581ad6265SDimitry Andric   // In most cases we're not going to have constraints, so check for that first.
86681ad6265SDimitry Andric   FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
86781ad6265SDimitry Andric   // Note - code synthesis context for the constraints check is created
86881ad6265SDimitry Andric   // inside CheckConstraintsSatisfaction.
86981ad6265SDimitry Andric   SmallVector<const Expr *, 3> TemplateAC;
87081ad6265SDimitry Andric   Template->getAssociatedConstraints(TemplateAC);
87181ad6265SDimitry Andric   if (TemplateAC.empty()) {
87281ad6265SDimitry Andric     Satisfaction.IsSatisfied = true;
87381ad6265SDimitry Andric     return false;
87481ad6265SDimitry Andric   }
87581ad6265SDimitry Andric 
87681ad6265SDimitry Andric   // Enter the scope of this instantiation. We don't use
87781ad6265SDimitry Andric   // PushDeclContext because we don't have a scope.
87881ad6265SDimitry Andric   Sema::ContextRAII savedContext(*this, Decl);
87981ad6265SDimitry Andric   LocalInstantiationScope Scope(*this);
88081ad6265SDimitry Andric 
881bdd1243dSDimitry Andric   std::optional<MultiLevelTemplateArgumentList> MLTAL =
882bdd1243dSDimitry Andric       SetupConstraintCheckingTemplateArgumentsAndScope(Decl, TemplateArgs,
883bdd1243dSDimitry Andric                                                        Scope);
884bdd1243dSDimitry Andric 
885bdd1243dSDimitry Andric   if (!MLTAL)
88681ad6265SDimitry Andric     return true;
887bdd1243dSDimitry Andric 
88881ad6265SDimitry Andric   Qualifiers ThisQuals;
88981ad6265SDimitry Andric   CXXRecordDecl *Record = nullptr;
89081ad6265SDimitry Andric   if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
89181ad6265SDimitry Andric     ThisQuals = Method->getMethodQualifiers();
89281ad6265SDimitry Andric     Record = Method->getParent();
89381ad6265SDimitry Andric   }
894*feb5b0c7SDimitry Andric 
89581ad6265SDimitry Andric   CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
896*feb5b0c7SDimitry Andric   LambdaScopeForCallOperatorInstantiationRAII LambdaScope(
897*feb5b0c7SDimitry Andric       *this, const_cast<FunctionDecl *>(Decl), *MLTAL, Scope);
898bdd1243dSDimitry Andric 
899bdd1243dSDimitry Andric   llvm::SmallVector<Expr *, 1> Converted;
900bdd1243dSDimitry Andric   return CheckConstraintSatisfaction(Template, TemplateAC, Converted, *MLTAL,
90181ad6265SDimitry Andric                                      PointOfInstantiation, Satisfaction);
90281ad6265SDimitry Andric }
90381ad6265SDimitry Andric 
90455e4f9d5SDimitry Andric static void diagnoseUnsatisfiedRequirement(Sema &S,
90555e4f9d5SDimitry Andric                                            concepts::ExprRequirement *Req,
90655e4f9d5SDimitry Andric                                            bool First) {
90755e4f9d5SDimitry Andric   assert(!Req->isSatisfied()
90855e4f9d5SDimitry Andric          && "Diagnose() can only be used on an unsatisfied requirement");
90955e4f9d5SDimitry Andric   switch (Req->getSatisfactionStatus()) {
91055e4f9d5SDimitry Andric     case concepts::ExprRequirement::SS_Dependent:
91155e4f9d5SDimitry Andric       llvm_unreachable("Diagnosing a dependent requirement");
91255e4f9d5SDimitry Andric       break;
91355e4f9d5SDimitry Andric     case concepts::ExprRequirement::SS_ExprSubstitutionFailure: {
91455e4f9d5SDimitry Andric       auto *SubstDiag = Req->getExprSubstitutionDiagnostic();
91555e4f9d5SDimitry Andric       if (!SubstDiag->DiagMessage.empty())
91655e4f9d5SDimitry Andric         S.Diag(SubstDiag->DiagLoc,
91755e4f9d5SDimitry Andric                diag::note_expr_requirement_expr_substitution_error)
91855e4f9d5SDimitry Andric                << (int)First << SubstDiag->SubstitutedEntity
91955e4f9d5SDimitry Andric                << SubstDiag->DiagMessage;
92055e4f9d5SDimitry Andric       else
92155e4f9d5SDimitry Andric         S.Diag(SubstDiag->DiagLoc,
92255e4f9d5SDimitry Andric                diag::note_expr_requirement_expr_unknown_substitution_error)
92355e4f9d5SDimitry Andric             << (int)First << SubstDiag->SubstitutedEntity;
92455e4f9d5SDimitry Andric       break;
92555e4f9d5SDimitry Andric     }
92655e4f9d5SDimitry Andric     case concepts::ExprRequirement::SS_NoexceptNotMet:
92755e4f9d5SDimitry Andric       S.Diag(Req->getNoexceptLoc(),
92855e4f9d5SDimitry Andric              diag::note_expr_requirement_noexcept_not_met)
92955e4f9d5SDimitry Andric           << (int)First << Req->getExpr();
93055e4f9d5SDimitry Andric       break;
93155e4f9d5SDimitry Andric     case concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure: {
93255e4f9d5SDimitry Andric       auto *SubstDiag =
93355e4f9d5SDimitry Andric           Req->getReturnTypeRequirement().getSubstitutionDiagnostic();
93455e4f9d5SDimitry Andric       if (!SubstDiag->DiagMessage.empty())
93555e4f9d5SDimitry Andric         S.Diag(SubstDiag->DiagLoc,
93655e4f9d5SDimitry Andric                diag::note_expr_requirement_type_requirement_substitution_error)
93755e4f9d5SDimitry Andric             << (int)First << SubstDiag->SubstitutedEntity
93855e4f9d5SDimitry Andric             << SubstDiag->DiagMessage;
93955e4f9d5SDimitry Andric       else
94055e4f9d5SDimitry Andric         S.Diag(SubstDiag->DiagLoc,
94155e4f9d5SDimitry Andric                diag::note_expr_requirement_type_requirement_unknown_substitution_error)
94255e4f9d5SDimitry Andric             << (int)First << SubstDiag->SubstitutedEntity;
94355e4f9d5SDimitry Andric       break;
94455e4f9d5SDimitry Andric     }
94555e4f9d5SDimitry Andric     case concepts::ExprRequirement::SS_ConstraintsNotSatisfied: {
94655e4f9d5SDimitry Andric       ConceptSpecializationExpr *ConstraintExpr =
94755e4f9d5SDimitry Andric           Req->getReturnTypeRequirementSubstitutedConstraintExpr();
948fe6060f1SDimitry Andric       if (ConstraintExpr->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
94955e4f9d5SDimitry Andric         // A simple case - expr type is the type being constrained and the concept
95055e4f9d5SDimitry Andric         // was not provided arguments.
951fe6060f1SDimitry Andric         Expr *e = Req->getExpr();
952fe6060f1SDimitry Andric         S.Diag(e->getBeginLoc(),
95355e4f9d5SDimitry Andric                diag::note_expr_requirement_constraints_not_satisfied_simple)
954349cc55cSDimitry Andric             << (int)First << S.Context.getReferenceQualifiedType(e)
95555e4f9d5SDimitry Andric             << ConstraintExpr->getNamedConcept();
956fe6060f1SDimitry Andric       } else {
95755e4f9d5SDimitry Andric         S.Diag(ConstraintExpr->getBeginLoc(),
95855e4f9d5SDimitry Andric                diag::note_expr_requirement_constraints_not_satisfied)
95955e4f9d5SDimitry Andric             << (int)First << ConstraintExpr;
960fe6060f1SDimitry Andric       }
96155e4f9d5SDimitry Andric       S.DiagnoseUnsatisfiedConstraint(ConstraintExpr->getSatisfaction());
96255e4f9d5SDimitry Andric       break;
96355e4f9d5SDimitry Andric     }
96455e4f9d5SDimitry Andric     case concepts::ExprRequirement::SS_Satisfied:
96555e4f9d5SDimitry Andric       llvm_unreachable("We checked this above");
96655e4f9d5SDimitry Andric   }
96755e4f9d5SDimitry Andric }
96855e4f9d5SDimitry Andric 
96955e4f9d5SDimitry Andric static void diagnoseUnsatisfiedRequirement(Sema &S,
97055e4f9d5SDimitry Andric                                            concepts::TypeRequirement *Req,
97155e4f9d5SDimitry Andric                                            bool First) {
97255e4f9d5SDimitry Andric   assert(!Req->isSatisfied()
97355e4f9d5SDimitry Andric          && "Diagnose() can only be used on an unsatisfied requirement");
97455e4f9d5SDimitry Andric   switch (Req->getSatisfactionStatus()) {
97555e4f9d5SDimitry Andric   case concepts::TypeRequirement::SS_Dependent:
97655e4f9d5SDimitry Andric     llvm_unreachable("Diagnosing a dependent requirement");
97755e4f9d5SDimitry Andric     return;
97855e4f9d5SDimitry Andric   case concepts::TypeRequirement::SS_SubstitutionFailure: {
97955e4f9d5SDimitry Andric     auto *SubstDiag = Req->getSubstitutionDiagnostic();
98055e4f9d5SDimitry Andric     if (!SubstDiag->DiagMessage.empty())
98155e4f9d5SDimitry Andric       S.Diag(SubstDiag->DiagLoc,
98255e4f9d5SDimitry Andric              diag::note_type_requirement_substitution_error) << (int)First
98355e4f9d5SDimitry Andric           << SubstDiag->SubstitutedEntity << SubstDiag->DiagMessage;
98455e4f9d5SDimitry Andric     else
98555e4f9d5SDimitry Andric       S.Diag(SubstDiag->DiagLoc,
98655e4f9d5SDimitry Andric              diag::note_type_requirement_unknown_substitution_error)
98755e4f9d5SDimitry Andric           << (int)First << SubstDiag->SubstitutedEntity;
98855e4f9d5SDimitry Andric     return;
98955e4f9d5SDimitry Andric   }
99055e4f9d5SDimitry Andric   default:
99155e4f9d5SDimitry Andric     llvm_unreachable("Unknown satisfaction status");
99255e4f9d5SDimitry Andric     return;
99355e4f9d5SDimitry Andric   }
99455e4f9d5SDimitry Andric }
995bdd1243dSDimitry Andric static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S,
996bdd1243dSDimitry Andric                                                         Expr *SubstExpr,
997bdd1243dSDimitry Andric                                                         bool First = true);
99855e4f9d5SDimitry Andric 
99955e4f9d5SDimitry Andric static void diagnoseUnsatisfiedRequirement(Sema &S,
100055e4f9d5SDimitry Andric                                            concepts::NestedRequirement *Req,
100155e4f9d5SDimitry Andric                                            bool First) {
1002bdd1243dSDimitry Andric   using SubstitutionDiagnostic = std::pair<SourceLocation, StringRef>;
1003bdd1243dSDimitry Andric   for (auto &Pair : Req->getConstraintSatisfaction()) {
1004bdd1243dSDimitry Andric     if (auto *SubstDiag = Pair.second.dyn_cast<SubstitutionDiagnostic *>())
1005bdd1243dSDimitry Andric       S.Diag(SubstDiag->first, diag::note_nested_requirement_substitution_error)
1006bdd1243dSDimitry Andric           << (int)First << Req->getInvalidConstraintEntity() << SubstDiag->second;
100755e4f9d5SDimitry Andric     else
1008bdd1243dSDimitry Andric       diagnoseWellFormedUnsatisfiedConstraintExpr(
1009bdd1243dSDimitry Andric           S, Pair.second.dyn_cast<Expr *>(), First);
1010bdd1243dSDimitry Andric     First = false;
101155e4f9d5SDimitry Andric   }
101255e4f9d5SDimitry Andric }
101355e4f9d5SDimitry Andric 
1014480093f4SDimitry Andric static void diagnoseWellFormedUnsatisfiedConstraintExpr(Sema &S,
1015480093f4SDimitry Andric                                                         Expr *SubstExpr,
1016bdd1243dSDimitry Andric                                                         bool First) {
1017480093f4SDimitry Andric   SubstExpr = SubstExpr->IgnoreParenImpCasts();
1018480093f4SDimitry Andric   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SubstExpr)) {
1019480093f4SDimitry Andric     switch (BO->getOpcode()) {
1020480093f4SDimitry Andric     // These two cases will in practice only be reached when using fold
1021480093f4SDimitry Andric     // expressions with || and &&, since otherwise the || and && will have been
1022480093f4SDimitry Andric     // broken down into atomic constraints during satisfaction checking.
1023480093f4SDimitry Andric     case BO_LOr:
1024480093f4SDimitry Andric       // Or evaluated to false - meaning both RHS and LHS evaluated to false.
1025480093f4SDimitry Andric       diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
1026480093f4SDimitry Andric       diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
1027480093f4SDimitry Andric                                                   /*First=*/false);
1028480093f4SDimitry Andric       return;
1029fe6060f1SDimitry Andric     case BO_LAnd: {
1030fe6060f1SDimitry Andric       bool LHSSatisfied =
1031fe6060f1SDimitry Andric           BO->getLHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1032480093f4SDimitry Andric       if (LHSSatisfied) {
1033480093f4SDimitry Andric         // LHS is true, so RHS must be false.
1034480093f4SDimitry Andric         diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(), First);
1035480093f4SDimitry Andric         return;
1036480093f4SDimitry Andric       }
1037480093f4SDimitry Andric       // LHS is false
1038480093f4SDimitry Andric       diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getLHS(), First);
1039480093f4SDimitry Andric 
1040480093f4SDimitry Andric       // RHS might also be false
1041fe6060f1SDimitry Andric       bool RHSSatisfied =
1042fe6060f1SDimitry Andric           BO->getRHS()->EvaluateKnownConstInt(S.Context).getBoolValue();
1043480093f4SDimitry Andric       if (!RHSSatisfied)
1044480093f4SDimitry Andric         diagnoseWellFormedUnsatisfiedConstraintExpr(S, BO->getRHS(),
1045480093f4SDimitry Andric                                                     /*First=*/false);
1046480093f4SDimitry Andric       return;
1047fe6060f1SDimitry Andric     }
1048480093f4SDimitry Andric     case BO_GE:
1049480093f4SDimitry Andric     case BO_LE:
1050480093f4SDimitry Andric     case BO_GT:
1051480093f4SDimitry Andric     case BO_LT:
1052480093f4SDimitry Andric     case BO_EQ:
1053480093f4SDimitry Andric     case BO_NE:
1054480093f4SDimitry Andric       if (BO->getLHS()->getType()->isIntegerType() &&
1055480093f4SDimitry Andric           BO->getRHS()->getType()->isIntegerType()) {
1056480093f4SDimitry Andric         Expr::EvalResult SimplifiedLHS;
1057480093f4SDimitry Andric         Expr::EvalResult SimplifiedRHS;
1058fe6060f1SDimitry Andric         BO->getLHS()->EvaluateAsInt(SimplifiedLHS, S.Context,
1059fe6060f1SDimitry Andric                                     Expr::SE_NoSideEffects,
1060fe6060f1SDimitry Andric                                     /*InConstantContext=*/true);
1061fe6060f1SDimitry Andric         BO->getRHS()->EvaluateAsInt(SimplifiedRHS, S.Context,
1062fe6060f1SDimitry Andric                                     Expr::SE_NoSideEffects,
1063fe6060f1SDimitry Andric                                     /*InConstantContext=*/true);
1064480093f4SDimitry Andric         if (!SimplifiedLHS.Diag && ! SimplifiedRHS.Diag) {
1065480093f4SDimitry Andric           S.Diag(SubstExpr->getBeginLoc(),
1066480093f4SDimitry Andric                  diag::note_atomic_constraint_evaluated_to_false_elaborated)
1067480093f4SDimitry Andric               << (int)First << SubstExpr
1068fe6060f1SDimitry Andric               << toString(SimplifiedLHS.Val.getInt(), 10)
1069480093f4SDimitry Andric               << BinaryOperator::getOpcodeStr(BO->getOpcode())
1070fe6060f1SDimitry Andric               << toString(SimplifiedRHS.Val.getInt(), 10);
1071480093f4SDimitry Andric           return;
1072480093f4SDimitry Andric         }
1073480093f4SDimitry Andric       }
1074480093f4SDimitry Andric       break;
1075480093f4SDimitry Andric 
1076480093f4SDimitry Andric     default:
1077480093f4SDimitry Andric       break;
1078480093f4SDimitry Andric     }
1079480093f4SDimitry Andric   } else if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(SubstExpr)) {
1080480093f4SDimitry Andric     if (CSE->getTemplateArgsAsWritten()->NumTemplateArgs == 1) {
1081480093f4SDimitry Andric       S.Diag(
1082480093f4SDimitry Andric           CSE->getSourceRange().getBegin(),
1083480093f4SDimitry Andric           diag::
1084480093f4SDimitry Andric           note_single_arg_concept_specialization_constraint_evaluated_to_false)
1085480093f4SDimitry Andric           << (int)First
1086480093f4SDimitry Andric           << CSE->getTemplateArgsAsWritten()->arguments()[0].getArgument()
1087480093f4SDimitry Andric           << CSE->getNamedConcept();
1088480093f4SDimitry Andric     } else {
1089480093f4SDimitry Andric       S.Diag(SubstExpr->getSourceRange().getBegin(),
1090480093f4SDimitry Andric              diag::note_concept_specialization_constraint_evaluated_to_false)
1091480093f4SDimitry Andric           << (int)First << CSE;
1092480093f4SDimitry Andric     }
1093480093f4SDimitry Andric     S.DiagnoseUnsatisfiedConstraint(CSE->getSatisfaction());
1094480093f4SDimitry Andric     return;
109555e4f9d5SDimitry Andric   } else if (auto *RE = dyn_cast<RequiresExpr>(SubstExpr)) {
1096bdd1243dSDimitry Andric     // FIXME: RequiresExpr should store dependent diagnostics.
109755e4f9d5SDimitry Andric     for (concepts::Requirement *Req : RE->getRequirements())
109855e4f9d5SDimitry Andric       if (!Req->isDependent() && !Req->isSatisfied()) {
109955e4f9d5SDimitry Andric         if (auto *E = dyn_cast<concepts::ExprRequirement>(Req))
110055e4f9d5SDimitry Andric           diagnoseUnsatisfiedRequirement(S, E, First);
110155e4f9d5SDimitry Andric         else if (auto *T = dyn_cast<concepts::TypeRequirement>(Req))
110255e4f9d5SDimitry Andric           diagnoseUnsatisfiedRequirement(S, T, First);
110355e4f9d5SDimitry Andric         else
110455e4f9d5SDimitry Andric           diagnoseUnsatisfiedRequirement(
110555e4f9d5SDimitry Andric               S, cast<concepts::NestedRequirement>(Req), First);
110655e4f9d5SDimitry Andric         break;
110755e4f9d5SDimitry Andric       }
110855e4f9d5SDimitry Andric     return;
1109480093f4SDimitry Andric   }
1110480093f4SDimitry Andric 
1111480093f4SDimitry Andric   S.Diag(SubstExpr->getSourceRange().getBegin(),
1112480093f4SDimitry Andric          diag::note_atomic_constraint_evaluated_to_false)
1113480093f4SDimitry Andric       << (int)First << SubstExpr;
1114480093f4SDimitry Andric }
1115480093f4SDimitry Andric 
1116480093f4SDimitry Andric template<typename SubstitutionDiagnostic>
1117480093f4SDimitry Andric static void diagnoseUnsatisfiedConstraintExpr(
1118480093f4SDimitry Andric     Sema &S, const Expr *E,
1119480093f4SDimitry Andric     const llvm::PointerUnion<Expr *, SubstitutionDiagnostic *> &Record,
1120480093f4SDimitry Andric     bool First = true) {
1121480093f4SDimitry Andric   if (auto *Diag = Record.template dyn_cast<SubstitutionDiagnostic *>()){
1122480093f4SDimitry Andric     S.Diag(Diag->first, diag::note_substituted_constraint_expr_is_ill_formed)
1123480093f4SDimitry Andric         << Diag->second;
1124480093f4SDimitry Andric     return;
1125480093f4SDimitry Andric   }
1126480093f4SDimitry Andric 
1127480093f4SDimitry Andric   diagnoseWellFormedUnsatisfiedConstraintExpr(S,
1128480093f4SDimitry Andric       Record.template get<Expr *>(), First);
1129480093f4SDimitry Andric }
1130480093f4SDimitry Andric 
113155e4f9d5SDimitry Andric void
113255e4f9d5SDimitry Andric Sema::DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction& Satisfaction,
113355e4f9d5SDimitry Andric                                     bool First) {
1134480093f4SDimitry Andric   assert(!Satisfaction.IsSatisfied &&
1135480093f4SDimitry Andric          "Attempted to diagnose a satisfied constraint");
1136480093f4SDimitry Andric   for (auto &Pair : Satisfaction.Details) {
1137480093f4SDimitry Andric     diagnoseUnsatisfiedConstraintExpr(*this, Pair.first, Pair.second, First);
1138480093f4SDimitry Andric     First = false;
1139480093f4SDimitry Andric   }
1140480093f4SDimitry Andric }
1141480093f4SDimitry Andric 
1142480093f4SDimitry Andric void Sema::DiagnoseUnsatisfiedConstraint(
114355e4f9d5SDimitry Andric     const ASTConstraintSatisfaction &Satisfaction,
114455e4f9d5SDimitry Andric     bool First) {
1145480093f4SDimitry Andric   assert(!Satisfaction.IsSatisfied &&
1146480093f4SDimitry Andric          "Attempted to diagnose a satisfied constraint");
1147480093f4SDimitry Andric   for (auto &Pair : Satisfaction) {
1148480093f4SDimitry Andric     diagnoseUnsatisfiedConstraintExpr(*this, Pair.first, Pair.second, First);
1149480093f4SDimitry Andric     First = false;
1150480093f4SDimitry Andric   }
1151480093f4SDimitry Andric }
1152480093f4SDimitry Andric 
1153480093f4SDimitry Andric const NormalizedConstraint *
1154480093f4SDimitry Andric Sema::getNormalizedAssociatedConstraints(
1155480093f4SDimitry Andric     NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints) {
115606c3fb27SDimitry Andric   // In case the ConstrainedDecl comes from modules, it is necessary to use
115706c3fb27SDimitry Andric   // the canonical decl to avoid different atomic constraints with the 'same'
115806c3fb27SDimitry Andric   // declarations.
115906c3fb27SDimitry Andric   ConstrainedDecl = cast<NamedDecl>(ConstrainedDecl->getCanonicalDecl());
116006c3fb27SDimitry Andric 
1161480093f4SDimitry Andric   auto CacheEntry = NormalizationCache.find(ConstrainedDecl);
1162480093f4SDimitry Andric   if (CacheEntry == NormalizationCache.end()) {
1163480093f4SDimitry Andric     auto Normalized =
1164480093f4SDimitry Andric         NormalizedConstraint::fromConstraintExprs(*this, ConstrainedDecl,
1165480093f4SDimitry Andric                                                   AssociatedConstraints);
1166480093f4SDimitry Andric     CacheEntry =
1167480093f4SDimitry Andric         NormalizationCache
1168480093f4SDimitry Andric             .try_emplace(ConstrainedDecl,
1169480093f4SDimitry Andric                          Normalized
1170480093f4SDimitry Andric                              ? new (Context) NormalizedConstraint(
1171480093f4SDimitry Andric                                  std::move(*Normalized))
1172480093f4SDimitry Andric                              : nullptr)
1173480093f4SDimitry Andric             .first;
1174480093f4SDimitry Andric   }
1175480093f4SDimitry Andric   return CacheEntry->second;
1176480093f4SDimitry Andric }
1177480093f4SDimitry Andric 
1178bdd1243dSDimitry Andric static bool
1179bdd1243dSDimitry Andric substituteParameterMappings(Sema &S, NormalizedConstraint &N,
1180bdd1243dSDimitry Andric                             ConceptDecl *Concept,
1181bdd1243dSDimitry Andric                             const MultiLevelTemplateArgumentList &MLTAL,
1182480093f4SDimitry Andric                             const ASTTemplateArgumentListInfo *ArgsAsWritten) {
1183480093f4SDimitry Andric   if (!N.isAtomic()) {
1184bdd1243dSDimitry Andric     if (substituteParameterMappings(S, N.getLHS(), Concept, MLTAL,
1185480093f4SDimitry Andric                                     ArgsAsWritten))
1186480093f4SDimitry Andric       return true;
1187bdd1243dSDimitry Andric     return substituteParameterMappings(S, N.getRHS(), Concept, MLTAL,
1188480093f4SDimitry Andric                                        ArgsAsWritten);
1189480093f4SDimitry Andric   }
1190480093f4SDimitry Andric   TemplateParameterList *TemplateParams = Concept->getTemplateParameters();
1191480093f4SDimitry Andric 
1192480093f4SDimitry Andric   AtomicConstraint &Atomic = *N.getAtomicConstraint();
1193480093f4SDimitry Andric   TemplateArgumentListInfo SubstArgs;
1194480093f4SDimitry Andric   if (!Atomic.ParameterMapping) {
1195480093f4SDimitry Andric     llvm::SmallBitVector OccurringIndices(TemplateParams->size());
1196480093f4SDimitry Andric     S.MarkUsedTemplateParameters(Atomic.ConstraintExpr, /*OnlyDeduced=*/false,
1197480093f4SDimitry Andric                                  /*Depth=*/0, OccurringIndices);
1198bdd1243dSDimitry Andric     TemplateArgumentLoc *TempArgs =
1199bdd1243dSDimitry Andric         new (S.Context) TemplateArgumentLoc[OccurringIndices.count()];
1200480093f4SDimitry Andric     for (unsigned I = 0, J = 0, C = TemplateParams->size(); I != C; ++I)
1201480093f4SDimitry Andric       if (OccurringIndices[I])
1202bdd1243dSDimitry Andric         new (&(TempArgs)[J++])
1203bdd1243dSDimitry Andric             TemplateArgumentLoc(S.getIdentityTemplateArgumentLoc(
1204bdd1243dSDimitry Andric                 TemplateParams->begin()[I],
1205480093f4SDimitry Andric                 // Here we assume we do not support things like
1206480093f4SDimitry Andric                 // template<typename A, typename B>
1207480093f4SDimitry Andric                 // concept C = ...;
1208480093f4SDimitry Andric                 //
1209480093f4SDimitry Andric                 // template<typename... Ts> requires C<Ts...>
1210480093f4SDimitry Andric                 // struct S { };
1211480093f4SDimitry Andric                 // The above currently yields a diagnostic.
1212480093f4SDimitry Andric                 // We still might have default arguments for concept parameters.
1213bdd1243dSDimitry Andric                 ArgsAsWritten->NumTemplateArgs > I
1214bdd1243dSDimitry Andric                     ? ArgsAsWritten->arguments()[I].getLocation()
1215bdd1243dSDimitry Andric                     : SourceLocation()));
1216bdd1243dSDimitry Andric     Atomic.ParameterMapping.emplace(TempArgs,  OccurringIndices.count());
1217480093f4SDimitry Andric   }
1218480093f4SDimitry Andric   Sema::InstantiatingTemplate Inst(
1219480093f4SDimitry Andric       S, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),
1220480093f4SDimitry Andric       Sema::InstantiatingTemplate::ParameterMappingSubstitution{}, Concept,
12211ac55f4cSDimitry Andric       ArgsAsWritten->arguments().front().getSourceRange());
1222480093f4SDimitry Andric   if (S.SubstTemplateArguments(*Atomic.ParameterMapping, MLTAL, SubstArgs))
1223480093f4SDimitry Andric     return true;
1224bdd1243dSDimitry Andric 
1225bdd1243dSDimitry Andric   TemplateArgumentLoc *TempArgs =
1226bdd1243dSDimitry Andric       new (S.Context) TemplateArgumentLoc[SubstArgs.size()];
1227480093f4SDimitry Andric   std::copy(SubstArgs.arguments().begin(), SubstArgs.arguments().end(),
1228bdd1243dSDimitry Andric             TempArgs);
1229bdd1243dSDimitry Andric   Atomic.ParameterMapping.emplace(TempArgs, SubstArgs.size());
1230480093f4SDimitry Andric   return false;
1231480093f4SDimitry Andric }
1232480093f4SDimitry Andric 
1233bdd1243dSDimitry Andric static bool substituteParameterMappings(Sema &S, NormalizedConstraint &N,
1234bdd1243dSDimitry Andric                                         const ConceptSpecializationExpr *CSE) {
1235bdd1243dSDimitry Andric   TemplateArgumentList TAL{TemplateArgumentList::OnStack,
1236bdd1243dSDimitry Andric                            CSE->getTemplateArguments()};
1237bdd1243dSDimitry Andric   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
1238bdd1243dSDimitry Andric       CSE->getNamedConcept(), /*Final=*/false, &TAL,
1239bdd1243dSDimitry Andric       /*RelativeToPrimary=*/true,
1240bdd1243dSDimitry Andric       /*Pattern=*/nullptr,
1241bdd1243dSDimitry Andric       /*ForConstraintInstantiation=*/true);
1242bdd1243dSDimitry Andric 
1243bdd1243dSDimitry Andric   return substituteParameterMappings(S, N, CSE->getNamedConcept(), MLTAL,
1244bdd1243dSDimitry Andric                                      CSE->getTemplateArgsAsWritten());
1245bdd1243dSDimitry Andric }
1246bdd1243dSDimitry Andric 
1247bdd1243dSDimitry Andric std::optional<NormalizedConstraint>
1248480093f4SDimitry Andric NormalizedConstraint::fromConstraintExprs(Sema &S, NamedDecl *D,
1249480093f4SDimitry Andric                                           ArrayRef<const Expr *> E) {
1250480093f4SDimitry Andric   assert(E.size() != 0);
12516e75b2fbSDimitry Andric   auto Conjunction = fromConstraintExpr(S, D, E[0]);
12526e75b2fbSDimitry Andric   if (!Conjunction)
1253bdd1243dSDimitry Andric     return std::nullopt;
12546e75b2fbSDimitry Andric   for (unsigned I = 1; I < E.size(); ++I) {
1255480093f4SDimitry Andric     auto Next = fromConstraintExpr(S, D, E[I]);
1256480093f4SDimitry Andric     if (!Next)
1257bdd1243dSDimitry Andric       return std::nullopt;
12586e75b2fbSDimitry Andric     *Conjunction = NormalizedConstraint(S.Context, std::move(*Conjunction),
1259480093f4SDimitry Andric                                         std::move(*Next), CCK_Conjunction);
1260480093f4SDimitry Andric   }
1261480093f4SDimitry Andric   return Conjunction;
1262480093f4SDimitry Andric }
1263480093f4SDimitry Andric 
1264bdd1243dSDimitry Andric std::optional<NormalizedConstraint>
1265480093f4SDimitry Andric NormalizedConstraint::fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E) {
1266480093f4SDimitry Andric   assert(E != nullptr);
1267480093f4SDimitry Andric 
1268480093f4SDimitry Andric   // C++ [temp.constr.normal]p1.1
1269480093f4SDimitry Andric   // [...]
1270480093f4SDimitry Andric   // - The normal form of an expression (E) is the normal form of E.
1271480093f4SDimitry Andric   // [...]
1272480093f4SDimitry Andric   E = E->IgnoreParenImpCasts();
1273bdd1243dSDimitry Andric 
1274bdd1243dSDimitry Andric   // C++2a [temp.param]p4:
1275bdd1243dSDimitry Andric   //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1276bdd1243dSDimitry Andric   // Fold expression is considered atomic constraints per current wording.
1277bdd1243dSDimitry Andric   // See http://cplusplus.github.io/concepts-ts/ts-active.html#28
1278bdd1243dSDimitry Andric 
12795ffd83dbSDimitry Andric   if (LogicalBinOp BO = E) {
12805ffd83dbSDimitry Andric     auto LHS = fromConstraintExpr(S, D, BO.getLHS());
1281480093f4SDimitry Andric     if (!LHS)
1282bdd1243dSDimitry Andric       return std::nullopt;
12835ffd83dbSDimitry Andric     auto RHS = fromConstraintExpr(S, D, BO.getRHS());
1284480093f4SDimitry Andric     if (!RHS)
1285bdd1243dSDimitry Andric       return std::nullopt;
1286480093f4SDimitry Andric 
12875ffd83dbSDimitry Andric     return NormalizedConstraint(S.Context, std::move(*LHS), std::move(*RHS),
12885ffd83dbSDimitry Andric                                 BO.isAnd() ? CCK_Conjunction : CCK_Disjunction);
1289480093f4SDimitry Andric   } else if (auto *CSE = dyn_cast<const ConceptSpecializationExpr>(E)) {
1290480093f4SDimitry Andric     const NormalizedConstraint *SubNF;
1291480093f4SDimitry Andric     {
1292480093f4SDimitry Andric       Sema::InstantiatingTemplate Inst(
1293480093f4SDimitry Andric           S, CSE->getExprLoc(),
1294480093f4SDimitry Andric           Sema::InstantiatingTemplate::ConstraintNormalization{}, D,
1295480093f4SDimitry Andric           CSE->getSourceRange());
1296480093f4SDimitry Andric       // C++ [temp.constr.normal]p1.1
1297480093f4SDimitry Andric       // [...]
1298480093f4SDimitry Andric       // The normal form of an id-expression of the form C<A1, A2, ..., AN>,
1299480093f4SDimitry Andric       // where C names a concept, is the normal form of the
1300480093f4SDimitry Andric       // constraint-expression of C, after substituting A1, A2, ..., AN for C’s
1301480093f4SDimitry Andric       // respective template parameters in the parameter mappings in each atomic
1302480093f4SDimitry Andric       // constraint. If any such substitution results in an invalid type or
1303480093f4SDimitry Andric       // expression, the program is ill-formed; no diagnostic is required.
1304480093f4SDimitry Andric       // [...]
1305480093f4SDimitry Andric       ConceptDecl *CD = CSE->getNamedConcept();
1306480093f4SDimitry Andric       SubNF = S.getNormalizedAssociatedConstraints(CD,
1307480093f4SDimitry Andric                                                    {CD->getConstraintExpr()});
1308480093f4SDimitry Andric       if (!SubNF)
1309bdd1243dSDimitry Andric         return std::nullopt;
1310480093f4SDimitry Andric     }
1311480093f4SDimitry Andric 
1312bdd1243dSDimitry Andric     std::optional<NormalizedConstraint> New;
1313480093f4SDimitry Andric     New.emplace(S.Context, *SubNF);
1314480093f4SDimitry Andric 
1315bdd1243dSDimitry Andric     if (substituteParameterMappings(S, *New, CSE))
1316bdd1243dSDimitry Andric       return std::nullopt;
1317480093f4SDimitry Andric 
1318480093f4SDimitry Andric     return New;
1319480093f4SDimitry Andric   }
1320480093f4SDimitry Andric   return NormalizedConstraint{new (S.Context) AtomicConstraint(S, E)};
1321480093f4SDimitry Andric }
1322480093f4SDimitry Andric 
1323480093f4SDimitry Andric using NormalForm =
1324480093f4SDimitry Andric     llvm::SmallVector<llvm::SmallVector<AtomicConstraint *, 2>, 4>;
1325480093f4SDimitry Andric 
1326480093f4SDimitry Andric static NormalForm makeCNF(const NormalizedConstraint &Normalized) {
1327480093f4SDimitry Andric   if (Normalized.isAtomic())
1328480093f4SDimitry Andric     return {{Normalized.getAtomicConstraint()}};
1329480093f4SDimitry Andric 
1330480093f4SDimitry Andric   NormalForm LCNF = makeCNF(Normalized.getLHS());
1331480093f4SDimitry Andric   NormalForm RCNF = makeCNF(Normalized.getRHS());
1332480093f4SDimitry Andric   if (Normalized.getCompoundKind() == NormalizedConstraint::CCK_Conjunction) {
1333480093f4SDimitry Andric     LCNF.reserve(LCNF.size() + RCNF.size());
1334480093f4SDimitry Andric     while (!RCNF.empty())
1335480093f4SDimitry Andric       LCNF.push_back(RCNF.pop_back_val());
1336480093f4SDimitry Andric     return LCNF;
1337480093f4SDimitry Andric   }
1338480093f4SDimitry Andric 
1339480093f4SDimitry Andric   // Disjunction
1340480093f4SDimitry Andric   NormalForm Res;
1341480093f4SDimitry Andric   Res.reserve(LCNF.size() * RCNF.size());
1342480093f4SDimitry Andric   for (auto &LDisjunction : LCNF)
1343480093f4SDimitry Andric     for (auto &RDisjunction : RCNF) {
1344480093f4SDimitry Andric       NormalForm::value_type Combined;
1345480093f4SDimitry Andric       Combined.reserve(LDisjunction.size() + RDisjunction.size());
1346480093f4SDimitry Andric       std::copy(LDisjunction.begin(), LDisjunction.end(),
1347480093f4SDimitry Andric                 std::back_inserter(Combined));
1348480093f4SDimitry Andric       std::copy(RDisjunction.begin(), RDisjunction.end(),
1349480093f4SDimitry Andric                 std::back_inserter(Combined));
1350480093f4SDimitry Andric       Res.emplace_back(Combined);
1351480093f4SDimitry Andric     }
1352480093f4SDimitry Andric   return Res;
1353480093f4SDimitry Andric }
1354480093f4SDimitry Andric 
1355480093f4SDimitry Andric static NormalForm makeDNF(const NormalizedConstraint &Normalized) {
1356480093f4SDimitry Andric   if (Normalized.isAtomic())
1357480093f4SDimitry Andric     return {{Normalized.getAtomicConstraint()}};
1358480093f4SDimitry Andric 
1359480093f4SDimitry Andric   NormalForm LDNF = makeDNF(Normalized.getLHS());
1360480093f4SDimitry Andric   NormalForm RDNF = makeDNF(Normalized.getRHS());
1361480093f4SDimitry Andric   if (Normalized.getCompoundKind() == NormalizedConstraint::CCK_Disjunction) {
1362480093f4SDimitry Andric     LDNF.reserve(LDNF.size() + RDNF.size());
1363480093f4SDimitry Andric     while (!RDNF.empty())
1364480093f4SDimitry Andric       LDNF.push_back(RDNF.pop_back_val());
1365480093f4SDimitry Andric     return LDNF;
1366480093f4SDimitry Andric   }
1367480093f4SDimitry Andric 
1368480093f4SDimitry Andric   // Conjunction
1369480093f4SDimitry Andric   NormalForm Res;
1370480093f4SDimitry Andric   Res.reserve(LDNF.size() * RDNF.size());
1371480093f4SDimitry Andric   for (auto &LConjunction : LDNF) {
1372480093f4SDimitry Andric     for (auto &RConjunction : RDNF) {
1373480093f4SDimitry Andric       NormalForm::value_type Combined;
1374480093f4SDimitry Andric       Combined.reserve(LConjunction.size() + RConjunction.size());
1375480093f4SDimitry Andric       std::copy(LConjunction.begin(), LConjunction.end(),
1376480093f4SDimitry Andric                 std::back_inserter(Combined));
1377480093f4SDimitry Andric       std::copy(RConjunction.begin(), RConjunction.end(),
1378480093f4SDimitry Andric                 std::back_inserter(Combined));
1379480093f4SDimitry Andric       Res.emplace_back(Combined);
1380480093f4SDimitry Andric     }
1381480093f4SDimitry Andric   }
1382480093f4SDimitry Andric   return Res;
1383480093f4SDimitry Andric }
1384480093f4SDimitry Andric 
1385480093f4SDimitry Andric template<typename AtomicSubsumptionEvaluator>
138606c3fb27SDimitry Andric static bool subsumes(const NormalForm &PDNF, const NormalForm &QCNF,
1387480093f4SDimitry Andric                      AtomicSubsumptionEvaluator E) {
1388480093f4SDimitry Andric   // C++ [temp.constr.order] p2
1389480093f4SDimitry Andric   //   Then, P subsumes Q if and only if, for every disjunctive clause Pi in the
1390480093f4SDimitry Andric   //   disjunctive normal form of P, Pi subsumes every conjunctive clause Qj in
1391480093f4SDimitry Andric   //   the conjuctive normal form of Q, where [...]
1392480093f4SDimitry Andric   for (const auto &Pi : PDNF) {
1393480093f4SDimitry Andric     for (const auto &Qj : QCNF) {
1394480093f4SDimitry Andric       // C++ [temp.constr.order] p2
1395480093f4SDimitry Andric       //   - [...] a disjunctive clause Pi subsumes a conjunctive clause Qj if
1396480093f4SDimitry Andric       //     and only if there exists an atomic constraint Pia in Pi for which
1397480093f4SDimitry Andric       //     there exists an atomic constraint, Qjb, in Qj such that Pia
1398480093f4SDimitry Andric       //     subsumes Qjb.
1399480093f4SDimitry Andric       bool Found = false;
1400480093f4SDimitry Andric       for (const AtomicConstraint *Pia : Pi) {
1401480093f4SDimitry Andric         for (const AtomicConstraint *Qjb : Qj) {
1402480093f4SDimitry Andric           if (E(*Pia, *Qjb)) {
1403480093f4SDimitry Andric             Found = true;
1404480093f4SDimitry Andric             break;
1405480093f4SDimitry Andric           }
1406480093f4SDimitry Andric         }
1407480093f4SDimitry Andric         if (Found)
1408480093f4SDimitry Andric           break;
1409480093f4SDimitry Andric       }
1410480093f4SDimitry Andric       if (!Found)
1411480093f4SDimitry Andric         return false;
1412480093f4SDimitry Andric     }
1413480093f4SDimitry Andric   }
1414480093f4SDimitry Andric   return true;
1415480093f4SDimitry Andric }
1416480093f4SDimitry Andric 
1417480093f4SDimitry Andric template<typename AtomicSubsumptionEvaluator>
1418480093f4SDimitry Andric static bool subsumes(Sema &S, NamedDecl *DP, ArrayRef<const Expr *> P,
1419480093f4SDimitry Andric                      NamedDecl *DQ, ArrayRef<const Expr *> Q, bool &Subsumes,
1420480093f4SDimitry Andric                      AtomicSubsumptionEvaluator E) {
1421480093f4SDimitry Andric   // C++ [temp.constr.order] p2
1422480093f4SDimitry Andric   //   In order to determine if a constraint P subsumes a constraint Q, P is
1423480093f4SDimitry Andric   //   transformed into disjunctive normal form, and Q is transformed into
1424480093f4SDimitry Andric   //   conjunctive normal form. [...]
1425480093f4SDimitry Andric   auto *PNormalized = S.getNormalizedAssociatedConstraints(DP, P);
1426480093f4SDimitry Andric   if (!PNormalized)
1427480093f4SDimitry Andric     return true;
1428480093f4SDimitry Andric   const NormalForm PDNF = makeDNF(*PNormalized);
1429480093f4SDimitry Andric 
1430480093f4SDimitry Andric   auto *QNormalized = S.getNormalizedAssociatedConstraints(DQ, Q);
1431480093f4SDimitry Andric   if (!QNormalized)
1432480093f4SDimitry Andric     return true;
1433480093f4SDimitry Andric   const NormalForm QCNF = makeCNF(*QNormalized);
1434480093f4SDimitry Andric 
1435480093f4SDimitry Andric   Subsumes = subsumes(PDNF, QCNF, E);
1436480093f4SDimitry Andric   return false;
1437480093f4SDimitry Andric }
1438480093f4SDimitry Andric 
1439bdd1243dSDimitry Andric bool Sema::IsAtLeastAsConstrained(NamedDecl *D1,
1440bdd1243dSDimitry Andric                                   MutableArrayRef<const Expr *> AC1,
1441bdd1243dSDimitry Andric                                   NamedDecl *D2,
1442bdd1243dSDimitry Andric                                   MutableArrayRef<const Expr *> AC2,
1443480093f4SDimitry Andric                                   bool &Result) {
1444bdd1243dSDimitry Andric   if (const auto *FD1 = dyn_cast<FunctionDecl>(D1)) {
1445bdd1243dSDimitry Andric     auto IsExpectedEntity = [](const FunctionDecl *FD) {
1446bdd1243dSDimitry Andric       FunctionDecl::TemplatedKind Kind = FD->getTemplatedKind();
1447bdd1243dSDimitry Andric       return Kind == FunctionDecl::TK_NonTemplate ||
1448bdd1243dSDimitry Andric              Kind == FunctionDecl::TK_FunctionTemplate;
1449bdd1243dSDimitry Andric     };
1450bdd1243dSDimitry Andric     const auto *FD2 = dyn_cast<FunctionDecl>(D2);
1451bdd1243dSDimitry Andric     (void)IsExpectedEntity;
1452bdd1243dSDimitry Andric     (void)FD1;
1453bdd1243dSDimitry Andric     (void)FD2;
1454bdd1243dSDimitry Andric     assert(IsExpectedEntity(FD1) && FD2 && IsExpectedEntity(FD2) &&
1455bdd1243dSDimitry Andric            "use non-instantiated function declaration for constraints partial "
1456bdd1243dSDimitry Andric            "ordering");
1457bdd1243dSDimitry Andric   }
1458bdd1243dSDimitry Andric 
1459480093f4SDimitry Andric   if (AC1.empty()) {
1460480093f4SDimitry Andric     Result = AC2.empty();
1461480093f4SDimitry Andric     return false;
1462480093f4SDimitry Andric   }
1463480093f4SDimitry Andric   if (AC2.empty()) {
1464480093f4SDimitry Andric     // TD1 has associated constraints and TD2 does not.
1465480093f4SDimitry Andric     Result = true;
1466480093f4SDimitry Andric     return false;
1467480093f4SDimitry Andric   }
1468480093f4SDimitry Andric 
1469480093f4SDimitry Andric   std::pair<NamedDecl *, NamedDecl *> Key{D1, D2};
1470480093f4SDimitry Andric   auto CacheEntry = SubsumptionCache.find(Key);
1471480093f4SDimitry Andric   if (CacheEntry != SubsumptionCache.end()) {
1472480093f4SDimitry Andric     Result = CacheEntry->second;
1473480093f4SDimitry Andric     return false;
1474480093f4SDimitry Andric   }
1475480093f4SDimitry Andric 
1476bdd1243dSDimitry Andric   unsigned Depth1 = CalculateTemplateDepthForConstraints(*this, D1, true);
1477bdd1243dSDimitry Andric   unsigned Depth2 = CalculateTemplateDepthForConstraints(*this, D2, true);
1478bdd1243dSDimitry Andric 
1479bdd1243dSDimitry Andric   for (size_t I = 0; I != AC1.size() && I != AC2.size(); ++I) {
1480bdd1243dSDimitry Andric     if (Depth2 > Depth1) {
1481bdd1243dSDimitry Andric       AC1[I] = AdjustConstraintDepth(*this, Depth2 - Depth1)
1482bdd1243dSDimitry Andric                    .TransformExpr(const_cast<Expr *>(AC1[I]))
1483bdd1243dSDimitry Andric                    .get();
1484bdd1243dSDimitry Andric     } else if (Depth1 > Depth2) {
1485bdd1243dSDimitry Andric       AC2[I] = AdjustConstraintDepth(*this, Depth1 - Depth2)
1486bdd1243dSDimitry Andric                    .TransformExpr(const_cast<Expr *>(AC2[I]))
1487bdd1243dSDimitry Andric                    .get();
1488bdd1243dSDimitry Andric     }
1489bdd1243dSDimitry Andric   }
1490bdd1243dSDimitry Andric 
1491480093f4SDimitry Andric   if (subsumes(*this, D1, AC1, D2, AC2, Result,
1492480093f4SDimitry Andric         [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
1493480093f4SDimitry Andric           return A.subsumes(Context, B);
1494480093f4SDimitry Andric         }))
1495480093f4SDimitry Andric     return true;
1496480093f4SDimitry Andric   SubsumptionCache.try_emplace(Key, Result);
1497480093f4SDimitry Andric   return false;
1498480093f4SDimitry Andric }
1499480093f4SDimitry Andric 
1500480093f4SDimitry Andric bool Sema::MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
1501480093f4SDimitry Andric     ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2) {
1502480093f4SDimitry Andric   if (isSFINAEContext())
1503480093f4SDimitry Andric     // No need to work here because our notes would be discarded.
1504480093f4SDimitry Andric     return false;
1505480093f4SDimitry Andric 
1506480093f4SDimitry Andric   if (AC1.empty() || AC2.empty())
1507480093f4SDimitry Andric     return false;
1508480093f4SDimitry Andric 
1509480093f4SDimitry Andric   auto NormalExprEvaluator =
1510480093f4SDimitry Andric       [this] (const AtomicConstraint &A, const AtomicConstraint &B) {
1511480093f4SDimitry Andric         return A.subsumes(Context, B);
1512480093f4SDimitry Andric       };
1513480093f4SDimitry Andric 
1514480093f4SDimitry Andric   const Expr *AmbiguousAtomic1 = nullptr, *AmbiguousAtomic2 = nullptr;
1515480093f4SDimitry Andric   auto IdenticalExprEvaluator =
1516480093f4SDimitry Andric       [&] (const AtomicConstraint &A, const AtomicConstraint &B) {
1517480093f4SDimitry Andric         if (!A.hasMatchingParameterMapping(Context, B))
1518480093f4SDimitry Andric           return false;
1519480093f4SDimitry Andric         const Expr *EA = A.ConstraintExpr, *EB = B.ConstraintExpr;
1520480093f4SDimitry Andric         if (EA == EB)
1521480093f4SDimitry Andric           return true;
1522480093f4SDimitry Andric 
1523480093f4SDimitry Andric         // Not the same source level expression - are the expressions
1524480093f4SDimitry Andric         // identical?
1525480093f4SDimitry Andric         llvm::FoldingSetNodeID IDA, IDB;
1526349cc55cSDimitry Andric         EA->Profile(IDA, Context, /*Canonical=*/true);
1527349cc55cSDimitry Andric         EB->Profile(IDB, Context, /*Canonical=*/true);
1528480093f4SDimitry Andric         if (IDA != IDB)
1529480093f4SDimitry Andric           return false;
1530480093f4SDimitry Andric 
1531480093f4SDimitry Andric         AmbiguousAtomic1 = EA;
1532480093f4SDimitry Andric         AmbiguousAtomic2 = EB;
1533480093f4SDimitry Andric         return true;
1534480093f4SDimitry Andric       };
1535480093f4SDimitry Andric 
1536480093f4SDimitry Andric   {
1537480093f4SDimitry Andric     // The subsumption checks might cause diagnostics
1538480093f4SDimitry Andric     SFINAETrap Trap(*this);
1539480093f4SDimitry Andric     auto *Normalized1 = getNormalizedAssociatedConstraints(D1, AC1);
1540480093f4SDimitry Andric     if (!Normalized1)
1541480093f4SDimitry Andric       return false;
1542480093f4SDimitry Andric     const NormalForm DNF1 = makeDNF(*Normalized1);
1543480093f4SDimitry Andric     const NormalForm CNF1 = makeCNF(*Normalized1);
1544480093f4SDimitry Andric 
1545480093f4SDimitry Andric     auto *Normalized2 = getNormalizedAssociatedConstraints(D2, AC2);
1546480093f4SDimitry Andric     if (!Normalized2)
1547480093f4SDimitry Andric       return false;
1548480093f4SDimitry Andric     const NormalForm DNF2 = makeDNF(*Normalized2);
1549480093f4SDimitry Andric     const NormalForm CNF2 = makeCNF(*Normalized2);
1550480093f4SDimitry Andric 
1551480093f4SDimitry Andric     bool Is1AtLeastAs2Normally = subsumes(DNF1, CNF2, NormalExprEvaluator);
1552480093f4SDimitry Andric     bool Is2AtLeastAs1Normally = subsumes(DNF2, CNF1, NormalExprEvaluator);
1553480093f4SDimitry Andric     bool Is1AtLeastAs2 = subsumes(DNF1, CNF2, IdenticalExprEvaluator);
1554480093f4SDimitry Andric     bool Is2AtLeastAs1 = subsumes(DNF2, CNF1, IdenticalExprEvaluator);
1555480093f4SDimitry Andric     if (Is1AtLeastAs2 == Is1AtLeastAs2Normally &&
1556480093f4SDimitry Andric         Is2AtLeastAs1 == Is2AtLeastAs1Normally)
1557480093f4SDimitry Andric       // Same result - no ambiguity was caused by identical atomic expressions.
1558480093f4SDimitry Andric       return false;
1559480093f4SDimitry Andric   }
1560480093f4SDimitry Andric 
1561480093f4SDimitry Andric   // A different result! Some ambiguous atomic constraint(s) caused a difference
1562480093f4SDimitry Andric   assert(AmbiguousAtomic1 && AmbiguousAtomic2);
1563480093f4SDimitry Andric 
1564480093f4SDimitry Andric   Diag(AmbiguousAtomic1->getBeginLoc(), diag::note_ambiguous_atomic_constraints)
1565480093f4SDimitry Andric       << AmbiguousAtomic1->getSourceRange();
1566480093f4SDimitry Andric   Diag(AmbiguousAtomic2->getBeginLoc(),
1567480093f4SDimitry Andric        diag::note_ambiguous_atomic_constraints_similar_expression)
1568480093f4SDimitry Andric       << AmbiguousAtomic2->getSourceRange();
1569480093f4SDimitry Andric   return true;
1570480093f4SDimitry Andric }
157155e4f9d5SDimitry Andric 
157255e4f9d5SDimitry Andric concepts::ExprRequirement::ExprRequirement(
157355e4f9d5SDimitry Andric     Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
157455e4f9d5SDimitry Andric     ReturnTypeRequirement Req, SatisfactionStatus Status,
157555e4f9d5SDimitry Andric     ConceptSpecializationExpr *SubstitutedConstraintExpr) :
157655e4f9d5SDimitry Andric     Requirement(IsSimple ? RK_Simple : RK_Compound, Status == SS_Dependent,
157755e4f9d5SDimitry Andric                 Status == SS_Dependent &&
157855e4f9d5SDimitry Andric                 (E->containsUnexpandedParameterPack() ||
157955e4f9d5SDimitry Andric                  Req.containsUnexpandedParameterPack()),
158055e4f9d5SDimitry Andric                 Status == SS_Satisfied), Value(E), NoexceptLoc(NoexceptLoc),
158155e4f9d5SDimitry Andric     TypeReq(Req), SubstitutedConstraintExpr(SubstitutedConstraintExpr),
158255e4f9d5SDimitry Andric     Status(Status) {
158355e4f9d5SDimitry Andric   assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
158455e4f9d5SDimitry Andric          "Simple requirement must not have a return type requirement or a "
158555e4f9d5SDimitry Andric          "noexcept specification");
158655e4f9d5SDimitry Andric   assert((Status > SS_TypeRequirementSubstitutionFailure && Req.isTypeConstraint()) ==
158755e4f9d5SDimitry Andric          (SubstitutedConstraintExpr != nullptr));
158855e4f9d5SDimitry Andric }
158955e4f9d5SDimitry Andric 
159055e4f9d5SDimitry Andric concepts::ExprRequirement::ExprRequirement(
159155e4f9d5SDimitry Andric     SubstitutionDiagnostic *ExprSubstDiag, bool IsSimple,
159255e4f9d5SDimitry Andric     SourceLocation NoexceptLoc, ReturnTypeRequirement Req) :
159355e4f9d5SDimitry Andric     Requirement(IsSimple ? RK_Simple : RK_Compound, Req.isDependent(),
159455e4f9d5SDimitry Andric                 Req.containsUnexpandedParameterPack(), /*IsSatisfied=*/false),
159555e4f9d5SDimitry Andric     Value(ExprSubstDiag), NoexceptLoc(NoexceptLoc), TypeReq(Req),
159655e4f9d5SDimitry Andric     Status(SS_ExprSubstitutionFailure) {
159755e4f9d5SDimitry Andric   assert((!IsSimple || (Req.isEmpty() && NoexceptLoc.isInvalid())) &&
159855e4f9d5SDimitry Andric          "Simple requirement must not have a return type requirement or a "
159955e4f9d5SDimitry Andric          "noexcept specification");
160055e4f9d5SDimitry Andric }
160155e4f9d5SDimitry Andric 
160255e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement::
160355e4f9d5SDimitry Andric ReturnTypeRequirement(TemplateParameterList *TPL) :
160404eeddc0SDimitry Andric     TypeConstraintInfo(TPL, false) {
160555e4f9d5SDimitry Andric   assert(TPL->size() == 1);
160655e4f9d5SDimitry Andric   const TypeConstraint *TC =
160755e4f9d5SDimitry Andric       cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint();
160855e4f9d5SDimitry Andric   assert(TC &&
160955e4f9d5SDimitry Andric          "TPL must have a template type parameter with a type constraint");
161055e4f9d5SDimitry Andric   auto *Constraint =
1611349cc55cSDimitry Andric       cast<ConceptSpecializationExpr>(TC->getImmediatelyDeclaredConstraint());
1612e8d8bef9SDimitry Andric   bool Dependent =
1613e8d8bef9SDimitry Andric       Constraint->getTemplateArgsAsWritten() &&
1614e8d8bef9SDimitry Andric       TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
1615e8d8bef9SDimitry Andric           Constraint->getTemplateArgsAsWritten()->arguments().drop_front(1));
161604eeddc0SDimitry Andric   TypeConstraintInfo.setInt(Dependent ? true : false);
161755e4f9d5SDimitry Andric }
161855e4f9d5SDimitry Andric 
161955e4f9d5SDimitry Andric concepts::TypeRequirement::TypeRequirement(TypeSourceInfo *T) :
1620e8d8bef9SDimitry Andric     Requirement(RK_Type, T->getType()->isInstantiationDependentType(),
162155e4f9d5SDimitry Andric                 T->getType()->containsUnexpandedParameterPack(),
162255e4f9d5SDimitry Andric                 // We reach this ctor with either dependent types (in which
162355e4f9d5SDimitry Andric                 // IsSatisfied doesn't matter) or with non-dependent type in
162455e4f9d5SDimitry Andric                 // which the existence of the type indicates satisfaction.
1625e8d8bef9SDimitry Andric                 /*IsSatisfied=*/true),
1626e8d8bef9SDimitry Andric     Value(T),
1627e8d8bef9SDimitry Andric     Status(T->getType()->isInstantiationDependentType() ? SS_Dependent
1628e8d8bef9SDimitry Andric                                                         : SS_Satisfied) {}
1629