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