Skip to main content

bitwright/prove/
mod.rs

1//! A native prover (feature `prove`): expressions are bit-blasted into an and-inverter graph,
2//! encoded as clauses, and decided by bitwright's own CDCL SAT solver. A proof of validity comes
3//! with a certificate, the clauses and a DRUP proof of their unsatisfiability, that an
4//! independent checker ([`Certificate::check`]) verifies, and that any DRAT checker can read
5//! ([`Certificate::dimacs`], [`Certificate::drat`]). A refutation comes with a counterexample:
6//! a value for every symbol, checked by bitwright's evaluator before it is returned. A question
7//! the search does not settle within its budget says why ([`Unknown`]), and a [`Question`]
8//! goes on from where the search stopped, under a larger budget, without starting over.
9//! For a small joint output superset above unresolved predicates, [`domain::analyze`]
10//! preserves shared Boolean structure under explicit premises without solving reachability.
11//!
12//! No other solver is involved. Bit-vector operators are blasted with bitwright's total
13//! semantics (SMT-LIB's); floating-point operators with IEEE 754's and bitwright's canonical
14//! NaN ([`crate::fp`]); extension operations through their [`expand`](crate::ext::ExtOp::expand)
15//! definition, if they have one (otherwise the question is not decided).
16//!
17//! ```
18//! use bitwright::prove::{Config, Outcome, equal};
19//! use bitwright::{Context, ParseOptions, Width};
20//!
21//! let mut cx = Context::new();
22//! let o = ParseOptions::width(Width::W32);
23//! let (a, b) = (cx.parse("(x ^ y) + 2 * (x & y)", &o)?, cx.parse("x + y", &o)?);
24//! let Outcome::Proved(Some(cert)) = equal(&mut cx, a, b, &Config::default().with_certificate(true))? else {
25//!     panic!("not proved")
26//! };
27//! assert!(cert.check().is_ok());
28//! let c = cx.parse("x | y", &o)?;
29//! assert!(matches!(equal(&mut cx, a, c, &Config::default())?, Outcome::Refuted(_)));
30//! # Ok::<(), bitwright::Error>(())
31//! ```
32
33pub mod aig;
34pub mod blast;
35mod cuts;
36pub mod domain;
37pub mod drup;
38mod exhaustion;
39pub mod finite;
40mod fp;
41mod incremental;
42mod lean;
43pub mod lrat;
44mod relations;
45mod rule;
46mod sample_words;
47pub mod sat;
48mod sums;
49mod sweep;
50#[cfg(test)]
51mod tests;
52
53use crate::error::Error;
54use crate::expr::{Context, Expr, OpCode};
55use crate::facts::Assumptions;
56use crate::hash::IdMap;
57use crate::{BitVec, SymbolKey, Width};
58
59pub use exhaustion::Exhaustion;
60/// What an [`Incremental`] answers.
61pub use incremental::Answer as IncrementalAnswer;
62pub use incremental::{Incremental, Prepared};
63pub(crate) use lean::lean_equation;
64pub use lean::lean_theorem;
65pub use rule::{RuleOutcome, WidthReport, rule, rule_all_widths};
66
67use aig::{Aig, Cnf, L};
68use blast::Bits;
69use sat::{Answer, Lit, Solver, Step};
70pub use sat::{Backend, Limits};
71
72/// How assignments are selected before SAT search. Sampling can find a concrete
73/// counterexample. Complete ordered enumeration on the word path can also prove validity;
74/// partial coverage and pseudorandom samples cannot.
75#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
76pub enum SampleMode {
77    /// Seeded pseudorandom assignments, with all-zero and all-one unknown bits first.
78    #[default]
79    Random,
80    /// Enumerate assignments from zero upwards over the circuit's unknown input bits,
81    /// least significant input first. Useful for small integer witnesses in wide domains.
82    /// Multiple symbols' unknown bits are concatenated in circuit input order; declared
83    /// fixed bits retain their values. Higher unknown bits stay zero until reached.
84    Small,
85    /// Enumerate small values of reconstructed words: unknown bits of larger pure
86    /// concatenations and standalone symbols are visited from low to high. A bounded
87    /// portfolio varies words separately and together within the shared sample allowance.
88    /// Shared bits keep one assignment. Uses the bounded word sampler when supported, falling
89    /// back to [`Small`](Self::Small) circuit ordering for other graphs.
90    Words,
91}
92
93/// How hard to try, and what to keep.
94#[derive(Copy, Clone, Debug, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct Config {
97    /// The most conflicts the SAT solver may meet (then [`Unknown::Budget`]).
98    pub max_conflicts: u64,
99    /// The most propagations the SAT solver may do (then [`Unknown::Budget`]; `u64::MAX`, the
100    /// default: no limit). A conflict costs more propagation on a larger circuit, so this bounds
101    /// the time a question takes more closely than conflicts do, and as deterministically.
102    pub max_propagations: u64,
103    /// The most AIG nodes the question may take (then [`Unknown::TooLarge`]).
104    pub max_nodes: usize,
105    /// Keep a [`Certificate`] for a proof.
106    pub certificate: bool,
107    /// Simplify the question with bitwright's own engine before blasting it (the
108    /// deobfuscation strategy, with the MBA service and its opaque-constant sweep when the `mba`
109    /// feature is on): identities the engine settles at the word level (products of MBA, say,
110    /// which bit-level SAT finds hard) are answered at once, and the rest is blasted smaller.
111    /// Not with a certificate: a certificate is of the question as asked, with its symbols'
112    /// declared known bits.
113    pub simplify: bool,
114    /// Simplify without the one pass of the engine that commits rewrites it has derived but
115    /// neither proved nor matched against a proved rule: the limb-arithmetic pass
116    /// ([`Phase::Words`](crate::engine::Phase), integer identities checked at sample points).
117    /// An answer then rests only on proved rules, passes that are decision procedures or
118    /// prove what they commit, and the search. Off by default: that pass is what decides
119    /// limb multiplications no search finishes.
120    pub strict: bool,
121    /// Whether the simplifier's limb-arithmetic pass writes a result only once a circuit and
122    /// a search have proved it ([`Strategy::words_proved`](crate::engine::Strategy)): between
123    /// the default, which takes the pass's derivations as they are, and
124    /// [`strict`](Self::strict), which leaves the pass out.
125    pub proved_words: bool,
126    /// The engine's budget for [`simplify`](Self::simplify): caps in the units of
127    /// [`Budget`](crate::engine::Budget), counts of work and never time, so a question stops at
128    /// the same place on every run. [`Budget::default`](crate::engine::Budget::default) (the
129    /// default) is generous; [`with_simplify_fuel`](Self::with_simplify_fuel) scales every cap
130    /// by one number. A simplification its budget stops keeps the rewrites it made, and the
131    /// rest of the question is blasted as it stands; [`Stats::simplification`] says what was
132    /// spent and which cap stopped it.
133    pub simplify_budget: crate::engine::Budget,
134    /// Assignments of the symbols to evaluate before the search, 64 at a time
135    /// (in batches of 64, selected by [`sample_mode`](Self::sample_mode)): a refutation that a fraction of
136    /// the values give is found without the search, which needs many conflicts for it on a
137    /// large circuit. For deep integer questions with simplification and random sampling,
138    /// one batch can probe comparison literals before simplifying; a miss is not a proof.
139    /// With [`word_sampling`](Self::word_sampling), supported samples precede bit-blasting. 0: none.
140    pub samples: u32,
141    /// Assignment selection for [`samples`](Self::samples). Default: [`SampleMode::Random`].
142    pub sample_mode: SampleMode,
143    /// Add certified transitive bit-equality lemmas exposed by the asserted query. Cycle
144    /// contradictions are detected regardless; additional lemmas are opt-in because their
145    /// effect on arithmetic search depends on the workload.
146    pub relational_lemmas: bool,
147    /// Initially prefer the unknown bits of small shift counts as decisions. This specializes
148    /// variable shifts during search without restricting which selector values are allowed.
149    pub selector_branching: bool,
150    /// Cancel a shared input through bounded XOR paths at every bitwise boundary. This can
151    /// remove direct input dependencies through odd products, but changes arithmetic search
152    /// behavior; opt-in pending workload-specific measurement.
153    pub input_cancellation: bool,
154    /// Factor ORs of XORs with a shared operand at one-valued equality target bits.
155    /// Opt-in because the smaller encoding can alter longer arithmetic searches adversely.
156    pub join_factoring: bool,
157    /// Inline private intermediate XORs into three-input parity gates. This reduces encoding
158    /// variables without changing the clause count, but its search performance is workload-dependent.
159    pub xor3_encoding: bool,
160    /// Compress modular multiplication columns before one final carry-propagating addition.
161    /// Opt-in pending measurements on arithmetic search workloads.
162    pub carry_save_multiplication: bool,
163    /// Try samples directly on a bounded integer DAG of at most 64-bit words before
164    /// bit-blasting. Ordered modes can prove after enumerating every legal input assignment;
165    /// partial samples and unsupported DAGs use the circuit path. Certificates use that path
166    /// even after complete enumeration.
167    /// [`SampleMode::Words`] also enables this path.
168    pub word_sampling: bool,
169    /// Decide a question by evaluating it at every legal assignment when it has at most this
170    /// many unknown input bits, before bit-blasting. It applies to bounded integer DAGs of at
171    /// most 64-bit words, the same as [`word_sampling`](Self::word_sampling), and costs
172    /// `2^bits` evaluations, in parallel across threads; it is not bounded by the search
173    /// limits. A failing assignment is replayed on the original question. A proof asked for
174    /// with a [`certificate`](Self::certificate) comes with an [`Exhaustion`], which checks the
175    /// question's bit-blasted circuit at every assignment of its inputs, independently of the
176    /// word-level decision. If that circuit has more inputs than this bound (it may keep bits
177    /// the word program fixes from scoped assumptions as constrained inputs), the search
178    /// decides the question instead. 0 (the default): never.
179    pub exhaustive_inputs: u8,
180    /// Write the sums of the question one way before blasting it: both sides read as linear
181    /// forms over slices of their values (carries of limbs as the high digits they stand
182    /// for), and built again in one order, so that what the two sides add up the same way is
183    /// one circuit and what cancels is gone. An equality at every input; not for a
184    /// [`certificate`](Self::certificate), which is of the question as asked. Opt-in: it
185    /// helps where the two sides are one arithmetic written twice (a limb against its word),
186    /// and changes the search elsewhere.
187    pub shared_sums: bool,
188    /// Read the divisions by constants that a compiler wrote as products by magic numbers
189    /// (`trunc((zext(x) · M) >>u k)`, a multiply-high and a shift, the signed forms) as the
190    /// divisions they are, before the question is blasted: the simplifier's division pass
191    /// alone, for a question asked without the simplifier ([`simplify`](Self::simplify)
192    /// reads them already). A multiplier's circuit against a divider's is beyond a search
193    /// (the 32-bit quotient by 10 is undecided after 200,000 conflicts); read, both sides
194    /// are one division. An equality at every input; not for a
195    /// [`certificate`](Self::certificate). Opt-in.
196    pub divisions: bool,
197    /// Sweep the circuit before the first search: nodes that simulation shows equal (or
198    /// complementary) are proved so one pair at a time, from the inputs up, by a solver of
199    /// the circuit's clauses alone, and each equivalence is given to the search as clauses.
200    /// Two circuits for one function often share most of their inner nodes (a prefix adder
201    /// and `x + y` have the same carries), and a search over their miter alone rediscovers
202    /// each of them inside one refutation: swept, the 64-bit prefix adder against `x + y`
203    /// takes 0.29 M propagations instead of 0.54 M, the 32-bit SWAR population count against
204    /// `popcnt` 24 k instead of 148 k, and a 64-bit MBA rewriting of `x - y` 0.56 M instead of
205    /// 7.6 M.
206    ///
207    /// The circuit is simulated first, and only swept when the simulation shows enough of
208    /// that sharing: classes of nodes that agree joining the two sides of an equality, at
209    /// least 4 and one per 10 nodes private to a side (a question that is no equality: classes
210    /// of two nodes or more, against all its nodes). Products, or the shift-and-xor addition
211    /// loop against `x + y`, show little and are not swept; the simulation is all they cost.
212    /// A sweep is part of preparing the question: it takes at most half of the configured
213    /// limits ([`max_conflicts`](Self::max_conflicts), [`max_propagations`](Self::max_propagations))
214    /// before any search, whatever the searches' own, so a question resumed in steps is swept
215    /// as one asked at once; its work counts in the question's totals as work done before the
216    /// first search; and with a [`certificate`](Self::certificate) its lemmas are logged so the
217    /// certificate still checks. See [`Stats::sweeping`]. On by default.
218    pub sweeping: bool,
219}
220
221impl Default for Config {
222    fn default() -> Self {
223        Config {
224            max_conflicts: 1_000_000,
225            max_propagations: u64::MAX,
226            max_nodes: 4_000_000,
227            certificate: false,
228            simplify: true,
229            strict: false,
230            proved_words: false,
231            simplify_budget: crate::engine::Budget::default(),
232            samples: 256,
233            sample_mode: SampleMode::Random,
234            relational_lemmas: false,
235            selector_branching: false,
236            input_cancellation: false,
237            join_factoring: false,
238            xor3_encoding: false,
239            carry_save_multiplication: false,
240            word_sampling: false,
241            exhaustive_inputs: 0,
242            shared_sums: false,
243            divisions: false,
244            sweeping: true,
245        }
246    }
247}
248
249setters!(Config {
250    with_max_conflicts: max_conflicts: u64,
251    with_max_propagations: max_propagations: u64,
252    with_max_nodes: max_nodes: usize,
253    with_certificate: certificate: bool,
254    with_simplify: simplify: bool,
255    with_strict: strict: bool,
256    with_proved_words: proved_words: bool,
257    with_simplify_budget: simplify_budget: crate::engine::Budget,
258    with_samples: samples: u32,
259    with_sample_mode: sample_mode: SampleMode,
260    with_relational_lemmas: relational_lemmas: bool,
261    with_selector_branching: selector_branching: bool,
262    with_input_cancellation: input_cancellation: bool,
263    with_join_factoring: join_factoring: bool,
264    with_xor3_encoding: xor3_encoding: bool,
265    with_carry_save_multiplication: carry_save_multiplication: bool,
266    with_word_sampling: word_sampling: bool,
267    with_exhaustive_inputs: exhaustive_inputs: u8,
268    with_shared_sums: shared_sums: bool,
269    with_divisions: divisions: bool,
270    with_sweeping: sweeping: bool,
271});
272
273impl Config {
274    /// Sets [`simplify_budget`](Self::simplify_budget) to
275    /// [`Budget::fuel`](crate::engine::Budget::fuel)`(fuel)`: `fuel` node visits of the engine
276    /// and every other cap in proportion (the default is `1 << 22`).
277    pub fn with_simplify_fuel(self, fuel: u64) -> Self {
278        self.with_simplify_budget(crate::engine::Budget::fuel(fuel))
279    }
280
281    /// The search's limits: [`max_conflicts`](Self::max_conflicts) and
282    /// [`max_propagations`](Self::max_propagations).
283    pub fn limits(&self) -> Limits {
284        Limits {
285            conflicts: self.max_conflicts,
286            propagations: self.max_propagations,
287        }
288    }
289}
290
291/// The engines that simplify questions (see [`Config::simplify`]), owned by whoever asks:
292/// the deobfuscation strategy with the MBA service, built when first needed, and with them
293/// the one thing they remember, the MBA solver's memo. The entry points of this module that
294/// take none use one such set for the process; a caller that wants nothing shared with the
295/// rest of the process (its statistics, its memory) makes its own and asks through
296/// [`Question::valid_under_with`], [`valid_under_with`] or a [`batch::Session`](crate::batch),
297/// which owns one. Answers are the same either way: the solver's memo returns what solving
298/// again would, at the same cost.
299pub struct Simplifiers {
300    /// As asked for, strict, and with the limb pass proved.
301    engines: [std::sync::OnceLock<crate::engine::Engine>; 3],
302    divisions: std::sync::OnceLock<crate::engine::Engine>,
303    /// The MBA phase, when not the prover's own.
304    #[cfg(feature = "mba")]
305    mba: Option<crate::mba::MbaConfig>,
306    #[cfg(feature = "mba")]
307    solver: Option<std::sync::Arc<dyn crate::mba::MbaSolver>>,
308    /// [`Strategy::kept_steps`](crate::engine::Strategy::kept_steps) of the engines.
309    kept_steps: u64,
310    /// [`Strategy::basis_sums`](crate::engine::Strategy::basis_sums) of the engines, and of
311    /// their solver where it is their own ([`NfOptions::basis_sums`](crate::mba::NfOptions)).
312    basis_sums: bool,
313}
314
315impl core::fmt::Debug for Simplifiers {
316    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
317        f.debug_struct("Simplifiers").finish_non_exhaustive()
318    }
319}
320
321impl Default for Simplifiers {
322    fn default() -> Self {
323        Simplifiers::new()
324    }
325}
326
327impl Simplifiers {
328    /// Engines of the prover's own configuration: the MBA service with its opaque-constant
329    /// sweep, and a normal-form solver of their own.
330    pub const fn new() -> Simplifiers {
331        Simplifiers {
332            engines: [
333                std::sync::OnceLock::new(),
334                std::sync::OnceLock::new(),
335                std::sync::OnceLock::new(),
336            ],
337            divisions: std::sync::OnceLock::new(),
338            #[cfg(feature = "mba")]
339            mba: None,
340            #[cfg(feature = "mba")]
341            solver: None,
342            kept_steps: crate::engine::KEPT_STEPS,
343            basis_sums: true,
344        }
345    }
346
347    /// Without sums over the basis of small bitwise functions in the engines' linear-MBA
348    /// pass and, where the solver is their own, in its answers. A question built of one gives
349    /// the search xors and ors where the conjunction form gives it ands: one of a
350    /// devirtualizer's, proved in 0.13 s from the conjunction form at 20,000 propagations,
351    /// was not proved at 10,000,000 from the basis form. Another host's questions (the
352    /// same devirtualizer on another protector) prove as well with them: it is the host's
353    /// choice, as in 0.32.1 they are on.
354    pub fn with_basis_sums(mut self, on: bool) -> Self {
355        self.basis_sums = on;
356        self
357    }
358
359    /// With the MBA phase keeping a fragment with no simpler form from the questions above it
360    /// from these solver steps ([`Strategy::kept_steps`](crate::engine::Strategy::kept_steps)),
361    /// not the default 2^16. A host whose questions are large next to its fuel sets it lower:
362    /// a devirtualizer's walk asked a third of its questions in the same time at 2^16, and as
363    /// many as with 0.31 (and fewer that ran slow) at 2^12.
364    pub fn with_kept_steps(mut self, steps: u64) -> Self {
365        self.kept_steps = steps;
366        self
367    }
368
369    /// With this configuration of the MBA phase instead of the prover's own (the default
370    /// with the opaque-constant sweep). It changes what simplification makes of a question,
371    /// so which questions are decided before the search.
372    #[cfg(feature = "mba")]
373    pub fn with_mba(mut self, mba: crate::mba::MbaConfig) -> Self {
374        self.mba = Some(mba);
375        self
376    }
377
378    /// With this MBA solver instead of a [`NormalFormSolver`](crate::mba::NormalFormSolver)
379    /// of their own.
380    #[cfg(feature = "mba")]
381    pub fn with_mba_solver(mut self, solver: std::sync::Arc<dyn crate::mba::MbaSolver>) -> Self {
382        self.solver = Some(solver);
383        self
384    }
385
386    /// The engine for [`Config::strict`] and [`Config::proved_words`] as given: with `strict`
387    /// without the pass that commits rewrites it has derived but neither proved nor matched
388    /// against a proved rule ([`Phase::Words`](crate::engine::Phase)), or with `proved` with
389    /// that pass writing only what a circuit and a search prove.
390    pub fn engine(&self, strict: bool, proved: bool) -> &crate::engine::Engine {
391        let which = if strict { 1 } else { 2 * usize::from(proved) };
392        self.engines[which].get_or_init(|| {
393            #[cfg(feature = "mba")]
394            let mut strategy = crate::engine::Strategy::deobfuscate().with_mba(
395                (self.mba)
396                    .unwrap_or_else(|| crate::mba::MbaConfig::default().with_opaque_sweep(true)),
397            );
398            #[cfg(not(feature = "mba"))]
399            let mut strategy = crate::engine::Strategy::deobfuscate();
400            if strict {
401                (strategy.phases).retain(|p| !matches!(p, crate::engine::Phase::Words));
402            }
403            strategy.words_proved = proved;
404            strategy.basis_sums = self.basis_sums;
405            strategy.kept_steps = self.kept_steps;
406            let builder = crate::engine::Engine::builder()
407                .builtin()
408                .strategy(strategy);
409            #[cfg(feature = "mba")]
410            let builder = match &self.solver {
411                Some(s) => builder.mba_solver(s.clone()),
412                None if !self.basis_sums => {
413                    builder.mba_solver(std::sync::Arc::new(crate::mba::NormalFormSolver::new(
414                        crate::mba::NfOptions::default().with_basis_sums(false),
415                    )))
416                }
417                None => builder,
418            };
419            builder
420                .build()
421                .unwrap_or_else(|_| crate::engine::Engine::standard())
422        })
423    }
424
425    /// The division pass alone ([`Config::divisions`]).
426    fn divisions_only(&self) -> &crate::engine::Engine {
427        self.divisions.get_or_init(|| {
428            let strategy =
429                crate::engine::Strategy::new("divisions", vec![crate::engine::Phase::Division]);
430            crate::engine::Engine::builder()
431                .builtin()
432                .strategy(strategy)
433                .build()
434                .unwrap_or_else(|_| crate::engine::Engine::standard())
435        })
436    }
437}
438
439/// The engines of the entry points that are given none.
440static PROCESS: Simplifiers = Simplifiers::new();
441
442/// What a question is built with besides its configuration.
443#[derive(Copy, Clone)]
444pub(crate) struct Env<'a> {
445    /// The engines that simplify it.
446    pub(crate) simplifiers: &'a Simplifiers,
447    /// Stops the simplification, and has the question answer [`Unknown::Deadline`].
448    pub(crate) deadline: Option<crate::engine::Deadline<'a>>,
449}
450
451impl Env<'static> {
452    fn process() -> Self {
453        Env {
454            simplifiers: &PROCESS,
455            deadline: None,
456        }
457    }
458}
459
460/// `p` as the prover's simplifier leaves it within [`Config::simplify_budget`]: an expression
461/// equal to `p` at every value of the symbols, which is what the prover builds its circuit
462/// of. Asked again of an expression a question was posed about, it costs a lookup.
463pub fn simplified(cx: &mut Context, p: Expr, cfg: &Config) -> Result<Expr, Error> {
464    let run = crate::engine::Run::default().with_per_call(cfg.simplify_budget);
465    Ok(PROCESS
466        .engine(cfg.strict, cfg.proved_words)
467        .run(cx, &[p], run)?
468        .roots[0]
469        .expr)
470}
471
472/// Clauses and a DRUP proof that they are unsatisfiable, or, for a proof by complete
473/// enumeration ([`Config::exhaustive_inputs`]), the circuit to enumerate.
474#[derive(Clone, Debug)]
475pub struct Certificate {
476    /// The number of variables.
477    pub vars: u32,
478    /// The clauses.
479    pub clauses: Vec<Vec<Lit>>,
480    /// The proof.
481    pub proof: Vec<Step>,
482    /// The circuit of a proof by complete enumeration. Such a certificate has no clauses or
483    /// DRUP proof, so its [`dimacs`](Self::dimacs) and [`drat`](Self::drat) export nothing a
484    /// DRAT checker would accept.
485    pub exhaustion: Option<Exhaustion>,
486}
487
488impl Certificate {
489    /// Checks the proof with the independent checker: the DRUP proof against the clauses, or
490    /// the circuit of an [`Exhaustion`] at every assignment of its inputs.
491    pub fn check(&self) -> Result<(), String> {
492        match &self.exhaustion {
493            Some(exhaustion) => exhaustion.check(),
494            None => {
495                drup::check(&self.clauses, &self.proof)?;
496                // In the tests, every proof checked is checked as LRAT too.
497                #[cfg(test)]
498                lrat::check(&self.clauses, &self.lrat()?)?;
499                Ok(())
500            }
501        }
502    }
503
504    /// The clauses in DIMACS CNF.
505    pub fn dimacs(&self) -> String {
506        let mut s = format!("p cnf {} {}\n", self.vars, self.clauses.len());
507        for c in &self.clauses {
508            for l in c {
509                s.push_str(&l.dimacs().to_string());
510                s.push(' ');
511            }
512            s.push_str("0\n");
513        }
514        s
515    }
516
517    /// The proof as LRAT ([`lrat`]): every learned clause with the clauses it follows from,
518    /// found by checking the DRUP proof, for a checker that does no search (the text is
519    /// [`lrat::to_text`], beside [`dimacs`](Self::dimacs)). An error when the proof does not
520    /// check, or is one by enumeration.
521    pub fn lrat(&self) -> Result<Vec<lrat::Step>, String> {
522        match &self.exhaustion {
523            Some(_) => Err("a proof by enumeration has no clauses".into()),
524            None => lrat::from_drup(&self.clauses, &self.proof),
525        }
526    }
527
528    /// The proof in DRAT's text format (additions, and deletions prefixed `d`).
529    pub fn drat(&self) -> String {
530        let mut s = String::new();
531        for step in &self.proof {
532            let (pre, c) = match step {
533                Step::Add(c) => ("", c),
534                Step::Delete(c) => ("d ", c),
535            };
536            s.push_str(pre);
537            for l in c {
538                s.push_str(&l.dimacs().to_string());
539                s.push(' ');
540            }
541            s.push_str("0\n");
542        }
543        s
544    }
545}
546
547/// The answer to a question.
548#[derive(Clone, Debug)]
549#[non_exhaustive]
550pub enum Outcome {
551    /// It holds for every value of the symbols (with a certificate, if asked for).
552    Proved(Option<Certificate>),
553    /// It fails at these values of the symbols (checked by evaluation).
554    Refuted(Vec<(SymbolKey, BitVec)>),
555    /// Not decided: why.
556    Unknown(Unknown),
557}
558
559/// Why a question is not decided.
560#[derive(Clone, Debug, PartialEq, Eq)]
561#[non_exhaustive]
562pub enum Unknown {
563    /// The search reached a limit ([`Config::max_conflicts`] or
564    /// [`Config::max_propagations`]) after this much work on the question: more may decide
565    /// it, and a [`Question`] goes on from where it stopped.
566    Budget {
567        /// Conflicts met on the question.
568        conflicts: u64,
569        /// Propagations done on the question.
570        propagations: u64,
571    },
572    /// The circuit passed [`Config::max_nodes`]: `nodes` had been built when blasting stopped.
573    /// The same under any search budget with that cap.
574    TooLarge {
575        /// AIG nodes built.
576        nodes: usize,
577    },
578    /// Something the prover does not reason about (an extension operation without an
579    /// expansion, say). The same under any budget.
580    Unsupported(String),
581    /// A caller's deadline passed ([`crate::solve::Solver::check_within`]): more time may
582    /// decide it. Unlike the budgets, this depends on timing.
583    Deadline,
584}
585
586impl Unknown {
587    /// Whether a larger search budget may decide the question ([`Unknown::Budget`]).
588    pub fn is_budget(&self) -> bool {
589        matches!(self, Unknown::Budget { .. })
590    }
591}
592
593impl core::fmt::Display for Unknown {
594    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
595        match self {
596            Unknown::Budget {
597                conflicts,
598                propagations,
599            } => write!(
600                f,
601                "no answer within {conflicts} conflicts ({propagations} propagations)"
602            ),
603            Unknown::Deadline => write!(f, "the deadline passed"),
604            Unknown::TooLarge { nodes } => {
605                write!(f, "the circuit is too large ({nodes} nodes built)")
606            }
607            Unknown::Unsupported(why) => f.write_str(why),
608        }
609    }
610}
611
612/// The work a question took, so far. Every count is of work done, not of time, and the same on
613/// every run: a question asked the same way (in a context with the same history) reports the
614/// same numbers, and the totals of one resumed in steps are those of one asked at once.
615#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
616#[non_exhaustive]
617pub struct Stats {
618    /// What simplifying the question took ([`Config::simplify`]).
619    pub simplification: Simplification,
620    /// What sweeping the circuit did ([`Config::sweeping`]); its conflicts, decisions,
621    /// propagations and lemmas are also counted in the totals below.
622    pub sweeping: Sweeping,
623    /// AIG nodes of the circuit (inputs and gates).
624    pub nodes: usize,
625    /// Whether the circuit is of the question with its sums written again
626    /// ([`Config::shared_sums`]), and not of the question as asked (where that changed
627    /// nothing, or made a circuit past [`Config::max_nodes`]).
628    pub rewritten: bool,
629    /// Assignments evaluated before search, on words or the circuit ([`Config::samples`]).
630    pub samples: u64,
631    /// Variables of the clauses.
632    pub vars: u32,
633    /// Clauses of the question (not learned ones).
634    pub clauses: usize,
635    /// Learned clauses kept.
636    pub learned: usize,
637    /// Clauses learned in all, units included, whether kept or since deleted.
638    pub lemmas: u64,
639    /// Variables fixed for good: assigned with no decision made, by the clauses and the units
640    /// learned so far. Of [`vars`](Self::vars), the part of the circuit the search has settled.
641    pub fixed: usize,
642    /// Conflicts.
643    pub conflicts: u64,
644    /// Decisions.
645    pub decisions: u64,
646    /// Propagations.
647    pub propagations: u64,
648    /// Searches run: [`Question::solve`] calls that searched (one that finds the question
649    /// already decided, or that has a zero allowance, does not).
650    pub searches: u32,
651    /// The last search's conflicts: the marginal cost of its call. A search goes on from where
652    /// the one before stopped, so these add up to [`conflicts`](Self::conflicts) and nothing
653    /// is searched twice.
654    pub last_conflicts: u64,
655    /// The last search's decisions.
656    pub last_decisions: u64,
657    /// The last search's propagations (they add up to [`propagations`](Self::propagations)
658    /// with the propagation of the clauses before any search).
659    pub last_propagations: u64,
660    /// Clauses the last search learned.
661    pub last_lemmas: u64,
662}
663
664impl Stats {
665    /// These counts without the last search's own ([`searches`](Self::searches) and the
666    /// `last_*` fields cleared): the work done in all, which is the same for a question
667    /// resumed in steps and one asked at once under their combined limits.
668    pub fn totals(self) -> Stats {
669        Stats {
670            searches: 0,
671            last_conflicts: 0,
672            last_decisions: 0,
673            last_propagations: 0,
674            last_lemmas: 0,
675            ..self
676        }
677    }
678}
679
680/// What sweeping a question's circuit did ([`Config::sweeping`]).
681#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
682#[non_exhaustive]
683pub struct Sweeping {
684    /// Whether the circuit was swept: simulated, and its candidate pairs proved.
685    pub ran: bool,
686    /// Whether the circuit was simulated and judged not worth sweeping: too few classes of
687    /// nodes that agree join the two sides of an equality (see [`Config::sweeping`]).
688    pub skipped: bool,
689    /// Classes of the first simulation that join the two sides of an equality (of a question
690    /// that is not one: classes of two nodes or more).
691    pub crossings: u64,
692    /// Nodes proved equal to an earlier node, or its complement, or to a constant.
693    pub merged: u64,
694    /// Candidate pairs a counterexample told apart.
695    pub separated: u64,
696    /// Candidate pairs left undecided within their own conflict cap.
697    pub undecided: u64,
698    /// The sweep's conflicts.
699    pub conflicts: u64,
700    /// The sweep's propagations.
701    pub propagations: u64,
702}
703
704/// What simplifying a question with bitwright's own engine took ([`Config::simplify`]).
705#[derive(Copy, Clone, Debug, PartialEq, Eq)]
706#[non_exhaustive]
707pub struct Simplification {
708    /// Whether the engine ran on the question.
709    pub ran: bool,
710    /// The work it did, in the units of its budget ([`Config::simplify_budget`]): every
711    /// field counted, capped or not. Work the engine finished on the same nodes earlier in the
712    /// same context is remembered there and not done again.
713    pub spent: crate::engine::Budget,
714    /// The cap that stopped it, if one did. The rewrites it made until then are kept, and the
715    /// rest of the question is blasted as it stands; a larger budget may settle more.
716    pub stopped: Option<crate::engine::Exhausted>,
717    /// Whether it decided the question (the simplified question is true).
718    pub decided: bool,
719}
720
721impl Default for Simplification {
722    /// The engine did not run.
723    fn default() -> Self {
724        Simplification {
725            ran: false,
726            spent: crate::engine::Budget::ZERO,
727            stopped: None,
728            decided: false,
729        }
730    }
731}
732
733/// The bits of expressions, blasted on demand.
734pub(crate) struct Blaster<'c> {
735    pub(crate) cx: &'c mut Context,
736    pub(crate) g: Aig,
737    bits: IdMap<u32, Bits>,
738    /// Each symbol met, with its bits.
739    pub(crate) symbols: Vec<(u32, Bits)>,
740    selectors: Vec<L>,
741    selector_hints: bool,
742    input_cancellation: bool,
743    join_factoring: bool,
744    carry_save_multiplication: bool,
745    hardwire_declared: bool,
746    udivrem_cache: IdMap<(u32, u32), (Bits, Bits)>,
747    max_nodes: usize,
748    /// Blasting stopped at `max_nodes`.
749    too_large: bool,
750}
751
752impl<'c> Blaster<'c> {
753    pub(crate) fn new(cx: &'c mut Context, max_nodes: usize) -> Blaster<'c> {
754        Blaster {
755            cx,
756            g: Aig::new(),
757            bits: IdMap::default(),
758            symbols: Vec::new(),
759            selectors: Vec::new(),
760            selector_hints: false,
761            input_cancellation: false,
762            join_factoring: false,
763            carry_save_multiplication: false,
764            hardwire_declared: true,
765            udivrem_cache: IdMap::default(),
766            max_nodes,
767            too_large: false,
768        }
769    }
770
771    /// A blaster that goes on from a circuit built before: its graph, the bits of the nodes
772    /// blasted and the symbols met ([`into_parts`](Self::into_parts)). Symbol bits stay free
773    /// inputs so [`Incremental`] can assume whatever known bits are declared at each check.
774    pub(crate) fn resume(
775        cx: &'c mut Context,
776        g: Aig,
777        bits: IdMap<u32, Bits>,
778        symbols: Vec<(u32, Bits)>,
779        max_nodes: usize,
780    ) -> Blaster<'c> {
781        Blaster {
782            g,
783            bits,
784            symbols,
785            hardwire_declared: false,
786            ..Blaster::new(cx, max_nodes)
787        }
788    }
789
790    /// The circuit, to [`resume`](Self::resume) from.
791    pub(crate) fn into_parts(self) -> (Aig, IdMap<u32, Bits>, Vec<(u32, Bits)>) {
792        (self.g, self.bits, self.symbols)
793    }
794
795    /// The bits of node `root`.
796    pub(crate) fn blast(&mut self, root: u32) -> Result<Bits, Error> {
797        let bits = &self.bits;
798        let order = self
799            .cx
800            .post_order_ids_pruned(&[root], |e| bits.contains_key(&e.index()));
801        for i in order {
802            if self.bits.contains_key(&i) {
803                continue;
804            }
805            if self.g.len() > self.max_nodes {
806                self.too_large = true;
807                return Err(Error::Unsupported("the circuit is too large".into()));
808            }
809            let b = self.node(i)?;
810            self.bits.insert(i, b);
811        }
812        Ok(self.bits[&root].clone())
813    }
814
815    fn node(&mut self, i: u32) -> Result<Bits, Error> {
816        use blast::*;
817        let n = self.cx.node(i);
818        let w = usize::from(n.width);
819        let g = &mut self.g;
820        Ok(match n.op {
821            OpCode::Const => konst(&self.cx.const_val(i).unwrap_or(BitVec::zero(Width::W1))),
822            OpCode::Sym => {
823                // Declarations are part of a symbol's meaning, including in certificate
824                // mode. Only its unknown bits are inputs of the circuit, unless the circuit
825                // is kept across checks (`Incremental`), where declarations are assumed per
826                // solve so changes or withdrawals stay sound.
827                let known = self
828                    .hardwire_declared
829                    .then(|| self.cx.declared_at(i))
830                    .flatten();
831                let b: Bits = (0..w)
832                    .map(|j| match known {
833                        Some(k) if k.known_one().bit(j as u16) == Some(true) => aig::TRUE,
834                        Some(k) if k.known_zero().bit(j as u16) == Some(true) => aig::FALSE,
835                        _ => g.input(),
836                    })
837                    .collect();
838                self.symbols.push((i, b.clone()));
839                b
840            }
841            OpCode::Not => not(g, &self.bits[&n.a]),
842            OpCode::Neg => neg(g, &self.bits[&n.a]),
843            OpCode::Popcnt => popcnt(g, &self.bits[&n.a]),
844            OpCode::Clz => clz(g, &self.bits[&n.a]),
845            OpCode::Ctz => ctz(g, &self.bits[&n.a]),
846            OpCode::Bswap => bswap(&self.bits[&n.a]),
847            OpCode::BitRev => bitrev(&self.bits[&n.a]),
848            OpCode::Zext | OpCode::Sext => {
849                let low = &self.bits[&n.a];
850                let fill = if n.op == OpCode::Sext { low[low.len() - 1] } else { aig::FALSE };
851                let mut out = Vec::with_capacity(w);
852                out.extend_from_slice(low);
853                out.resize(w, fill);
854                out
855            }
856            OpCode::Extract => {
857                let a = &self.bits[&n.a];
858                let lo = n.b as usize;
859                a[lo..lo + w].to_vec()
860            }
861            OpCode::Concat => {
862                let mut out = Vec::with_capacity(w);
863                out.extend_from_slice(&self.bits[&n.b]);
864                out.extend_from_slice(&self.bits[&n.a]);
865                out
866            }
867            OpCode::Select => mux(g, self.bits[&n.a][0], &self.bits[&n.b], &self.bits[&n.c]),
868            OpCode::Eq | OpCode::Ne | OpCode::Ult | OpCode::Ule | OpCode::Slt | OpCode::Sle => {
869                let (a, b) = (&self.bits[&n.a], &self.bits[&n.b]);
870                let r = match n.op {
871                    OpCode::Eq if self.join_factoring => eq_factored(g, a, b),
872                    OpCode::Ne if self.join_factoring => eq_factored(g, a, b) ^ 1,
873                    OpCode::Eq => eq(g, a, b),
874                    OpCode::Ne => eq(g, a, b) ^ 1,
875                    OpCode::Ult => ult(g, a, b),
876                    OpCode::Ule => ule(g, a, b),
877                    OpCode::Slt => slt(g, a, b),
878                    _ => sle(g, a, b),
879                };
880                vec![r]
881            }
882            op if op.as_bin().is_some() => {
883                let (a, b) = (&self.bits[&n.a], &self.bits[&n.b]);
884                if self.selector_hints && matches!(op, OpCode::Shl | OpCode::LShr | OpCode::AShr) {
885                    let unknown: Vec<_> = b
886                        .iter()
887                        .copied()
888                        .filter(|&l| l > aig::TRUE)
889                        .take(5)
890                        .collect();
891                    if !unknown.is_empty() && unknown.len() <= 4 {
892                        self.selectors.extend(unknown);
893                    }
894                }
895                match op {
896                    OpCode::Add => add(g, a, b),
897                    OpCode::Sub => sub(g, a, b),
898                    OpCode::Mul if self.carry_save_multiplication => mul_carry_save(g, a, b),
899                    OpCode::Mul => mul(g, a, b),
900                    OpCode::UMulHi if self.carry_save_multiplication => mulhi_carry_save(g, a, b, false),
901                    OpCode::UMulHi => mulhi(g, a, b, false),
902                    OpCode::SMulHi if self.carry_save_multiplication => mulhi_carry_save(g, a, b, true),
903                    OpCode::SMulHi => mulhi(g, a, b, true),
904                    OpCode::UDiv | OpCode::URem => {
905                        let qr = self.udivrem_cache.entry((n.a, n.b)).or_insert_with(|| udivrem(g, a, b));
906                        if op == OpCode::UDiv { qr.0.clone() } else { qr.1.clone() }
907                    }
908                    OpCode::SDiv => sdiv(g, a, b),
909                    OpCode::SRem => srem(g, a, b),
910                    OpCode::And => and(g, a, b),
911                    OpCode::Or => or(g, a, b),
912                    OpCode::Xor if self.input_cancellation => xor_cancel_input(g, a, b),
913                    OpCode::Xor => xor(g, a, b),
914                    OpCode::Shl => shift(g, a, b, true, aig::FALSE),
915                    OpCode::LShr => shift(g, a, b, false, aig::FALSE),
916                    OpCode::AShr => shift(g, a, b, false, a[a.len() - 1]),
917                    OpCode::RotL => rotate(g, a, b, true),
918                    OpCode::RotR => rotate(g, a, b, false),
919                    OpCode::Pdep => pdep(g, a, b),
920                    _ => pext(g, a, b),
921                }
922            }
923            op if op.as_ext().is_some() => self.ext(i)?,
924            _ => {
925                let kids: Vec<Bits> = n.children().map(|c| self.bits[&c].clone()).collect();
926                fp::blast(self, i, &kids)?
927            }
928        })
929    }
930
931    /// An extension output, through the operation's expansion.
932    fn ext(&mut self, i: u32) -> Result<Bits, Error> {
933        let n = self.cx.node(i);
934        let Some((_, k)) = n.op.as_ext() else {
935            return Err(Error::Unsupported("not an extension output".into()));
936        };
937        let args: Vec<Expr> = n.children().map(|c| self.cx.handle(c)).collect();
938        let reg = self
939            .cx
940            .registry
941            .clone()
942            .ok_or_else(|| Error::Unsupported("an extension without its registry".into()))?;
943        let op = reg
944            .op_at(n.aux)
945            .ok_or_else(|| Error::Unsupported("an extension without its operation".into()))?;
946        let Some(ex) = op.expand(self.cx, &args) else {
947            return Err(Error::Unsupported(format!(
948                "`{}` has no expansion to reason about",
949                op.name()
950            )));
951        };
952        let outs = ex?;
953        let e = self.cx.id(outs[k])?;
954        self.blast(e)
955    }
956
957    /// Why blasting failed with `e`: [`Unknown::TooLarge`] past `max_nodes`, else the reason
958    /// of an unsupported operation. Other errors are errors.
959    fn unknown(&self, e: Error) -> Result<Unknown, Error> {
960        match e {
961            _ if self.too_large => Ok(Unknown::TooLarge {
962                nodes: self.g.len(),
963            }),
964            Error::Unsupported(why) => Ok(Unknown::Unsupported(why)),
965            e => Err(e),
966        }
967    }
968}
969
970/// Where a SAT-solved question stands.
971struct Search {
972    solver: Solver,
973    cnf: Cnf,
974    /// What the sweep cost ([`Config::sweeping`]), counted in the totals.
975    swept: sweep::Work,
976}
977
978/// A question, blasted and encoded once, then decided in as many steps as its caller likes: a
979/// search that ends on its limits stops where it is, keeping what it learned, and the next
980/// [`solve`](Self::solve) goes on from there. Asking under 5,000 conflicts, then 15,000 more,
981/// costs what asking under 20,000 once does, and answers the same.
982///
983/// ```
984/// use bitwright::prove::{Config, Limits, Outcome, Question};
985/// use bitwright::{Context, ParseOptions, Width};
986///
987/// let mut cx = Context::new();
988/// let o = ParseOptions::width(Width::W16);
989/// let p = cx.parse("x * x != 0x1234", &o)?;
990/// // Without the engine's simplification first, which decides it by residues.
991/// let cfg = Config::default().with_samples(0).with_simplify(false);
992/// let mut q = Question::valid(&mut cx, p, &cfg)?;
993/// let mut out = q.solve(&mut cx, Limits::conflicts(10))?;
994/// while let Outcome::Unknown(why) = &out {
995///     assert!(why.is_budget());
996///     out = q.solve(&mut cx, Limits::conflicts(10))?;
997/// }
998/// assert!(matches!(out, Outcome::Proved(_))); // 0x1234 is not a square mod 2^16
999/// assert!(q.stats().conflicts > 0);
1000/// # Ok::<(), bitwright::Error>(())
1001/// ```
1002pub struct Question {
1003    /// The question as asked (with the constraints, as `¬(c1 ∧ …) ∨ p`), checked by evaluation.
1004    root: Expr,
1005    /// Each symbol of the question with its bits (one the circuit does not read takes its
1006    /// declared ones, or 0 without a declaration).
1007    symbols: Vec<(SymbolKey, Width, Bits)>,
1008    search: Option<Box<Search>>,
1009    outcome: Option<Outcome>,
1010    stats: Stats,
1011}
1012
1013impl core::fmt::Debug for Question {
1014    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1015        f.debug_struct("Question")
1016            .field("outcome", &self.outcome)
1017            .field("stats", &self.stats)
1018            .finish_non_exhaustive()
1019    }
1020}
1021
1022impl Question {
1023    /// Whether the 1-bit `p` is true for every value of its symbols agreeing with their
1024    /// declared known bits.
1025    pub fn valid(cx: &mut Context, p: Expr, cfg: &Config) -> Result<Question, Error> {
1026        Question::valid_under(cx, p, None, cfg)
1027    }
1028
1029    /// Whether `a` and `b` (of one width) are equal for every value of their symbols agreeing
1030    /// with their declared known bits.
1031    pub fn equal(cx: &mut Context, a: Expr, b: Expr, cfg: &Config) -> Result<Question, Error> {
1032        let (ai, bi) = (cx.id(a)?, cx.id(b)?);
1033        if cx.wid(ai) != cx.wid(bi) {
1034            return Err(crate::WidthError::Mismatch {
1035                left: cx.wid(ai),
1036                right: cx.wid(bi),
1037            }
1038            .into());
1039        }
1040        let p = cx.c_cmp(crate::CmpOp::Eq, ai, bi)?;
1041        let p = cx.handle(p);
1042        Question::valid(cx, p, cfg)
1043    }
1044
1045    /// Whether `p` is true wherever the constraints of `assumptions` hold. Complete original
1046    /// facts are retained, including partial masks, signed/unsigned
1047    /// intervals and unsigned strides; they remain in certificates and counterexample replay.
1048    /// The question is simplified (see [`Config::simplify`]), optionally sampled at the word level, then
1049    /// blasted, sampled (see [`Config::samples`]) and encoded here; each stage may decide it.
1050    pub fn valid_under(
1051        cx: &mut Context,
1052        p: Expr,
1053        assumptions: Option<&Assumptions>,
1054        cfg: &Config,
1055    ) -> Result<Question, Error> {
1056        Self::valid_under_with_pairs(cx, p, assumptions, &[], cfg)
1057    }
1058
1059    /// Ask the original question after applying explicitly supplied, exhaustively checked
1060    /// finite-domain pair facts. Verification costs are separate from this query's budget.
1061    /// Models are replayed on the original predicate. Certificate requests retain the
1062    /// original bit-blast path and do not use these word-level facts.
1063    pub fn valid_with_pairs(
1064        cx: &mut Context,
1065        p: Expr,
1066        pairs: &[finite::CheckedPair],
1067        cfg: &Config,
1068    ) -> Result<Question, Error> {
1069        Self::valid_under_with_pairs(cx, p, None, pairs, cfg)
1070    }
1071
1072    /// [`valid_with_pairs`](Self::valid_with_pairs) under explicit assumptions.
1073    pub fn valid_under_with_pairs(
1074        cx: &mut Context,
1075        p: Expr,
1076        assumptions: Option<&Assumptions>,
1077        pairs: &[finite::CheckedPair],
1078        cfg: &Config,
1079    ) -> Result<Question, Error> {
1080        Self::build(cx, p, assumptions, pairs, cfg, Env::process())
1081    }
1082
1083    /// [`valid_under`](Self::valid_under), simplified by the caller's engines and not the
1084    /// process's: the same question, answer and statistics.
1085    pub fn valid_under_with(
1086        cx: &mut Context,
1087        p: Expr,
1088        assumptions: Option<&Assumptions>,
1089        cfg: &Config,
1090        simplifiers: &Simplifiers,
1091    ) -> Result<Question, Error> {
1092        let env = Env {
1093            simplifiers,
1094            deadline: None,
1095        };
1096        Self::build(cx, p, assumptions, &[], cfg, env)
1097    }
1098
1099    /// The question, built with `env`.
1100    pub(crate) fn build(
1101        cx: &mut Context,
1102        p: Expr,
1103        assumptions: Option<&Assumptions>,
1104        pairs: &[finite::CheckedPair],
1105        cfg: &Config,
1106        env: Env<'_>,
1107    ) -> Result<Question, Error> {
1108        let pi = cx.id(p)?;
1109        if cx.wid(pi) != 1 {
1110            return Err(crate::WidthError::Mismatch {
1111                left: 1,
1112                right: cx.wid(pi),
1113            }
1114            .into());
1115        }
1116        let mut q = Question {
1117            root: p,
1118            symbols: Vec::new(),
1119            search: None,
1120            outcome: None,
1121            stats: Stats::default(),
1122        };
1123        let decided = |mut q: Question, o: Outcome| {
1124            q.outcome = Some(o);
1125            Ok(q)
1126        };
1127        // Exact original constraints, including masks, signed/unsigned bounds and strides.
1128        let mut cons: Vec<u32> = Vec::new();
1129        if let Some(a) = assumptions {
1130            for predicate in a.predicates(cx)? {
1131                cons.push(cx.id(predicate)?);
1132            }
1133        }
1134        // The root checked by evaluation: `p` where the constraints hold, as `¬(c1 ∧ …) ∨ p`.
1135        let mut root = pi;
1136        for &c in &cons {
1137            let nc = cx.c_un(crate::UnOp::Not, c)?;
1138            root = cx.c_bin(crate::BinOp::Or, nc, root)?;
1139        }
1140        q.root = cx.handle(root);
1141        // The question simplified (not for a certificate, which must be of the question itself).
1142        let mut goal_node = pi;
1143        if !cfg.certificate {
1144            for pair in pairs {
1145                let rewritten = pair.simplify(cx, cx.handle(goal_node))?;
1146                goal_node = cx.id(rewritten)?;
1147            }
1148            if cx
1149                .const_val(goal_node)
1150                .is_some_and(|value| !value.is_zero())
1151            {
1152                return decided(q, Outcome::Proved(None));
1153            }
1154        }
1155        // Reserve at least one ordinary circuit batch. Sample the *original implication*
1156        // so even constraints hidden inside the predicate participate in witness validation.
1157        if cfg.simplify && !cfg.certificate && !cfg.word_sampling
1158            && cfg.sample_mode == SampleMode::Random && cfg.samples >= 128
1159            && env.deadline.is_none()
1160            && let Some((tested, model)) = sample_words::guard_samples(cx, root)
1161        {
1162            q.stats.samples = tested;
1163            if let Some(model) = model {
1164                let outcome = q.refuted(cx, model)?;
1165                return decided(q, outcome);
1166            }
1167        }
1168        let remaining_batches = cfg.samples.div_ceil(64) - (q.stats.samples / 64) as u32;
1169        if cfg.simplify && !cfg.certificate {
1170            let mut spent = crate::engine::Allowance::new(crate::engine::Budget::UNLIMITED);
1171            let run = crate::engine::Run::default()
1172                .with_per_call(cfg.simplify_budget)
1173                .with_allowance(&mut spent);
1174            let run = match assumptions {
1175                Some(a) => run.with_assumptions(a),
1176                None => run,
1177            };
1178            let run = match env.deadline {
1179                Some(d) => run.with_deadline(d),
1180                None => run,
1181            };
1182            let goal = cx.handle(goal_node);
1183            let out = (env.simplifiers)
1184                .engine(cfg.strict, cfg.proved_words)
1185                .run(cx, &[goal], run)?
1186                .roots[0];
1187            let s = cx.id(out.expr)?;
1188            let proved = cx.const_val(s).is_some_and(|v| !v.is_zero());
1189            q.stats.simplification = Simplification {
1190                ran: true,
1191                spent: spent.spent(),
1192                stopped: match out.end {
1193                    crate::engine::End::BudgetTerminated(why) => Some(why),
1194                    _ => None,
1195                },
1196                decided: proved,
1197            };
1198            if proved {
1199                return decided(q, Outcome::Proved(None));
1200            }
1201            // Stopped by its caller: what is left would be built and searched for nobody.
1202            if out.end == crate::engine::End::BudgetTerminated(crate::engine::Exhausted::Deadline) {
1203                return decided(q, Outcome::Unknown(Unknown::Deadline));
1204            }
1205            // A result that relies on constraints holds where they do, which is all a proof
1206            // under them needs.
1207            goal_node = s;
1208        }
1209        if cfg.divisions && !cfg.simplify && !cfg.certificate {
1210            let run = crate::engine::Run::default().with_per_call(cfg.simplify_budget);
1211            let run = match assumptions {
1212                Some(a) => run.with_assumptions(a),
1213                None => run,
1214            };
1215            let goal = cx.handle(goal_node);
1216            let out = env
1217                .simplifiers
1218                .divisions_only()
1219                .run(cx, &[goal], run)?
1220                .roots[0];
1221            goal_node = cx.id(out.expr)?;
1222            if cx.const_val(goal_node).is_some_and(|v| !v.is_zero()) {
1223                q.stats.rewritten = true;
1224                return decided(q, Outcome::Proved(None));
1225            }
1226        }
1227        let mut word_sampled = false;
1228        if (cfg.word_sampling || cfg.sample_mode == SampleMode::Words)
1229            && cfg.samples != 0
1230            && let Some(trial) = sample_words::try_sample(cx, goal_node, &cons, assumptions, cfg)
1231        {
1232            q.stats.samples = trial.samples;
1233            word_sampled = true;
1234            if let Some(mut model) = trial.model {
1235                complete_model(cx, q.root, &mut model)?;
1236                let outcome = q.refuted(cx, model)?;
1237                return decided(q, outcome);
1238            }
1239            if trial.complete && !cfg.certificate {
1240                return decided(q, Outcome::Proved(None));
1241            }
1242        }
1243        // Every legal assignment, when there are few enough. A proof that asks for a
1244        // certificate takes it from the circuit below, which is checked independently.
1245        let mut exhausted = false;
1246        if cfg.exhaustive_inputs != 0
1247            && let Some((failure, evaluated)) =
1248                sample_words::try_exhaust(cx, goal_node, &cons, assumptions, cfg.exhaustive_inputs)
1249        {
1250            q.stats.samples += evaluated;
1251            match failure {
1252                Some(mut model) => {
1253                    complete_model(cx, q.root, &mut model)?;
1254                    let outcome = q.refuted(cx, model)?;
1255                    return decided(q, outcome);
1256                }
1257                None if !cfg.certificate => return decided(q, Outcome::Proved(None)),
1258                None => exhausted = true,
1259            }
1260        }
1261        // The question as asked, where writing its sums again changes it.
1262        let asked = goal_node;
1263        if cfg.shared_sums && !cfg.certificate {
1264            goal_node = sums::shared(cx, goal_node)?;
1265            if cx
1266                .const_val(goal_node)
1267                .is_some_and(|value| !value.is_zero())
1268            {
1269                q.stats.rewritten = true;
1270                return decided(q, Outcome::Proved(None));
1271            }
1272        }
1273        let (mut b, goal, extra) = loop {
1274            let constant_goal = cuts::constant_true(cx, goal_node);
1275            let mut b = Blaster::new(cx, cfg.max_nodes);
1276            b.selector_hints = cfg.selector_branching;
1277            b.input_cancellation = cfg.input_cancellation;
1278            b.join_factoring = cfg.join_factoring;
1279            b.carry_save_multiplication = cfg.carry_save_multiplication;
1280            if constant_goal {
1281                b.bits.insert(goal_node, vec![aig::TRUE]);
1282            }
1283            let mut blasted = || -> Result<(L, Vec<L>), Error> {
1284                let goal = b.blast(goal_node)?[0];
1285                let mut extra = Vec::new();
1286                for &c in &cons {
1287                    extra.push(b.blast(c)?[0]);
1288                }
1289                Ok((goal, extra))
1290            };
1291            match blasted() {
1292                Ok((goal, extra)) if b.g.len() <= cfg.max_nodes => break (b, goal, extra),
1293                // (Written again the circuit is too large: the question as asked, then.)
1294                _ if goal_node != asked => goal_node = asked,
1295                Ok(_) => {
1296                    let why = Unknown::TooLarge { nodes: b.g.len() };
1297                    return decided(q, Outcome::Unknown(why));
1298                }
1299                Err(e) => {
1300                    let why = b.unknown(e)?;
1301                    return decided(q, Outcome::Unknown(why));
1302                }
1303            }
1304        };
1305        q.stats.nodes = b.g.len();
1306        q.stats.rewritten = goal_node != asked;
1307        // Every symbol of the question, with its bits if the circuit reads it. (Marked by
1308        // symbol index: a search of the list per symbol took 12 s on a question of 64 000
1309        // symbols that simplification had already decided.)
1310        let mut listed = vec![false; b.cx.symbol_count()];
1311        for (s, bits) in &b.symbols {
1312            let h = b.cx.handle(*s);
1313            let id =
1314                b.cx.symbol_id(h)?
1315                    .ok_or_else(|| Error::Contract("a symbol without its key".into()))?;
1316            let key =
1317                b.cx.symbol_key(id)
1318                    .cloned()
1319                    .ok_or_else(|| Error::Contract("a symbol without its key".into()))?;
1320            listed[id.index() as usize] = true;
1321            q.symbols.push((key, b.cx.width_of(*s), bits.clone()));
1322        }
1323        for id in b.cx.symbols_in(&[q.root])? {
1324            if !core::mem::replace(&mut listed[id.index() as usize], true)
1325                && let (Some(k), Some(w)) = (b.cx.symbol_key(id).cloned(), b.cx.symbol_width(id))
1326            {
1327                let bits =
1328                    b.cx.find_symbol(&k)
1329                        .and_then(|e| b.cx.declared_at(e.index()))
1330                        .map(|known| blast::konst(&known.known_one()))
1331                        .unwrap_or_default();
1332                q.symbols.push((k, w, bits));
1333            }
1334        }
1335        if exhausted {
1336            let exhaustion = Exhaustion::of(&b.g, goal, &extra);
1337            if exhaustion.inputs() <= u32::from(cfg.exhaustive_inputs.min(63)) {
1338                let cert = Certificate {
1339                    vars: 0,
1340                    clauses: Vec::new(),
1341                    proof: Vec::new(),
1342                    exhaustion: Some(exhaustion),
1343                };
1344                return decided(q, Outcome::Proved(Some(cert)));
1345            }
1346        }
1347        // Sampled: a lane where the constraints hold and the goal does not refutes it.
1348        let batches = if word_sampled {
1349            0
1350        } else {
1351            remaining_batches
1352        };
1353        for batch in 0..batches {
1354            let vals = b.g.eval_words(|k| match cfg.sample_mode {
1355                SampleMode::Random => sample(batch, k),
1356                SampleMode::Small | SampleMode::Words => small_sample(batch, k),
1357            });
1358            q.stats.samples += 64;
1359            let mut bad = !Aig::word(&vals, goal);
1360            for &e in &extra {
1361                bad &= Aig::word(&vals, e);
1362            }
1363            if bad != 0 {
1364                let lane = bad.trailing_zeros();
1365                let ce = Question::counterexample(&q.symbols, |l| {
1366                    (Aig::word(&vals, l) >> lane) & 1 == 1
1367                });
1368                let o = q.refuted(b.cx, ce)?;
1369                return decided(q, o);
1370            }
1371        }
1372        let mut solver = Solver::new();
1373        if cfg.certificate {
1374            solver.log_proof();
1375        }
1376        let mut roots = vec![goal];
1377        roots.extend_from_slice(&extra);
1378        let mut cnf = Cnf::encode_with_xor3(
1379            &b.g,
1380            &roots,
1381            &mut solver,
1382            cfg.certificate,
1383            cfg.xor3_encoding,
1384        );
1385        for &e in &extra {
1386            cnf.assert(e, &mut solver);
1387        }
1388        cnf.assert(goal ^ 1, &mut solver);
1389        let mut asserted = vec![goal ^ 1];
1390        asserted.extend_from_slice(&extra);
1391        relations::strengthen(&b.g, &asserted, &cnf, &mut solver, cfg.relational_lemmas);
1392        if cfg.selector_branching {
1393            for &l in &b.selectors {
1394                if let Some(l) = cnf.mapped_lit(l) {
1395                    solver.prefer_selector(l);
1396                }
1397            }
1398        }
1399        // Swept once, as part of preparing the question: within half of the configured limits,
1400        // whatever the searches' own, so a question resumed in steps is swept as one asked at
1401        // once.
1402        let mut swept = sweep::Work::default();
1403        if cfg.sweeping {
1404            // The two sides of an equality, whose inner nodes a sweep can merge across.
1405            let sides = match b.cx.node(goal_node) {
1406                n if n.op == OpCode::Eq => match (b.bits.get(&n.a), b.bits.get(&n.b)) {
1407                    (Some(x), Some(y)) => Some((x.clone(), y.clone())),
1408                    _ => None,
1409                },
1410                _ => None,
1411            };
1412            let pending = sweep::Pending {
1413                sides,
1414                words: b.symbols.iter().map(|(_, bits)| bits.clone()).collect(),
1415                aig: core::mem::take(&mut b.g),
1416                roots,
1417                xor3: cfg.xor3_encoding,
1418                certificate: cfg.certificate,
1419            };
1420            let share = Limits {
1421                conflicts: cfg.max_conflicts / 2,
1422                propagations: cfg.max_propagations / 2,
1423            };
1424            swept = sweep::sweep(&pending, &cnf, &mut solver, share);
1425            q.stats.sweeping = Sweeping {
1426                ran: swept.ran,
1427                skipped: swept.skipped,
1428                crossings: swept.crossings,
1429                merged: swept.merged,
1430                separated: swept.separated,
1431                undecided: swept.undecided,
1432                conflicts: swept.conflicts,
1433                propagations: swept.propagations,
1434            };
1435        }
1436        q.stats.vars = solver.num_vars();
1437        q.stats.clauses = cnf.emitted();
1438        q.stats.learned = solver.num_learnts();
1439        q.stats.lemmas = solver.lemmas + swept.lemmas;
1440        q.stats.fixed = solver.num_fixed();
1441        q.stats.conflicts = swept.conflicts;
1442        q.stats.decisions = swept.decisions;
1443        q.stats.propagations = solver.propagations + swept.propagations;
1444        q.search = Some(Box::new(Search { solver, cnf, swept }));
1445        Ok(q)
1446    }
1447
1448    /// Searches within `limits` more work (counted from this call): the answer, or
1449    /// [`Unknown::Budget`] with the work done on the question so far, and the next call goes on
1450    /// from there. Once decided (here or when built), the answer is kept and returned again.
1451    /// `cx` is the context the question was built in.
1452    pub fn solve(&mut self, cx: &mut Context, limits: Limits) -> Result<Outcome, Error> {
1453        if let Some(o) = &self.outcome {
1454            return Ok(o.clone());
1455        }
1456        let Some(s) = self.search.as_mut() else {
1457            return Err(Error::Contract(
1458                "a question neither decided nor open".into(),
1459            ));
1460        };
1461        // The question's totals: its solver's and its sweep's.
1462        let totals = |s: &Search| {
1463            (
1464                s.solver.conflicts + s.swept.conflicts,
1465                s.solver.decisions + s.swept.decisions,
1466                s.solver.propagations + s.swept.propagations,
1467                s.solver.lemmas + s.swept.lemmas,
1468            )
1469        };
1470        let before = totals(s);
1471        // A zero allowance pauses the question without searching.
1472        let searching = limits.conflicts != 0 && limits.propagations != 0;
1473        let answer = s.solver.solve_within(limits);
1474        let after = totals(s);
1475        self.stats.learned = s.solver.num_learnts();
1476        self.stats.lemmas = after.3;
1477        self.stats.fixed = s.solver.num_fixed();
1478        self.stats.conflicts = after.0;
1479        self.stats.decisions = after.1;
1480        self.stats.propagations = after.2;
1481        if searching {
1482            self.stats.searches += 1;
1483            self.stats.last_conflicts = after.0 - before.0;
1484            self.stats.last_decisions = after.1 - before.1;
1485            self.stats.last_propagations = after.2 - before.2;
1486            self.stats.last_lemmas = after.3 - before.3;
1487        }
1488        let o = match answer {
1489            Answer::Unknown => {
1490                return Ok(Outcome::Unknown(Unknown::Budget {
1491                    conflicts: after.0,
1492                    propagations: after.2,
1493                }));
1494            }
1495            Answer::Unsat => {
1496                let cert = s.solver.take_proof().map(|proof| Certificate {
1497                    vars: s.solver.num_vars(),
1498                    clauses: core::mem::take(&mut s.cnf.clauses),
1499                    proof,
1500                    exhaustion: None,
1501                });
1502                Outcome::Proved(cert)
1503            }
1504            Answer::Sat(model) => {
1505                let cnf = &s.cnf;
1506                let ce = Question::counterexample(&self.symbols, |l| cnf.value(l, &model));
1507                self.refuted(cx, ce)?
1508            }
1509        };
1510        self.search = None;
1511        self.outcome = Some(o.clone());
1512        Ok(o)
1513    }
1514
1515    /// The answer, once decided.
1516    pub fn outcome(&self) -> Option<&Outcome> {
1517        self.outcome.as_ref()
1518    }
1519
1520    /// The work done on the question so far.
1521    pub fn stats(&self) -> Stats {
1522        self.stats
1523    }
1524
1525    /// The counterexample an assignment of the circuit's inputs gives.
1526    fn counterexample(symbols: &[(SymbolKey, Width, Bits)], bit: impl Fn(L) -> bool) -> Model {
1527        symbols
1528            .iter()
1529            .map(|(k, w, bits)| {
1530                let mut limbs = [0u64; 8];
1531                for (j, &b) in bits.iter().enumerate() {
1532                    if bit(b) {
1533                        limbs[j / 64] |= 1 << (j % 64);
1534                    }
1535                }
1536                (k.clone(), BitVec::wrapping_from_limbs(*w, &limbs))
1537            })
1538            .collect()
1539    }
1540
1541    /// `Refuted(ce)`, checked by bitwright's evaluator: a solver or blaster bug cannot produce a
1542    /// false refutation unnoticed.
1543    fn refuted(&self, cx: &mut Context, ce: Model) -> Result<Outcome, Error> {
1544        // (By key, the first value given for one: a model lists every symbol of the question.)
1545        let mut env: std::collections::HashMap<SymbolKey, BitVec> =
1546            std::collections::HashMap::with_capacity(ce.len());
1547        for (k, v) in &ce {
1548            env.entry(k.clone()).or_insert(*v);
1549        }
1550        let v = cx.eval(&[self.root], &env)?[0];
1551        if v.is_zero() {
1552            Ok(Outcome::Refuted(ce))
1553        } else {
1554            Err(Error::Contract(format!(
1555                "the prover's counterexample does not refute {}",
1556                cx.display(self.root)
1557            )))
1558        }
1559    }
1560}
1561
1562/// Simplification can omit original symbols: supply values consistent with their declarations
1563/// before replaying the original constrained predicate.
1564fn complete_model(cx: &mut Context, root: Expr, model: &mut Model) -> Result<(), Error> {
1565    let mut given: std::collections::HashSet<SymbolKey> =
1566        model.iter().map(|(k, _)| k.clone()).collect();
1567    for id in cx.symbols_in(&[root])? {
1568        let key = cx.symbol_key(id).unwrap().clone();
1569        if given.insert(key.clone()) {
1570            let symbol = cx.find_symbol(&key).unwrap();
1571            let value = cx.declared_known(symbol)?.map_or_else(
1572                || BitVec::zero(cx.symbol_width(id).unwrap()),
1573                |k| k.known_one(),
1574            );
1575            model.push((key, value));
1576        }
1577    }
1578    Ok(())
1579}
1580
1581/// The 64 consecutive assignments `64*batch .. 64*batch+64`, transposed into input words.
1582fn small_sample(batch: u32, k: u32) -> u64 {
1583    const LOW: [u64; 6] = [
1584        0xaaaa_aaaa_aaaa_aaaa,
1585        0xcccc_cccc_cccc_cccc,
1586        0xf0f0_f0f0_f0f0_f0f0,
1587        0xff00_ff00_ff00_ff00,
1588        0xffff_0000_ffff_0000,
1589        0xffff_ffff_0000_0000,
1590    ];
1591    if k < 6 {
1592        LOW[k as usize]
1593    } else if k - 6 < 32 && (batch >> (k - 6)) & 1 == 1 {
1594        u64::MAX
1595    } else {
1596        0
1597    }
1598}
1599
1600/// Input `k`'s word in sample batch `batch` (splitmix64 of the pair); batch 0's lanes 0 and 1
1601/// are all zeros and all ones.
1602fn sample(batch: u32, k: u32) -> u64 {
1603    let mut z = (u64::from(batch) << 32 | u64::from(k)).wrapping_add(0x9e37_79b9_7f4a_7c15);
1604    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
1605    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
1606    z ^= z >> 31;
1607    if batch == 0 { (z & !0b11) | 0b10 } else { z }
1608}
1609
1610/// Whether the 1-bit `p` is true for every value of its symbols agreeing with their declared
1611/// known bits.
1612pub fn valid(cx: &mut Context, p: Expr, cfg: &Config) -> Result<Outcome, Error> {
1613    valid_under(cx, p, None, cfg)
1614}
1615
1616/// Whether `p` is true wherever the constraints of `assumptions` and the symbols' declared
1617/// known bits hold.
1618pub fn valid_under(
1619    cx: &mut Context,
1620    p: Expr,
1621    assumptions: Option<&Assumptions>,
1622    cfg: &Config,
1623) -> Result<Outcome, Error> {
1624    Question::valid_under(cx, p, assumptions, cfg)?.solve(cx, cfg.limits())
1625}
1626
1627/// [`valid_under`], simplified by the caller's engines and not the process's
1628/// ([`Simplifiers`]): the same answer.
1629pub fn valid_under_with(
1630    cx: &mut Context,
1631    p: Expr,
1632    assumptions: Option<&Assumptions>,
1633    cfg: &Config,
1634    simplifiers: &Simplifiers,
1635) -> Result<Outcome, Error> {
1636    Question::valid_under_with(cx, p, assumptions, cfg, simplifiers)?.solve(cx, cfg.limits())
1637}
1638
1639/// Whether `a` and `b` (of one width) are equal for every value of their symbols agreeing with
1640/// their declared known bits.
1641pub fn equal(cx: &mut Context, a: Expr, b: Expr, cfg: &Config) -> Result<Outcome, Error> {
1642    Question::equal(cx, a, b, cfg)?.solve(cx, cfg.limits())
1643}
1644
1645/// Values of symbols, as a counterexample or a model gives them.
1646pub type Model = Vec<(SymbolKey, BitVec)>;
1647
1648/// A value of the symbols that makes the 1-bit `p` true, if there is one: `Refuted` of `¬p`
1649/// read back as a model (`Ok(Some)`), `Ok(None)` when `p` is unsatisfiable, and `Err` with the
1650/// reason when not decided.
1651pub fn satisfy(
1652    cx: &mut Context,
1653    p: Expr,
1654    cfg: &Config,
1655) -> Result<Result<Option<Model>, Unknown>, Error> {
1656    let np = cx.un(crate::UnOp::Not, p)?;
1657    Ok(match valid(cx, np, cfg)? {
1658        Outcome::Proved(_) => Ok(None),
1659        Outcome::Refuted(m) => Ok(Some(m)),
1660        Outcome::Unknown(why) => Err(why),
1661    })
1662}
1663
1664/// The prover the engine's passes are given ([`crate::engine::oracle`]): the circuit and the
1665/// search alone, without the simplifier (which is the engine that asks).
1666pub(crate) fn circuit_equality(
1667    cx: &mut Context,
1668    a: Expr,
1669    b: Expr,
1670    caps: &crate::engine::oracle::EqualityCaps,
1671) -> Result<crate::engine::oracle::EqualityAnswer, Error> {
1672    use crate::engine::oracle::{EqualityAnswer, EqualityVerdict};
1673    let cfg = Config::default()
1674        .with_simplify(false)
1675        .with_certificate(false)
1676        .with_samples(caps.samples)
1677        .with_max_nodes(caps.max_nodes)
1678        .with_max_conflicts(u64::MAX)
1679        .with_max_propagations(caps.max_propagations);
1680    let mut q = Question::equal(cx, a, b, &cfg)?;
1681    let out = q.solve(cx, cfg.limits())?;
1682    let stats = q.stats();
1683    let (verdict, nodes) = match out {
1684        Outcome::Proved(_) => (EqualityVerdict::Proved, stats.nodes),
1685        Outcome::Refuted(_) => (EqualityVerdict::Refuted, stats.nodes),
1686        Outcome::Unknown(Unknown::Budget { .. }) => (EqualityVerdict::Budget, stats.nodes),
1687        Outcome::Unknown(Unknown::TooLarge { nodes }) => (EqualityVerdict::Unknown, nodes),
1688        Outcome::Unknown(_) => (EqualityVerdict::Unknown, stats.nodes),
1689    };
1690    Ok(EqualityAnswer {
1691        verdict,
1692        nodes,
1693        propagations: stats.propagations,
1694    })
1695}