SemaConcept.cpp 61 KB

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