synth_verify/fact_spec.rs
1//! Proof-carrying specialization — VCR-PERF-002 / #494 **Phase 2**: the
2//! single-elision prototype (value-range facts ⇒ dead conditional-branch
3//! elision, the `gust_mix` clamp shape).
4//!
5//! Design source of truth: `docs/design/proof-carrying-specialization.md`
6//! ("How synth consumes facts: the per-elision proof obligation"). loom is the
7//! PROVER (its validator discharged the `wsc.facts` invariants upstream);
8//! synth is a CONDITIONAL optimizer: it never re-derives a fact — it proves
9//! the correctness of its OWN transformation *given* the fact, per elision
10//! site, BEFORE emission, through the ordeal-backed [`BvSolver`]
11//! (certificate-checked pure-Rust QF_BV; every `Unsat` verdict carries an
12//! LRAT proof validated by the trusted `ordeal-lrat` checker before it is
13//! reported).
14//!
15//! # The transformation
16//!
17//! Working on the decoded [`WasmOp`] stream (backend-agnostic — the rewritten
18//! stream feeds whichever selector the driver picks), the pass walks the
19//! function top-level with a symbolic state (stack + locals as QF_BV terms via
20//! the existing [`WasmSemantics`] encoder) and, at every no-`else`
21//! `if … end`, discharges the obligation
22//!
23//! ```text
24//! premise P (every value-range fact reached so far, asserted as a hypothesis)
25//! obligation UNSAT( P ∧ cond ≠ 0 )
26//! ```
27//!
28//! `UNSAT(P ∧ cond ≠ 0)` implies the design doc's
29//! `UNSAT(P ∧ general_lowering(x) ≠ specialized_lowering(x))`: a no-`else`
30//! `if` whose condition is 0 on every P-admissible input never executes its
31//! body, and wasm validation forces a no-`else` `if` blocktype to have
32//! identical param/result types, so the not-taken path is the identity — the
33//! general and specialized lowerings agree on every input P admits. The
34//! stronger query is deliberately used because it is decided in the pure
35//! QF_BV fragment with no control-flow encoding.
36//!
37//! - **UNSAT (certificate-checked)** → the elision is ADMITTED: the
38//! condition-producing op slice (proven pure and contiguous) plus the whole
39//! `if … end` region are deleted; the certificate line is logged per
40//! function (the evidence trail).
41//! - **Sat / Unknown / conflict-budget exceeded / any shape outside the
42//! tracked fragment** → **DECLINE LOUDLY**: the general lowering is
43//! emitted. There is no silent wrong-code path; the conservative fallback
44//! is today's codegen.
45//!
46//! # Soundness of the symbolic tracking (over-approximation discipline)
47//!
48//! * Values produced by ops outside the tracked i32 fragment never enter the
49//! state: the walk STOPS at the first untracked op (no further elisions in
50//! the function; everything already admitted was justified independently).
51//! * Locals are seeded as fresh unconstrained variables (a superset of both
52//! parameter values and the zero-init of non-param locals — sound).
53//! * A DECLINED `if` region may or may not execute: every local it assigns
54//! (at any nesting depth) is havocked to a fresh variable, and its block
55//! results are pushed as fresh variables.
56//! * An ADMITTED `if` region provably never executes, so state is unchanged.
57//! * `div`/`rem` (i32 AND i64) are tracked since Phase 2b (#494
58//! divisor-nonzero), but NEVER deleted: they can trap, and a deleted
59//! condition slice must be effect-free under ALL inputs, not just
60//! P-admissible ones — so a div result always carries `start = None`
61//! (non-erasable) and its value is havocked to a fresh variable. What
62//! Phase 2b adds is per-site TRAP-GUARD elision marks consumed by the
63//! direct selector (see "The div/rem guard obligations" below).
64//!
65//! # The div/rem guard obligations (Phase 2b, #494 divisor-nonzero)
66//!
67//! A `div`/`rem` lowering carries up to TWO trap guards, and they fall to two
68//! INDEPENDENT obligations — this is the #633/#634 two-guard distinction:
69//!
70//! ```text
71//! divide-by-zero guard (div_u/div_s/rem_u/rem_s, i32+i64):
72//! UNSAT( P ∧ divisor == 0 )
73//! INT_MIN/-1 overflow guard (div_s ONLY; rem_s(INT_MIN,-1)==0 never traps):
74//! UNSAT( P ∧ dividend == INT_MIN ∧ divisor == -1 )
75//! ```
76//!
77//! A divisor-nonzero fact (kind 3) discharges the first but NOT the second —
78//! `divisor ≠ 0` does not exclude `divisor == -1`, so the overflow guard is
79//! RETAINED unless the premises independently prove the second obligation
80//! (e.g. a value-range fact `divisor ∈ [1, N]` proves both). Each discharged
81//! obligation becomes a per-site elision mark ([`FactSpecResult::elide_div_zero`]
82//! / [`FactSpecResult::elide_div_ovf`], indices into the RETURNED stream);
83//! the driver threads them to the direct selector, which omits exactly that
84//! guard. Sat / Unknown / no-premise ⇒ loud decline, the guard is emitted.
85//!
86//! # Flag gating
87//!
88//! The driver only invokes this pass when `SYNTH_FACT_SPEC` is set (default
89//! OFF) AND the module carried a parseable `wsc.facts` section. Frozen
90//! fixtures carry no facts section, so every frozen anchor is bit-identical
91//! trivially; with the flag off the pass does not run at all.
92
93use crate::solver::{CheckOutcome, new_solver};
94use crate::term::{BV, Bool};
95use crate::wasm_semantics::WasmSemantics;
96use std::collections::{HashMap, HashSet};
97use synth_core::WasmOp;
98use synth_core::wsc_facts::{FactKind, WscFact};
99
100/// Outcome of specializing one function. `ops`/`block_arity`/`kept` are only
101/// meaningful when [`changed`](Self::changed) — otherwise they echo the input.
102#[derive(Debug)]
103pub struct FactSpecResult {
104 /// The (possibly rewritten) op stream.
105 pub ops: Vec<WasmOp>,
106 /// The blocktype-arity side-table matching `ops` (one entry per
107 /// `Block`/`Loop`/`If` in op order — entries of deleted openers removed).
108 pub block_arity: Vec<(u8, u8)>,
109 /// Indices into the ORIGINAL op stream that were kept, in order. Lets the
110 /// driver filter parallel side-tables (e.g. `op_offsets` for DWARF).
111 pub kept: Vec<usize>,
112 /// One certificate line per ADMITTED elision (logged per function).
113 pub admitted: Vec<String>,
114 /// One line per LOUD DECLINE (the general lowering is emitted for these).
115 pub declined: Vec<String>,
116 /// #494 phase 2b: indices (into the RETURNED `ops` stream) of div/rem
117 /// ops whose divide-by-zero trap guard was certificate-elided
118 /// (`UNSAT(P ∧ divisor == 0)` discharged per site).
119 pub elide_div_zero: Vec<usize>,
120 /// #494 phase 2b: indices (into the RETURNED `ops` stream) of `div_s`
121 /// ops whose `INT_MIN / -1` overflow guard was certificate-elided — a
122 /// SEPARATE obligation (`UNSAT(P ∧ dividend == INT_MIN ∧ divisor == -1)`);
123 /// a divisor-nonzero fact alone never lands here (#633/#634).
124 pub elide_div_ovf: Vec<usize>,
125 /// True when `ops` differs from the input (at least one region deletion).
126 stream_changed: bool,
127}
128
129impl FactSpecResult {
130 /// True when the op STREAM was rewritten (region deletions). Guard-elision
131 /// marks do not rewrite the stream — check
132 /// [`elide_div_zero`](Self::elide_div_zero) /
133 /// [`elide_div_ovf`](Self::elide_div_ovf) separately.
134 pub fn changed(&self) -> bool {
135 self.stream_changed
136 }
137}
138
139/// A symbolic operand-stack slot.
140#[derive(Clone)]
141struct Val {
142 bv: BV,
143 /// Start of the contiguous, side-effect-free op range that produced this
144 /// value — `None` when the producing slice is impure (`local.tee`) or not
145 /// provably contiguous. Only a `Some` slice may be deleted.
146 start: Option<usize>,
147 /// Index of the op that (last) produced this value.
148 created: usize,
149}
150
151/// Specialize one function's op stream against its `wsc.facts` premises.
152///
153/// `block_arity` is the decoder's ordinal side-table (one `(params, results)`
154/// entry per `Block`/`Loop`/`If` in op order); `facts` is the per-function
155/// slice (`CompileConfig::current_func_facts`); `params_i64` is the declared
156/// param-width table (`CompileConfig::current_func_params_i64` — `true` ⇒
157/// param `k` is 64-bit), which fixes the symbolic width of a param
158/// `local.get` (Phase 2b tracks i64 divisors). Total: every input yields a
159/// result — inapplicable shapes surface as loud declines, never errors.
160pub fn specialize_function(
161 func_name: &str,
162 ops: &[WasmOp],
163 block_arity: &[(u8, u8)],
164 facts: &[WscFact],
165 params_i64: &[bool],
166) -> FactSpecResult {
167 let mut pass = Pass::new(func_name, ops, block_arity, facts, params_i64);
168 pass.walk();
169 pass.finish()
170}
171
172/// #494 phase 2b RED-TEAM lever (debug builds ONLY): treat a Sat verdict on
173/// the divide-by-zero guard obligation as an admit anyway. Exists so the
174/// differential oracle can DEMONSTRATE the divergence an unsound admit would
175/// cause (wasmtime traps at divisor == 0, the forced build does not) and then
176/// show the Sat-decline restoring the guard byte-identically. Compiled out of
177/// release builds; every forced admit screams in its certificate line.
178#[cfg(debug_assertions)]
179fn force_admit_unsound() -> bool {
180 std::env::var("SYNTH_FACT_SPEC_FORCE_ADMIT").is_ok_and(|v| v != "0")
181}
182
183#[cfg(not(debug_assertions))]
184fn force_admit_unsound() -> bool {
185 false
186}
187
188struct Pass<'a> {
189 func: &'a str,
190 ops: &'a [WasmOp],
191 block_arity: &'a [(u8, u8)],
192 /// op index → ordinal into `block_arity` (for `Block`/`Loop`/`If` ops).
193 opener_ordinal: HashMap<usize, usize>,
194 /// op index → signed range fact attached to that op's result (raw s64
195 /// bounds; clamped to the value's width at attach time).
196 range_facts: HashMap<usize, (i64, i64)>,
197 /// op indices carrying a divisor-nonzero fact (kind 3): `value ≠ 0`.
198 nonzero_facts: HashSet<usize>,
199 /// Declared param widths (`true` ⇒ 64-bit) — fixes `local.get` widths.
200 params_i64: &'a [bool],
201 sem: WasmSemantics,
202 stack: Vec<Val>,
203 locals: HashMap<u32, BV>,
204 /// Every fresh variable created (name order), for Sat counterexamples.
205 vars: Vec<BV>,
206 fresh: u32,
207 premises: Vec<Bool>,
208 premise_desc: Vec<String>,
209 /// Inclusive op-index ranges to delete (disjoint, ascending).
210 deletions: Vec<(usize, usize)>,
211 admitted: Vec<String>,
212 declined: Vec<String>,
213 /// #494 phase 2b: ORIGINAL op indices marked for zero-guard elision.
214 zero_marks: Vec<usize>,
215 /// #494 phase 2b: ORIGINAL op indices marked for overflow-guard elision.
216 ovf_marks: Vec<usize>,
217}
218
219impl<'a> Pass<'a> {
220 fn new(
221 func: &'a str,
222 ops: &'a [WasmOp],
223 block_arity: &'a [(u8, u8)],
224 facts: &'a [WscFact],
225 params_i64: &'a [bool],
226 ) -> Self {
227 let mut opener_ordinal = HashMap::new();
228 let mut ord = 0usize;
229 for (i, op) in ops.iter().enumerate() {
230 if matches!(op, WasmOp::Block | WasmOp::Loop | WasmOp::If) {
231 opener_ordinal.insert(i, ord);
232 ord += 1;
233 }
234 }
235 let mut range_facts = HashMap::new();
236 let mut nonzero_facts = HashSet::new();
237 for f in facts {
238 // Out-of-range value_id is vacuous (encoding doc's rule).
239 if (f.value_id as usize) >= ops.len() {
240 continue;
241 }
242 match f.kind {
243 FactKind::ValueRange { lo, hi } => {
244 // Raw s64 bounds; clamped to the value's width when the
245 // walk attaches the premise. An inverted bound is vacuous.
246 if lo <= hi {
247 range_facts.insert(f.value_id as usize, (lo, hi));
248 }
249 }
250 // #494 phase 2b: divisor-nonzero (kind 3) — `value ≠ 0`.
251 FactKind::DivisorNonZero => {
252 nonzero_facts.insert(f.value_id as usize);
253 }
254 _ => {}
255 }
256 }
257 Self {
258 func,
259 ops,
260 block_arity,
261 opener_ordinal,
262 range_facts,
263 nonzero_facts,
264 params_i64,
265 // No memory model needed: memory ops are outside the tracked
266 // fragment (the walk stops there).
267 sem: WasmSemantics::new_with_memory(Vec::new()),
268 stack: Vec::new(),
269 locals: HashMap::new(),
270 vars: Vec::new(),
271 fresh: 0,
272 premises: Vec::new(),
273 premise_desc: Vec::new(),
274 deletions: Vec::new(),
275 admitted: Vec::new(),
276 declined: Vec::new(),
277 zero_marks: Vec::new(),
278 ovf_marks: Vec::new(),
279 }
280 }
281
282 fn fresh_var(&mut self, name: String) -> BV {
283 let v = BV::new_const(name, 32);
284 self.vars.push(v.clone());
285 v
286 }
287
288 fn local_bv(&mut self, idx: u32) -> BV {
289 if let Some(bv) = self.locals.get(&idx) {
290 return bv.clone();
291 }
292 // A not-yet-seen local's width comes from the declared param table
293 // (#494 phase 2b tracks i64 divisors); non-param locals default to
294 // 32 bits — an i64 op reading one fails the width check and declines.
295 let width = if self.params_i64.get(idx as usize).copied().unwrap_or(false) {
296 64
297 } else {
298 32
299 };
300 let v = BV::new_const(format!("fs_l{idx}"), width);
301 self.vars.push(v.clone());
302 self.locals.insert(idx, v.clone());
303 v
304 }
305
306 /// Attach the premises of every fact naming op `i`'s result, at the
307 /// value's own width.
308 fn attach_fact(&mut self, i: usize, bv: &BV) {
309 let width = bv.get_size();
310 if let Some(&(lo, hi)) = self.range_facts.get(&i) {
311 // Clamp the s64 bound to the value's width (the phase-2 rule for
312 // 32-bit values; 64-bit values take the bound verbatim). A bound
313 // that inverts after clamping is impossible for a genuine value
314 // of this width — fact validity is loom's obligation (trust
315 // split), so we keep the phase-2 clamp semantics unchanged.
316 let (lo, hi) = if width == 32 {
317 (
318 lo.clamp(i64::from(i32::MIN), i64::from(i32::MAX)),
319 hi.clamp(i64::from(i32::MIN), i64::from(i32::MAX)),
320 )
321 } else {
322 (lo, hi)
323 };
324 let lo_bv = BV::from_i64(lo, width);
325 let hi_bv = BV::from_i64(hi, width);
326 let p = Bool::and(&[&bv.bvsge(&lo_bv), &bv.bvsle(&hi_bv)]);
327 self.premises.push(p);
328 self.premise_desc
329 .push(format!("value(op#{i}) ∈ [{lo}, {hi}] (signed, i{width})"));
330 }
331 if self.nonzero_facts.contains(&i) {
332 // #494 phase 2b: divisor-nonzero (kind 3).
333 let p = bv.ne(BV::from_i64(0, width));
334 self.premises.push(p);
335 self.premise_desc
336 .push(format!("value(op#{i}) ≠ 0 (i{width})"));
337 }
338 }
339
340 fn push(&mut self, bv: BV, start: Option<usize>, created: usize) {
341 self.stack.push(Val { bv, start, created });
342 }
343
344 /// Find the matching `End` for the opener at `i`; also reports whether a
345 /// top-level `Else` occurs. `None` = malformed nesting (stop the walk).
346 fn matching_end(&self, i: usize) -> Option<(usize, bool)> {
347 let mut depth = 0usize;
348 let mut has_else = false;
349 for (j, op) in self.ops.iter().enumerate().skip(i + 1) {
350 match op {
351 WasmOp::Block | WasmOp::Loop | WasmOp::If => depth += 1,
352 WasmOp::Else if depth == 0 => has_else = true,
353 WasmOp::End => {
354 if depth == 0 {
355 return Some((j, has_else));
356 }
357 depth -= 1;
358 }
359 _ => {}
360 }
361 }
362 None
363 }
364
365 /// Continuation after a DECLINED `if` region `[i..=end]`: the body may or
366 /// may not run, so havoc every local it assigns (any depth) and model its
367 /// block results as fresh variables.
368 fn havoc_region(&mut self, i: usize, end: usize, arity: (u8, u8)) {
369 let ops = self.ops;
370 for op in &ops[i + 1..end] {
371 if let WasmOp::LocalSet(idx) | WasmOp::LocalTee(idx) = op {
372 let n = self.fresh;
373 self.fresh += 1;
374 let v = self.fresh_var(format!("fs_h{n}"));
375 self.locals.insert(*idx, v);
376 }
377 }
378 for _ in 0..arity.0 {
379 self.stack.pop();
380 }
381 for k in 0..arity.1 {
382 let n = self.fresh;
383 self.fresh += 1;
384 let v = self.fresh_var(format!("fs_r{n}_{k}"));
385 self.push(v, None, end);
386 }
387 }
388
389 fn decline(&mut self, msg: String) {
390 self.declined
391 .push(format!("{}: {} — general lowering emitted", self.func, msg));
392 }
393
394 /// #494 phase 2b: discharge the per-site div/rem trap-guard obligations
395 /// for the op at `i` (`op_name`, operand width `width`, dividend `a`,
396 /// divisor `b`), recording elision marks for the lowering. TWO independent
397 /// obligations (the #633/#634 two-guard distinction):
398 ///
399 /// - zero guard (every div/rem): `UNSAT(P ∧ divisor == 0)`;
400 /// - overflow guard (`div_s` only): `UNSAT(P ∧ dividend == INT_MIN ∧
401 /// divisor == -1)` — divisor-nonzero alone NEVER discharges this.
402 ///
403 /// Sat / Unknown / no-premise ⇒ loud decline; the guard is emitted.
404 fn try_elide_div_guards(&mut self, i: usize, op_name: &str, is_div_s: bool, a: &Val, b: &Val) {
405 let width = b.bv.get_size();
406 if self.premises.is_empty() {
407 self.decline(format!(
408 "op#{i} {op_name} — no premise reaches this site; both trap guards retained"
409 ));
410 return;
411 }
412 // Obligation 1: the divide-by-zero guard.
413 let mut solver = new_solver();
414 for p in &self.premises {
415 solver.assert(p);
416 }
417 solver.assert(&b.bv.eq(BV::from_i64(0, width)));
418 match solver.check() {
419 CheckOutcome::Unsat => {
420 self.zero_marks.push(i);
421 self.admitted.push(format!(
422 "{}: op#{i} {op_name} — divide-by-zero guard elided: UNSAT(P ∧ divisor == 0) via {} (certificate-checked QF_BV; every Unsat carries an LRAT proof validated by ordeal-lrat); P = {{{}}}; divisor = {}",
423 self.func,
424 solver.name(),
425 self.premise_desc.join(" ∧ "),
426 b.bv,
427 ));
428 }
429 CheckOutcome::Sat => {
430 let cex = self.counterexample(solver.as_ref());
431 if force_admit_unsound() {
432 // RED-TEAM lever (debug builds only): admit the Sat site
433 // anyway so the differential oracle can demonstrate the
434 // divergence. Screams, and still logs the model.
435 self.zero_marks.push(i);
436 self.admitted.push(format!(
437 "{}: op#{i} {op_name} — divide-by-zero guard elided by UNSOUND FORCED ADMIT (SYNTH_FACT_SPEC_FORCE_ADMIT, red-team oracle lever, debug builds only) — obligation was Sat (counterexample: {cex}); NEVER use in production",
438 self.func,
439 ));
440 } else {
441 self.decline(format!(
442 "op#{i} {op_name} — zero-guard obligation Sat (divisor can be 0 under P; counterexample: {cex}); guard retained"
443 ));
444 }
445 }
446 CheckOutcome::Unknown(reason) => {
447 self.decline(format!(
448 "op#{i} {op_name} — zero-guard obligation Unknown ({reason}); conservative decline, guard retained"
449 ));
450 }
451 }
452 // Obligation 2: the INT_MIN/-1 overflow guard — div_s only, and a
453 // SEPARATE proof (#633/#634): divisor ≠ 0 does not exclude -1.
454 if !is_div_s {
455 return;
456 }
457 let int_min = if width == 64 {
458 i64::MIN
459 } else {
460 i64::from(i32::MIN)
461 };
462 let mut solver = new_solver();
463 for p in &self.premises {
464 solver.assert(p);
465 }
466 solver.assert(&a.bv.eq(BV::from_i64(int_min, width)));
467 solver.assert(&b.bv.eq(BV::from_i64(-1, width)));
468 match solver.check() {
469 CheckOutcome::Unsat => {
470 self.ovf_marks.push(i);
471 self.admitted.push(format!(
472 "{}: op#{i} {op_name} — INT{width}_MIN/-1 overflow guard elided: UNSAT(P ∧ dividend == INT{width}_MIN ∧ divisor == -1) via {} (certificate-checked QF_BV; every Unsat carries an LRAT proof validated by ordeal-lrat); P = {{{}}}",
473 self.func,
474 solver.name(),
475 self.premise_desc.join(" ∧ "),
476 ));
477 }
478 CheckOutcome::Sat => {
479 let cex = self.counterexample(solver.as_ref());
480 self.decline(format!(
481 "op#{i} {op_name} — overflow-guard obligation Sat (dividend == INT{width}_MIN with divisor == -1 is possible under P; counterexample: {cex}); the #633 overflow guard is RETAINED — a divisor-nonzero premise alone never elides it"
482 ));
483 }
484 CheckOutcome::Unknown(reason) => {
485 self.decline(format!(
486 "op#{i} {op_name} — overflow-guard obligation Unknown ({reason}); conservative decline, the #633 overflow guard is RETAINED"
487 ));
488 }
489 }
490 }
491
492 /// Read the model back for an actionable counterexample string.
493 fn counterexample(&self, solver: &dyn crate::solver::BvSolver) -> String {
494 let cex: Vec<String> = self
495 .vars
496 .iter()
497 .filter_map(|v| {
498 let name = format!("{v}");
499 solver.value(v).map(|x| {
500 if v.get_size() == 64 {
501 format!("{name}={}", x as u64 as i64)
502 } else {
503 format!("{name}={}", x as u32 as i32)
504 }
505 })
506 })
507 .collect();
508 if cex.is_empty() {
509 "<no model>".to_string()
510 } else {
511 cex.join(", ")
512 }
513 }
514
515 /// Discharge the per-elision obligation for the no-`else` `if` at `i`
516 /// (matching `End` at `end`, condition `cond`). Returns true iff admitted.
517 fn try_elide(&mut self, i: usize, end: usize, cond: &Val) -> bool {
518 if self.premises.is_empty() {
519 self.decline(format!(
520 "op#{i} `if` — no premise reaches this site (no usable value-range fact)"
521 ));
522 return false;
523 }
524 let mut solver = new_solver();
525 for p in &self.premises {
526 solver.assert(p);
527 }
528 let taken = cond.bv.ne(BV::from_i64(0, 32));
529 solver.assert(&taken);
530 match solver.check() {
531 CheckOutcome::Unsat => {
532 let Some(start) = cond.start else {
533 // Proven dead, but the condition slice has a side effect
534 // (`local.tee`) or is not provably contiguous — deleting
535 // it could drop live work. Conservative: keep everything.
536 self.decline(format!(
537 "op#{i} `if` proven dead (UNSAT) but its condition slice is not \
538 erasable (impure or non-contiguous producer)"
539 ));
540 return false;
541 };
542 self.deletions.push((start, end));
543 self.admitted.push(format!(
544 "{}: op#{i} `if` (+condition slice) — ops [{start}..={end}] elided \
545 ({} ops): UNSAT(P ∧ cond ≠ 0) via {} (certificate-checked QF_BV; \
546 every Unsat carries an LRAT proof validated by ordeal-lrat); \
547 P = {{{}}}; cond = {}",
548 self.func,
549 end - start + 1,
550 solver.name(),
551 self.premise_desc.join(" ∧ "),
552 cond.bv,
553 ));
554 true
555 }
556 CheckOutcome::Sat => {
557 // Read the model back for an actionable counterexample.
558 let cex: Vec<String> = self
559 .vars
560 .iter()
561 .filter_map(|v| {
562 let name = format!("{v}");
563 solver
564 .value(v)
565 .map(|x| format!("{name}={}", x as u32 as i32))
566 })
567 .collect();
568 self.decline(format!(
569 "op#{i} `if` — obligation Sat (branch reachable under P; \
570 counterexample: {})",
571 if cex.is_empty() {
572 "<no model>".to_string()
573 } else {
574 cex.join(", ")
575 }
576 ));
577 false
578 }
579 CheckOutcome::Unknown(reason) => {
580 self.decline(format!(
581 "op#{i} `if` — obligation Unknown ({reason}); conservative decline"
582 ));
583 false
584 }
585 }
586 }
587
588 fn walk(&mut self) {
589 if self.range_facts.is_empty() && self.nonzero_facts.is_empty() {
590 self.decline(
591 "no usable value-range or divisor-nonzero fact targets this function".to_string(),
592 );
593 return;
594 }
595 let ops = self.ops;
596 let mut i = 0usize;
597 while i < ops.len() {
598 let op = &ops[i];
599 match op {
600 WasmOp::Nop => {}
601 WasmOp::I32Const(v) => {
602 let bv = self.sem.encode_op(&WasmOp::I32Const(*v), &[]);
603 self.attach_fact(i, &bv);
604 self.push(bv, Some(i), i);
605 }
606 // #494 phase 2b: tracked so an i64 divisor term can be built
607 // (the i64 fragment is const/local/div-rem only — anything
608 // else stops the walk as before).
609 WasmOp::I64Const(v) => {
610 let bv = self.sem.encode_op(&WasmOp::I64Const(*v), &[]);
611 self.attach_fact(i, &bv);
612 self.push(bv, Some(i), i);
613 }
614 WasmOp::LocalGet(idx) => {
615 let bv = self.local_bv(*idx);
616 self.attach_fact(i, &bv);
617 self.push(bv, Some(i), i);
618 }
619 WasmOp::LocalSet(idx) => {
620 let Some(v) = self.stack.pop() else {
621 self.decline(format!("op#{i} local.set on empty symbolic stack"));
622 return;
623 };
624 self.locals.insert(*idx, v.bv);
625 }
626 WasmOp::LocalTee(idx) => {
627 let Some(top) = self.stack.last_mut() else {
628 self.decline(format!("op#{i} local.tee on empty symbolic stack"));
629 return;
630 };
631 // The tee is a side effect: its slice must never be
632 // deleted as a "pure condition producer".
633 top.start = None;
634 top.created = i;
635 let bv = top.bv.clone();
636 self.locals.insert(*idx, bv.clone());
637 self.attach_fact(i, &bv);
638 }
639 WasmOp::Drop => {
640 if self.stack.pop().is_none() {
641 self.decline(format!("op#{i} drop on empty symbolic stack"));
642 return;
643 }
644 }
645 WasmOp::I32Eqz => {
646 let Some(a) = self.stack.pop() else {
647 self.decline(format!("op#{i} unary op on empty symbolic stack"));
648 return;
649 };
650 if a.bv.get_size() != 32 {
651 self.decline(format!("op#{i} i32.eqz on a non-32-bit operand"));
652 return;
653 }
654 let bv = self.sem.encode_op(op, &[a.bv]);
655 self.attach_fact(i, &bv);
656 let start = a.start.filter(|_| a.created + 1 == i);
657 self.push(bv, start, i);
658 }
659 // Tracked, trap-free i32 binops (div/rem excluded on purpose:
660 // they can trap, and a deleted slice must be effect-free).
661 WasmOp::I32Add
662 | WasmOp::I32Sub
663 | WasmOp::I32Mul
664 | WasmOp::I32And
665 | WasmOp::I32Or
666 | WasmOp::I32Xor
667 | WasmOp::I32Shl
668 | WasmOp::I32ShrS
669 | WasmOp::I32ShrU
670 | WasmOp::I32Rotl
671 | WasmOp::I32Rotr
672 | WasmOp::I32Eq
673 | WasmOp::I32Ne
674 | WasmOp::I32LtS
675 | WasmOp::I32LtU
676 | WasmOp::I32LeS
677 | WasmOp::I32LeU
678 | WasmOp::I32GtS
679 | WasmOp::I32GtU
680 | WasmOp::I32GeS
681 | WasmOp::I32GeU => {
682 let (Some(b), Some(a)) = (self.stack.pop(), self.stack.pop()) else {
683 self.decline(format!("op#{i} binop on underflowing symbolic stack"));
684 return;
685 };
686 if a.bv.get_size() != 32 || b.bv.get_size() != 32 {
687 self.decline(format!("op#{i} i32 binop on a non-32-bit operand"));
688 return;
689 }
690 let bv = self.sem.encode_op(op, &[a.bv, b.bv]);
691 self.attach_fact(i, &bv);
692 // Contiguity proof for the combined producer slice:
693 // a's slice, immediately followed by b's, immediately
694 // followed by this op. Anything else ⇒ not erasable.
695 let start = match (a.start, b.start) {
696 (Some(sa), Some(sb)) if a.created + 1 == sb && b.created + 1 == i => {
697 Some(sa)
698 }
699 _ => None,
700 };
701 self.push(bv, start, i);
702 }
703 // #494 phase 2b: i32/i64 div/rem — TRACKED (upgrading the
704 // phase-2 hard stop), never DELETED. The op can trap, so its
705 // result carries `start = None` (it can never sit inside an
706 // erasable condition slice); the walk instead discharges the
707 // per-site guard obligations (see the module docs' two-guard
708 // distinction) and marks the op for the lowering. Downstream
709 // soundness: if the op traps, nothing after it executes (any
710 // later admitted elision is vacuous on that path); if it does
711 // not, its result is havocked to a fresh variable.
712 WasmOp::I32DivU
713 | WasmOp::I32DivS
714 | WasmOp::I32RemU
715 | WasmOp::I32RemS
716 | WasmOp::I64DivU
717 | WasmOp::I64DivS
718 | WasmOp::I64RemU
719 | WasmOp::I64RemS => {
720 let (Some(b), Some(a)) = (self.stack.pop(), self.stack.pop()) else {
721 self.decline(format!("op#{i} div/rem on underflowing symbolic stack"));
722 return;
723 };
724 let (op_name, expect, is_div_s) = match op {
725 WasmOp::I32DivU => ("i32.div_u", 32, false),
726 WasmOp::I32DivS => ("i32.div_s", 32, true),
727 WasmOp::I32RemU => ("i32.rem_u", 32, false),
728 WasmOp::I32RemS => ("i32.rem_s", 32, false),
729 WasmOp::I64DivU => ("i64.div_u", 64, false),
730 WasmOp::I64DivS => ("i64.div_s", 64, true),
731 WasmOp::I64RemU => ("i64.rem_u", 64, false),
732 _ => ("i64.rem_s", 64, false),
733 };
734 if a.bv.get_size() != expect || b.bv.get_size() != expect {
735 self.decline(format!(
736 "op#{i} {op_name} on operands of unexpected width (symbolic widths {}/{}, expected {expect})",
737 a.bv.get_size(),
738 b.bv.get_size()
739 ));
740 return;
741 }
742 self.try_elide_div_guards(i, op_name, is_div_s, &a, &b);
743 // Havoc the result; `start = None` keeps a possibly-
744 // trapping op out of every erasable condition slice.
745 let n = self.fresh;
746 self.fresh += 1;
747 let v = self.fresh_var(format!("fs_d{n}"));
748 self.attach_fact(i, &v);
749 self.push(v, None, i);
750 }
751 WasmOp::If => {
752 let Some(cond) = self.stack.pop() else {
753 self.decline(format!("op#{i} `if` on empty symbolic stack"));
754 return;
755 };
756 if cond.bv.get_size() != 32 {
757 self.decline(format!("op#{i} `if` condition is not 32-bit"));
758 return;
759 }
760 let Some((end, has_else)) = self.matching_end(i) else {
761 self.decline(format!("op#{i} `if` without matching `end`"));
762 return;
763 };
764 let Some(&ord) = self.opener_ordinal.get(&i) else {
765 self.decline(format!("op#{i} `if` missing from the opener ordinal map"));
766 return;
767 };
768 let Some(&arity) = self.block_arity.get(ord) else {
769 self.decline(format!(
770 "op#{i} `if` has no block_arity entry (side-table desync)"
771 ));
772 return;
773 };
774 if has_else {
775 self.decline(format!(
776 "op#{i} `if`/`else` — only no-else `if` is in Phase-2 scope"
777 ));
778 self.havoc_region(i, end, arity);
779 } else if self.try_elide(i, end, &cond) {
780 // Region provably never executes: state unchanged
781 // (params-as-results pass-through is the identity for
782 // a no-else `if`, whose blocktype has equal
783 // param/result types by wasm validation).
784 } else {
785 self.havoc_region(i, end, arity);
786 }
787 i = end + 1;
788 continue;
789 }
790 // Function-final `End` (top-level): done.
791 WasmOp::End => break,
792 WasmOp::Return => break,
793 other => {
794 // First op outside the tracked fragment: stop. Everything
795 // already admitted was justified independently of what
796 // follows; declining the REST loudly keeps honesty.
797 self.decline(format!(
798 "op#{i} {other:?} is outside the tracked i32 fragment — \
799 fact tracking stops here (no further elisions in this function)"
800 ));
801 return;
802 }
803 }
804 i += 1;
805 }
806 }
807
808 fn finish(self) -> FactSpecResult {
809 let Pass {
810 ops,
811 block_arity,
812 deletions,
813 admitted,
814 declined,
815 zero_marks,
816 ovf_marks,
817 ..
818 } = self;
819 if deletions.is_empty() {
820 return FactSpecResult {
821 ops: ops.to_vec(),
822 block_arity: block_arity.to_vec(),
823 kept: (0..ops.len()).collect(),
824 admitted,
825 declined,
826 // No rewrite ⇒ original indices ARE the output indices.
827 elide_div_zero: zero_marks,
828 elide_div_ovf: ovf_marks,
829 stream_changed: false,
830 };
831 }
832 let deleted = |i: usize| deletions.iter().any(|&(s, e)| i >= s && i <= e);
833 let mut out_ops = Vec::with_capacity(ops.len());
834 let mut out_arity = Vec::with_capacity(block_arity.len());
835 let mut kept = Vec::with_capacity(ops.len());
836 let mut ord = 0usize;
837 for (i, op) in ops.iter().enumerate() {
838 let is_opener = matches!(op, WasmOp::Block | WasmOp::Loop | WasmOp::If);
839 if !deleted(i) {
840 out_ops.push(op.clone());
841 kept.push(i);
842 if is_opener && let Some(&a) = block_arity.get(ord) {
843 out_arity.push(a);
844 }
845 }
846 if is_opener {
847 ord += 1;
848 }
849 }
850 // Remap the guard-elision marks into the REWRITTEN index space. A
851 // marked div/rem can never sit inside a deleted range (deleted ranges
852 // are contiguous PURE condition slices plus proven-dead `if` regions
853 // the walk skipped over; a div result's `start = None` bars it from
854 // any erasable slice) — the filter below is defense in depth.
855 let remap = |marks: Vec<usize>| -> Vec<usize> {
856 marks
857 .into_iter()
858 .filter_map(|m| {
859 debug_assert!(!deleted(m), "guard mark op#{m} inside a deleted range");
860 kept.binary_search(&m).ok()
861 })
862 .collect()
863 };
864 FactSpecResult {
865 ops: out_ops,
866 block_arity: out_arity,
867 elide_div_zero: remap(zero_marks),
868 elide_div_ovf: remap(ovf_marks),
869 kept,
870 admitted,
871 declined,
872 stream_changed: true,
873 }
874 }
875}
876
877#[cfg(test)]
878mod tests {
879 use super::*;
880 use WasmOp::*;
881
882 fn fact(value_id: u32, lo: i64, hi: i64) -> WscFact {
883 WscFact {
884 func_index: 0,
885 value_id,
886 kind: FactKind::ValueRange { lo, hi },
887 }
888 }
889
890 /// The gust_mix clamp shape: clamp(ch + 476, 1000, 2000) via two
891 /// no-else `if`s over a local.
892 fn clamp_ops() -> Vec<WasmOp> {
893 vec![
894 LocalGet(0), // 0 ch ← fact target
895 I32Const(476), // 1
896 I32Add, // 2 v = ch+476
897 LocalSet(1), // 3
898 LocalGet(1), // 4
899 I32Const(1000), // 5
900 I32LtS, // 6
901 If, // 7
902 I32Const(1000), // 8
903 LocalSet(1), // 9
904 End, // 10
905 LocalGet(1), // 11
906 I32Const(2000), // 12
907 I32GtS, // 13
908 If, // 14
909 I32Const(2000), // 15
910 LocalSet(1), // 16
911 End, // 17
912 LocalGet(1), // 18
913 End, // 19
914 ]
915 }
916
917 const CLAMP_ARITY: &[(u8, u8)] = &[(0, 0), (0, 0)];
918
919 #[test]
920 fn clamp_shape_elides_both_branches_under_the_proven_bound_494() {
921 let ops = clamp_ops();
922 let r = specialize_function("gust_mix", &ops, CLAMP_ARITY, &[fact(0, 524, 1524)], &[]);
923 assert_eq!(r.admitted.len(), 2, "declines: {:?}", r.declined);
924 assert!(r.changed());
925 assert_eq!(
926 r.ops,
927 vec![
928 LocalGet(0),
929 I32Const(476),
930 I32Add,
931 LocalSet(1),
932 LocalGet(1),
933 End
934 ],
935 "both clamp comparisons + branches + bodies must be gone"
936 );
937 assert_eq!(r.block_arity, vec![], "both If arity entries removed");
938 assert_eq!(r.kept, vec![0, 1, 2, 3, 18, 19]);
939 // The certificate evidence trail names the engine and the premise.
940 for line in &r.admitted {
941 assert!(line.contains("UNSAT"), "{line}");
942 assert!(line.contains("certificate-checked"), "{line}");
943 assert!(line.contains("[524, 1524]"), "{line}");
944 }
945 }
946
947 #[test]
948 fn wrong_wide_bound_is_sat_and_declines_loudly_494() {
949 // ch ∈ [0, 4000] does NOT make the clamp dead (ch=0 → v=476 < 1000):
950 // the obligation is Sat and BOTH sites decline with a counterexample.
951 let ops = clamp_ops();
952 let r = specialize_function("gust_mix", &ops, CLAMP_ARITY, &[fact(0, 0, 4000)], &[]);
953 assert_eq!(r.admitted.len(), 0);
954 assert!(!r.changed());
955 assert_eq!(r.ops, ops, "declined ⇒ byte-identical op stream");
956 assert_eq!(r.block_arity, CLAMP_ARITY.to_vec());
957 assert!(
958 r.declined
959 .iter()
960 .any(|d| d.contains("Sat") && d.contains("counterexample")),
961 "declines must be loud and carry a model: {:?}",
962 r.declined
963 );
964 }
965
966 #[test]
967 fn partially_dead_bound_elides_only_the_proven_branch_494() {
968 // ch ∈ [524, 4000]: v ≥ 1000 so the LOW clamp is dead, but v can
969 // exceed 2000 so the HIGH clamp must survive.
970 let ops = clamp_ops();
971 let r = specialize_function("gust_mix", &ops, CLAMP_ARITY, &[fact(0, 524, 4000)], &[]);
972 assert_eq!(r.admitted.len(), 1, "declines: {:?}", r.declined);
973 assert_eq!(r.declined.len(), 1);
974 assert_eq!(
975 r.ops,
976 vec![
977 LocalGet(0),
978 I32Const(476),
979 I32Add,
980 LocalSet(1),
981 LocalGet(1),
982 I32Const(2000),
983 I32GtS,
984 If,
985 I32Const(2000),
986 LocalSet(1),
987 End,
988 LocalGet(1),
989 End,
990 ]
991 );
992 assert_eq!(r.block_arity, vec![(0, 0)], "one If survives");
993 }
994
995 #[test]
996 fn no_facts_changes_nothing_494() {
997 let ops = clamp_ops();
998 let r = specialize_function("gust_mix", &ops, CLAMP_ARITY, &[], &[]);
999 assert!(!r.changed());
1000 assert_eq!(r.ops, ops);
1001 assert!(!r.declined.is_empty(), "the no-fact case is a loud decline");
1002 }
1003
1004 #[test]
1005 fn declined_if_havocs_its_locals_no_false_admit_downstream_494() {
1006 // The FIRST if is undecidable (condition on an unconstrained local),
1007 // and its body rewrites local 1 — so the SECOND if (which would be
1008 // dead under the fact alone) must NOT be admitted: local 1 is
1009 // havocked by the declined region.
1010 let ops = vec![
1011 LocalGet(0), // 0 ← fact ch ∈ [524, 1524]
1012 I32Const(476), // 1
1013 I32Add, // 2
1014 LocalSet(1), // 3
1015 LocalGet(2), // 4 unconstrained
1016 If, // 5
1017 I32Const(-9), // 6
1018 LocalSet(1), // 7 havocs local 1
1019 End, // 8
1020 LocalGet(1), // 9
1021 I32Const(2000), // 10
1022 I32GtS, // 11
1023 If, // 12
1024 I32Const(2000), // 13
1025 LocalSet(1), // 14
1026 End, // 15
1027 LocalGet(1), // 16
1028 End, // 17
1029 ];
1030 let r = specialize_function("f", &ops, CLAMP_ARITY, &[fact(0, 524, 1524)], &[]);
1031 assert_eq!(
1032 r.admitted.len(),
1033 0,
1034 "havocked local must block the downstream elision: {:?}",
1035 r.admitted
1036 );
1037 assert_eq!(r.ops, ops);
1038 }
1039
1040 #[test]
1041 fn if_with_else_declines_494() {
1042 let ops = vec![
1043 LocalGet(0), // 0 ← fact forces cond = 0
1044 If, // 1
1045 I32Const(1), // 2
1046 LocalSet(1), // 3
1047 Else, // 4
1048 I32Const(2), // 5
1049 LocalSet(1), // 6
1050 End, // 7
1051 LocalGet(1), // 8
1052 End, // 9
1053 ];
1054 let r = specialize_function("f", &ops, &[(0, 0)], &[fact(0, 0, 0)], &[]);
1055 assert_eq!(r.admitted.len(), 0);
1056 assert!(
1057 r.declined.iter().any(|d| d.contains("else")),
1058 "{:?}",
1059 r.declined
1060 );
1061 assert_eq!(r.ops, ops);
1062 }
1063
1064 #[test]
1065 fn nested_opener_inside_elided_body_fixes_block_arity_ordinals_494() {
1066 // A dead outer if contains a nested if: BOTH arity entries vanish and
1067 // the SURVIVING later block keeps its (translated) entry.
1068 let ops = vec![
1069 LocalGet(0), // 0 ← fact [5,5] ⇒ eqz = 0
1070 I32Eqz, // 1
1071 If, // 2 (ordinal 0)
1072 LocalGet(0), // 3
1073 If, // 4 (ordinal 1, nested)
1074 I32Const(7), // 5
1075 LocalSet(1), // 6
1076 End, // 7
1077 End, // 8
1078 Block, // 9 (ordinal 2, survives)
1079 End, // 10
1080 End, // 11
1081 ];
1082 let arity = &[(0, 0), (0, 0), (0, 1)];
1083 let r = specialize_function("f", &ops, arity, &[fact(0, 5, 5)], &[]);
1084 assert_eq!(r.admitted.len(), 1, "declines: {:?}", r.declined);
1085 // The condition slice starts at op 0 (LocalGet feeds the eqz), so the
1086 // whole deleted range is [0..=8]; only the trailing block survives.
1087 assert_eq!(r.ops, vec![Block, End, End]);
1088 assert_eq!(r.kept, vec![9, 10, 11]);
1089 assert_eq!(
1090 r.block_arity,
1091 vec![(0, 1)],
1092 "only the surviving Block's entry"
1093 );
1094 }
1095
1096 #[test]
1097 fn tee_condition_slice_is_not_erasable_494() {
1098 // cond built through local.tee: proven dead, but deleting the slice
1099 // would lose the local write ⇒ decline (loud), stream unchanged.
1100 let ops = vec![
1101 LocalGet(0), // 0 ← fact [1,1]
1102 LocalTee(1), // 1 side effect in the slice
1103 I32Eqz, // 2 = 0 under the fact
1104 If, // 3
1105 I32Const(9), // 4
1106 LocalSet(2), // 5
1107 End, // 6
1108 End, // 7
1109 ];
1110 let r = specialize_function("f", &ops, &[(0, 0)], &[fact(0, 1, 1)], &[]);
1111 assert_eq!(r.admitted.len(), 0);
1112 assert!(
1113 r.declined
1114 .iter()
1115 .any(|d| d.contains("not") && d.contains("erasable")),
1116 "{:?}",
1117 r.declined
1118 );
1119 assert_eq!(r.ops, ops);
1120 }
1121
1122 #[test]
1123 fn untracked_op_stops_tracking_loudly_494() {
1124 let ops = vec![
1125 LocalGet(0), // 0 ← fact
1126 I64ExtendI32S, // 1 untracked ⇒ stop
1127 Drop, // 2
1128 End, // 3
1129 ];
1130 let r = specialize_function("f", &ops, &[], &[fact(0, 1, 2)], &[]);
1131 assert!(!r.changed());
1132 assert!(
1133 r.declined.iter().any(|d| d.contains("outside the tracked")),
1134 "{:?}",
1135 r.declined
1136 );
1137 }
1138
1139 fn nonzero_fact(value_id: u32) -> WscFact {
1140 WscFact {
1141 func_index: 0,
1142 value_id,
1143 kind: FactKind::DivisorNonZero,
1144 }
1145 }
1146
1147 // ================= #494 phase 2b: div/rem trap-guard elision =================
1148
1149 #[test]
1150 fn divisor_range_excluding_zero_elides_zero_guard_all_rem_div_494() {
1151 // div_u, rem_u, rem_s by a param divisor proven ∈ [1, 100]: every
1152 // zero guard falls to UNSAT(P ∧ divisor == 0); the stream itself is
1153 // untouched (marks only).
1154 let ops = vec![
1155 LocalGet(0), // 0 n
1156 LocalGet(1), // 1 d ← fact [1,100]
1157 I32DivU, // 2 → zero mark
1158 Drop, // 3
1159 LocalGet(0), // 4
1160 LocalGet(1), // 5 ← fact [1,100]
1161 I32RemU, // 6 → zero mark
1162 Drop, // 7
1163 LocalGet(0), // 8
1164 LocalGet(1), // 9 ← fact [1,100]
1165 I32RemS, // 10 → zero mark
1166 End, // 11
1167 ];
1168 let facts = [fact(1, 1, 100), fact(5, 1, 100), fact(9, 1, 100)];
1169 let r = specialize_function("f", &ops, &[], &facts, &[]);
1170 assert_eq!(
1171 r.elide_div_zero,
1172 vec![2, 6, 10],
1173 "declines: {:?}",
1174 r.declined
1175 );
1176 assert_eq!(
1177 r.elide_div_ovf,
1178 Vec::<usize>::new(),
1179 "no div_s in the stream"
1180 );
1181 assert!(!r.changed(), "guard marks never rewrite the op stream");
1182 assert_eq!(r.ops, ops);
1183 assert_eq!(r.admitted.len(), 3);
1184 for line in &r.admitted {
1185 assert!(line.contains("divide-by-zero guard elided"), "{line}");
1186 assert!(line.contains("UNSAT(P ∧ divisor == 0)"), "{line}");
1187 assert!(line.contains("certificate-checked"), "{line}");
1188 }
1189 }
1190
1191 #[test]
1192 fn nonzero_fact_elides_zero_guard_but_retains_div_s_overflow_guard_494() {
1193 // THE TWO-GUARD DISTINCTION (#633/#634): a divisor-nonzero fact (kind
1194 // 3) discharges UNSAT(P ∧ divisor == 0) but NOT the overflow
1195 // obligation — divisor ≠ 0 still admits divisor == -1 with dividend
1196 // == INT_MIN, so the overflow guard is RETAINED with a loud decline.
1197 let ops = vec![
1198 LocalGet(0), // 0
1199 LocalGet(1), // 1 ← divisor-nonzero fact
1200 I32DivS, // 2
1201 End, // 3
1202 ];
1203 let r = specialize_function("f", &ops, &[], &[nonzero_fact(1)], &[]);
1204 assert_eq!(r.elide_div_zero, vec![2], "declines: {:?}", r.declined);
1205 assert_eq!(
1206 r.elide_div_ovf,
1207 Vec::<usize>::new(),
1208 "divisor ≠ 0 must NOT elide the INT_MIN/-1 overflow guard"
1209 );
1210 assert!(
1211 r.declined
1212 .iter()
1213 .any(|d| d.contains("overflow-guard obligation Sat") && d.contains("RETAINED")),
1214 "{:?}",
1215 r.declined
1216 );
1217 }
1218
1219 #[test]
1220 fn positive_range_discharges_both_div_s_obligations_494() {
1221 // divisor ∈ [1, 100] excludes BOTH 0 and -1 — the two obligations
1222 // are discharged independently and both guards fall.
1223 let ops = vec![LocalGet(0), LocalGet(1), I32DivS, End];
1224 let r = specialize_function("f", &ops, &[], &[fact(1, 1, 100)], &[]);
1225 assert_eq!(r.elide_div_zero, vec![2], "declines: {:?}", r.declined);
1226 assert_eq!(r.elide_div_ovf, vec![2]);
1227 assert_eq!(r.admitted.len(), 2, "one certificate line per obligation");
1228 assert!(
1229 r.admitted
1230 .iter()
1231 .any(|a| a.contains("overflow guard elided")
1232 && a.contains("dividend == INT32_MIN ∧ divisor == -1")),
1233 "{:?}",
1234 r.admitted
1235 );
1236 }
1237
1238 #[test]
1239 fn range_including_zero_is_sat_and_declines_the_zero_guard_494() {
1240 // divisor ∈ [0, 100]: divisor == 0 is P-admissible — the obligation
1241 // is Sat, the decline is loud and carries a model, no mark is set.
1242 let ops = vec![LocalGet(0), LocalGet(1), I32DivU, End];
1243 let r = specialize_function("f", &ops, &[], &[fact(1, 0, 100)], &[]);
1244 assert_eq!(r.elide_div_zero, Vec::<usize>::new());
1245 assert!(
1246 r.declined
1247 .iter()
1248 .any(|d| d.contains("zero-guard obligation Sat") && d.contains("counterexample")),
1249 "{:?}",
1250 r.declined
1251 );
1252 }
1253
1254 #[test]
1255 fn i64_div_s_nonzero_fact_zero_guard_only_overflow_retained_494() {
1256 // Oracle 5 at the pass level: i64.div_s with an i64 param divisor
1257 // carrying a divisor-nonzero fact — the zero guard is proven dead,
1258 // the INT64_MIN/-1 overflow guard (#633/#634) is RETAINED.
1259 let ops = vec![LocalGet(0), LocalGet(1), I64DivS, End];
1260 let r = specialize_function("f", &ops, &[], &[nonzero_fact(1)], &[true, true]);
1261 assert_eq!(r.elide_div_zero, vec![2], "declines: {:?}", r.declined);
1262 assert_eq!(
1263 r.elide_div_ovf,
1264 Vec::<usize>::new(),
1265 "i64 overflow guard retained"
1266 );
1267 assert!(
1268 r.declined.iter().any(|d| d.contains("RETAINED")),
1269 "{:?}",
1270 r.declined
1271 );
1272 }
1273
1274 #[test]
1275 fn i64_div_s_positive_range_discharges_both_obligations_494() {
1276 let ops = vec![LocalGet(0), LocalGet(1), I64DivS, End];
1277 let r = specialize_function("f", &ops, &[], &[fact(1, 1, 1000)], &[true, true]);
1278 assert_eq!(r.elide_div_zero, vec![2], "declines: {:?}", r.declined);
1279 assert_eq!(r.elide_div_ovf, vec![2]);
1280 }
1281
1282 #[test]
1283 fn i64_div_on_undeclared_width_declines_no_marks_494() {
1284 // Without the params_i64 table the divisor local is symbolically
1285 // 32-bit — the width check declines rather than building a
1286 // wrong-width obligation.
1287 let ops = vec![LocalGet(0), LocalGet(1), I64DivU, End];
1288 let r = specialize_function("f", &ops, &[], &[nonzero_fact(1)], &[]);
1289 assert_eq!(r.elide_div_zero, Vec::<usize>::new());
1290 assert!(
1291 r.declined.iter().any(|d| d.contains("unexpected width")),
1292 "{:?}",
1293 r.declined
1294 );
1295 }
1296
1297 #[test]
1298 fn div_with_no_premise_declines_loudly_494() {
1299 // The function carries a fact, but no premise reaches the divisor —
1300 // the obligation cannot even be posed; both guards stay.
1301 let ops = vec![
1302 LocalGet(0), // 0 ← fact on the DIVIDEND, not the divisor
1303 LocalGet(1), // 1 unconstrained divisor
1304 I32DivU, // 2
1305 End, // 3
1306 ];
1307 // A fact on op 0 (the dividend): premises exist but do not constrain
1308 // the divisor — Sat, decline.
1309 let r = specialize_function("f", &ops, &[], &[fact(0, 1, 5)], &[]);
1310 assert_eq!(r.elide_div_zero, Vec::<usize>::new());
1311 assert!(
1312 r.declined
1313 .iter()
1314 .any(|d| d.contains("zero-guard obligation Sat")),
1315 "{:?}",
1316 r.declined
1317 );
1318 }
1319
1320 #[test]
1321 fn guard_marks_are_remapped_through_a_clamp_elision_494() {
1322 // A clamp elision rewrites the stream; a downstream div's mark must
1323 // land on the REWRITTEN index (the driver feeds the rewritten stream
1324 // to the selector, which keys guards by its own op index).
1325 let ops = vec![
1326 LocalGet(0), // 0 ← fact [524, 1524]
1327 I32Const(476), // 1
1328 I32Add, // 2
1329 LocalSet(1), // 3
1330 LocalGet(1), // 4 -+ low clamp (elided 4..=10)
1331 I32Const(1000), // 5 |
1332 I32LtS, // 6 |
1333 If, // 7 |
1334 I32Const(1000), // 8 |
1335 LocalSet(1), // 9 |
1336 End, // 10 -+
1337 LocalGet(1), // 11
1338 LocalGet(0), // 12 divisor = ch ∈ [524, 1524] ⇒ nonzero
1339 I32DivU, // 13 → zero mark (rewritten index 6)
1340 End, // 14
1341 ];
1342 let r = specialize_function("f", &ops, &[(0, 0)], &[fact(0, 524, 1524)], &[]);
1343 assert!(r.changed(), "declines: {:?}", r.declined);
1344 assert_eq!(r.kept, vec![0, 1, 2, 3, 11, 12, 13, 14]);
1345 assert_eq!(
1346 r.ops,
1347 vec![
1348 LocalGet(0),
1349 I32Const(476),
1350 I32Add,
1351 LocalSet(1),
1352 LocalGet(1),
1353 LocalGet(0),
1354 I32DivU,
1355 End
1356 ]
1357 );
1358 assert_eq!(
1359 r.elide_div_zero,
1360 vec![6],
1361 "mark remapped from original op#13 to rewritten op#6"
1362 );
1363 }
1364
1365 #[test]
1366 fn out_of_range_value_id_is_vacuous_494() {
1367 let ops = clamp_ops();
1368 let r = specialize_function("f", &ops, CLAMP_ARITY, &[fact(999, 524, 1524)], &[]);
1369 assert!(!r.changed());
1370 assert_eq!(r.ops, ops);
1371 }
1372}