Simplification & Formal Proofs (archsem-simplify & formal/)

archsem-simplify provides self-contained, effect-aware integer analysis and rewriting over archsem-ir fragments and functions. Its directed fragment rewrite contract is backed by a machine-checked Lean 4 model in formal/.

Contexts, Budgets & Strictness

All scratch state, known-bits facts, and telemetry live in a caller-owned SimplifyContext—there are no process-global interners, caches, or thread-local state. Every entry point (simplify_fragment, simplify_fragment_with_summary, simplify_function, simplify_function_with_summary, simplify_function_unsummarized) is transactional:

  • Incomplete (Completion::Incomplete) and observation-bound artifacts are rejected on every destructive path—even when max_iterations or max_node_visits is 0.
  • Candidate rewrites are validated against Fragment::validate() / Function invariants and remapped across OriginGraph and EffectSummary before committing. If validation fails, the input IR and provenance remain untouched.
  • A deterministic SSA-user worklist recomputes only definitions affected by a local replacement or alias rather than re-analyzing the whole fragment on every wave.

Known-Bits & Range Analysis (archsem_simplify::analysis)

analyze_known_bits computes forward dataflow facts for 1–512-bit integer values using archsem_core::known_bits:

  • KnownBits: Separate known_zero and known_one bitmasks (1..=512 bits).
  • UnsignedRange & SmallUnsignedRange: Exact modular interval tracking for comparison proving (prove_known_bits_compare, prove_known_bits_signed_greater, prove_unsigned_range_compare).
  • Shared Production Evaluator: Constant folding and known-bit transfer share archsem_core::bitvec with archsem-ir and archsem-symex, guaranteeing identical 1–512-bit modular arithmetic, sign/zero extensions, and explicit invalid partial-operation tracking (division by zero, INT_MIN / -1, shift count >= width, out-of-bounds lanes).

Demanded-Bits & Consumer Flag Demand

Fragment Demanded-Bits (analyze_demanded_bits)

analyze_demanded_bits performs backward bit-liveness over a Fragment, returning a DemandMask per ValueId and per-register read demand (RegisterReadDemand). Callers can supply an OutputDemand specifying which parent-register bit slices are observed at fragment exit; by default every bit is demanded.

[!IMPORTANT] Soundness Contract for Narrowed Demand: Just like archsem_core::FlagDemand, narrowing OutputDemand is a consumer assertion about the surrounding program. A consumer may drop a bit only when that bit is overwritten before any read on every path leaving the instruction—including fault, trap, exception, and unwind edges and any unknown exit. Exceptional checkpoints and side effects inside the fragment always retain full demand on their own operands.

Static Flag-Demand Inference (infer_flag_effects_for_insn)

For consumers lifting one instruction at a time into their own IR, archsem_core::FlagDemand (read via IrEmitter::flag_demand) lets the micro-op VM suppress entire per-flag computations and dead pure intermediates feeding only undemanded flags—while preserving the exact relative op sequence of every demanded flag. archsem_core::infer_flag_effects_for_insn computes a static FlagEffects summary (flags read, written, undefined, defined on all paths, or unbounded) for a decoded instruction form without executing it.

Effect-Aware Rewrite Rules & Telemetry

archsem-simplify only replaces or aliases pure integer definitions. Loads, stores, probes, atomics, fences, traps, faults, opaque intrinsics, and register writes retain their order and stable EventIds.

The 31 RuleId Families

CategoryRuleId Variants
Constants & IdentitiesConstantFold, AddZero, SubZero, MulOne, MulZero, BitwiseIdentity, BitwiseAnnihilator, ShiftZero, DivideOne, RemainderOne, ConvertNoop
Same-Operand & SelectSameOperand, SelectConstant, SelectSameArms, CompareSameOperand
Boolean & ComparisonsBooleanCompare, CompareInversion, CompareCanonicalOrder, SelectToMask, KnownMaskRedundant, KnownConstantResult
Algebraic & BitwiseDoubleUnary, AffineCancellation, NegatedArithmetic, ComplementaryBitwise, ConversionChain, RotateInverse
Packed LanesExtractInsertedLane, ExtractDisjointLane, InsertExtractedLane, OverwriteInsertedLane

Partial-Operation & Choice Guards

A rewrite never erases a partial-operation validity obligation or alters choice correlation:

  • (x + y) - y, (x - y) + y, x & 0, x * 0, inverse rotates, and packed-lane cancellations drop a retired dependency only if that operand is proven defined (cannot divide by zero, overflow signed division, or shift by >= width).
  • Unspecified choices at ProducedValue scope without a correlation key may be eliminated by DCE only if all uses are gone; keyed InstructionExecution, FreshPerObservation, ConstrainedUnpredictable, ImplementationDefined, Environment, Entropy, and Uninitialized choices are preserved.

Per-Rule Decision Telemetry

RuleStats / RuleDecisionStats distinguishes:

  • considered, applied, declined (proof refused), deferred (another rule fired first)
  • choice_sensitive and potentially_invalid orthogonal flags
  • budget_limited when stopped at SimplifyOutcome::IterationLimit or SimplifyOutcome::NodeVisitLimit

Lean 4 Formal Proofs (formal/)

The formal/ Lake project (pinned to Lean 4.32.0, standard-library-only, no sorry, no custom axioms, no unsafe, verified via lake build and AxiomAudit.lean) formalizes the strict, semantics-preserving transformation contract of archsem-simplify and whole-function CFG sealing:

ModuleContents
Archsem/Word.leanConcrete BitVec semantics and explicit invalid-partial-operation reasons
Archsem/Expr.leanTyped pure expressions, lazy select, inputs, and site/correlation-keyed Choices
Archsem/Rewrite.leanAll 31 RuleId names plus proof-carrying local steps, congruence, and guarded cancellation/annihilator rules
Archsem/Behavior.leanObservation profiles, protected event contracts, domain-checked choice plans, behavior sets, and certified deletion-ledger cleanup
Archsem/CFG.leanScope/epoch/generation-indexed CFG completion, unique block/entry obligations, closed targets, total outer-value remapping, and sealing certificates
Archsem/Soundness.leanMain theorem simplifyFragment_behavior_equiv, complete mapping records, and transactional rollback
Archsem/Examples.leanRegression witnesses (e.g., correlated-choice cancellation and refusal to totalize unconstrained division)

[!NOTE] Proof Boundary: The Lean development is a denotational unfolding of validated acyclic SSA rather than extracted Rust. It verifies the proof-carrying transformation contract (AnalysisCertificate) and modeled architectural projection—not the compiled Rust choose_rewrite implementation itself, which is cross-checked by archsem-simplify property suites and archsem-symex's transform-check feature.