Skip to content

[AUTOMATED] s8: iteboolean - re-roll short-circuit 0/1 select diamonds into a boolean assignment (DIV-51) - #241

Merged
mahaloz merged 1 commit into
mainfrom
feat/decbench-iteboolean
Aug 1, 2026
Merged

mahaloz merged 1 commit into
mainfrom
feat/decbench-iteboolean

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Closes the whole residual structural gap vs Hex-Rays on the mined decbench case
O0-bash-bash-time_command: a short-circuit boolean assignment (x = a && b;)
staying an explicit 0/1 diamond.

The gap

Source (execute_cmd.i, time_command):

posix_time = command && (command->flags & 0x100);
nullcmd = (command == 0) || (command->type == cm_simple && ... && ...);

kuna before (--mode reliable, what auto picks for this 1.5 MB binary):

  v26 = subshell_environment;
  if ((a0) && (v2 = a0[1] & 0x100, v2))
    v2 = 1;
  else {
    v2 = 0;
  }
  v28 = v2;
  if ((a0) && (((*a0 != 4 || (*(int8 *)(*(int8 *)&a0[6] + 8))) || (*(int8 *)(*(int8 *)&a0[6] + 0x10)))))
    v2 = 0;
  else {
    v2 = 1;
  }

kuna after (this PR, default):

  v26 = subshell_environment;
  v2 = ((a0) && (v2 = a0[1] & 0x100, v2));
  v28 = v2;
  v2 = !((a0) && (((*a0 != 4 || (*(int8 *)(*(int8 *)&a0[6] + 8))) || (*(int8 *)(*(int8 *)&a0[6] + 0x10)))));

Two diamonds = 6 CFG blocks / 8 edges of a 28-node function. Full panes:
docs/features/iteboolean/kuna-time_command-{off,on}.c.

Upstream-fidelity verdict: faithful port ⇒ this is a feature, behind an option

P3 RuleConditionalMove is the rule that folds MULTIEQUAL(0,1) into
zext(cond)/BOOL_AND/BOOL_OR. It fires on the simple one-test shape and
bails when a MULTIEQUAL input block has more than one predecessor. That bail is
verbatim upstream, Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.cc
RuleConditionalMove::applyOp (lines 9424-9439, upstream
f9e13846b20c223334d37cfe75bf36fbe9e4dce7):

  bb = op->getParent();
  inblock0 = bb->getIn(0);
  if (inblock0->sizeOut() == 1) {
    if (inblock0->sizeIn() != 1) return 0;
    rootblock0 = inblock0->getIn(0);
  }
  else
    rootblock0 = inblock0;
  inblock1 = bb->getIn(1);
  if (inblock1->sizeOut() == 1) {
    if (inblock1->sizeIn() != 1) return 0;
    rootblock1 = inblock1->getIn(0);
  }
  else
    rootblock1 = inblock1;
  if (rootblock0 != rootblock1) return 0;

kuna's p3_dataflow/ruleaction_7.rs:1894-1914 reproduces this character for
character. So it is a judgment call beyond upstream, not a mis-port: option,
not silent bug fix.

And the literal P3 relaxation is not implementable. gcc compiles the idiom to

 4ea9c: cmpq $0x0,-0x3c8(%rbp) ; je 4eac0     <- B0, false edge
 4eaa6: mov 0x4(%rax),%eax ; and $0x100,%eax
 4eab5: test %eax,%eax ; je 4eac0             <- B1, false edge
 4eab9: mov $0x1,%eax ; jmp 4eac5             <- B1b
 4eac0: mov $0x0,%eax                         <- B2, TWO in-edges (B0 and B1)
 4eac5: mov %eax,-0x3ac(%rbp)                 <- B3, the MULTIEQUAL

The constant arm B2's extra predecessor is a different CBRANCH. B1's boolean is
not even defined on the B0 path, so folding the select to zext(B1.cond) would be
an SSA violation as well as wrong; and reconstructing the whole chain condition at
P3 would have to hoist p[1] above its p != 0 guard. Upstream's bail is right at
the IR level — the short-circuit must stay in the CFG, and only C's own &&/||
can express it.

Where the decision belongs (P8, print-only)

By the end of structuring the chain P3 could not see is already one
BlockCondition
— kuna prints it today as the if's condition, complete with
C's short-circuit semantics and any comma-expression side effects. That is where
the re-roll is expressible and safe.

ActionIteBoolean (p8_structure/kuna_iteboolean.rs, ELEM 4119) marks a
3-component gotoless BlockIf whose

  • condition component is that BlockCondition (a tree of clean, unlabelled
    CBRANCH-terminated leaves, depth ≤ 16), and whose
  • true/else clauses are each a single leaf whose only printed op is a COPY of
    the constants 1 and 0 (either order) to the same integral storage,

and PrintC::emit_block_if_bool emits dest = ( cond ); (arms 0/1 ->
dest = !( cond );). The condition goes through the same ONLY_BRANCH renderer
that produced the if (...) header, so parenthesization, evaluation order,
short-circuiting and comma side effects are preserved verbatim. Print-only: an
addl-flag (kuna_iteboolean, 0x4000) on the condition's terminal CBRANCH; no
p-code is cloned or mutated, so option iteboolean off is byte-identical.

The safety argument (this is the part that could have produced wrong code)

Requiring the BlockCondition is what makes the rewrite value-safe, not just
shape-safe. &&/|| and the negating ! always yield exactly 0/1 in C — the
two constants the arms wrote. A bare leaf condition gives no such guarantee:
under truthycond (DIV-37) an if (x & 0x100) renders as (x & 0x100), so
v = (x & 0x100) would store 0x100 instead of 1. That bare-leaf shape is also
exactly the one P3 already folds, so excluding it costs essentially nothing
(1 function / 1 diamond across the 14-binary corpus below). The matcher also
declines pointer/float/aggregate destinations (they would lose the constant's own
rendering/cast), labelled arms, computed arms, and any second statement in an arm.

Mechanical audit of every rewrite across the corpus: 160/160 emitted
expressions are boolean-valued at their top level (81 positive v = ( a && b );,
79 negated v = !( ... );), 0 exceptions.

Source-level spot checks (kuna output vs the project's own .i):

function source kuna after
grep print_line_tail eol_size = (lim > beg && lim[-1] == eolbyte); v1 = !((a1 <= a0) || (*(char *)(a1 - 1) != dat_33183));
grep grep skip_nuls = skip_empty_lines && !eol; dat_33830 = ((dat_33831) && (!v2));
gzip yesno yes = (c == 'y' || c == 'Y'); v1 = !((v2 != 0x79) && (v2 != 0x59));

Each is the exact De Morgan dual of the source. num += out_line && num < INTMAX_MAX;
likewise becomes v6 = ((dat_33852) && (v19 != 0x7fffffffffffffff)); v19 += v6; —
the && value is 0/1, so the += is right.

Ablation

Ablation (option ON) Speed Ship as
0/675 datatest assertions change (PARITY OK, no re-pin) within budget (best measurement: -3.0% / -0.9% / -3.0%, i.e. no cost) default-ON, DIV-51

One stage test needed a per-test option iteboolean off: ghangr-earlyreturn,
whose witness is a 0/1 diamond, so the re-roll would collapse it before the
return phi earlyreturn is about ever forms. No baseline was re-pinned.

Measurements

GED, the mined case (scripts.decbench.rescore --case O0-bash-bash-time_command):

pane GED
kuna, recorded run (stored artifact) 55
kuna, today's build before this PR 26
kuna, this PR 6

28 nodes / 43 edges vs the source's 28/44 — exactly the hand-rerolled pane the
triage note predicted.

Corpus breadth — kuna decompile-all, option off vs on, 14 -O0 decbench
binaries:

binary functions changed diamonds
tar 1664 48 57
findutils find 917 22 31
diffutils diff 532 17 24
grep 674 12 17
iproute2 ip 1962 10 10
e2fsprogs e2fsck 1991 8 10
zlib minigzip 197 2 4
dpkg 1033 3 3
gzip 263 2 2
kmod 576 2 2
bzip2 / sysvinit init / shadow su / cronie crond 685 0 0
total 10,494 126 (1.2%) 160

Speed — decompile-all --mode reliable, interleaved median of 5 (off/on
alternating; the machine was shared, so both arms absorb the same contention):

binary off on delta
grep 7,308 ms 7,092 ms -2.96%
gzip 2,563 ms 2,540 ms -0.90%
diffutils diff 7,659 ms 7,431 ms -2.98%

No measurable cost — the pass is one linear walk of the structured tree with a
cheap match and no p-code mutation. Budget is +5%.

Gates

gate result
make test PARITY OK (675/675)
make test-stages PARITY OK (350/350)
make rust-test green
make check-spec OK (lenient and --strict)
kuna catalog --check catalog OK

What's in the PR

  • p8_structure/kuna_iteboolean.rs (new), p9_emit/printc.rs
    (ite_boolean_match + emit_block_if_bool, checked before the iteregion
    ternary so the more specific form wins), substrate/op.rs (addl-flag 0x4000),
    schedule entry after iteregion.
  • Option iteboolean (phases.toml settable + p0_knowledge/options.rs +
    Architecture/ArchSeam wiring) and the hard-coded catalog counts
    (82 -> 83 settables, transform tier 37 -> 38, catalog_bytecompat + its
    phase_catalog.json fixture, kuna-catalog.xml structure-recovery 20 -> 21,
    the list_action schedule oracle + leaf count 269 -> 270).
  • tests/stages/ghdec-iteboolean.xml (two-pass over a real gcc -O0
    binary -> decompile(f) path: 2 of 4 assertions fail with the option off, 4/4
    with it on), corpus file count 182 -> 183, docs/baseline-stages.json
    re-recorded.
  • Spec prose in docs/spec/08-structuring.md (new iteboolean section, incl. the
    upstream-fidelity argument) and docs/spec/09-emission.md; DIV-51 in
    docs/history.md; regenerated docs/options.md; feature bundle
    docs/features/iteboolean/.

Provenance: inspiration = "decbench:O0-bash-bash-time_command",
source_decompiler = "ida", change_kind = "structure-recovery",
tier = "transform".

🤖 Generated with Claude Code

https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

…s into a boolean assignment (DIV-51)

gcc at -O0 materializes a source `x = a && b;` as a jump-based select whose
constant-0 arm is the shared target of every short-circuit exit. kuna printed
that as an explicit two-arm constant diamond where the source and Hex-Rays have
one statement; on bash time_command two of them are the entire residual
structural gap vs IDA (GED 26 -> 6 with them re-rolled).

Upstream fidelity: the P3 RuleConditionalMove bail that leaves this alone is a
FAITHFUL port of upstream Ghidra (ruleaction.cc:9424-9439,
`if (inblock->sizeIn() != 1) return 0;` on each MULTIEQUAL input block), so this
ships as an option, not as a bug fix. The bail is also right at the IR level --
the constant arm's extra predecessor is a different CBRANCH whose boolean does
not dominate the join, and reconstructing the whole chain would hoist a guarded
load above its guard -- so the re-roll is done at P8, after structuring, where
the chain is already one BlockCondition that C's own &&/|| renders with
short-circuit semantics.

ActionIteBoolean (p8_structure/kuna_iteboolean.rs, ELEM 4119) marks a
3-component gotoless BlockIf whose condition is that BlockCondition and whose
two arms are each a single COPY of the constants 1/0 to the same integral
storage; PrintC::emit_block_if_bool emits `v = ( cond );` (arms 0/1 ->
`v = !( cond );`). Print-only: an addl-flag on the condition's terminal CBRANCH,
no p-code cloned or mutated, so `option iteboolean off` is byte-identical.

Requiring the BlockCondition is what makes the rewrite value-safe and not just
shape-safe: &&/|| and the negating ! always yield exactly 0/1 in C, while a bare
leaf condition renders truthy under DIV-37 (`if (x & 0x100)` prints
`(x & 0x100)`, worth 0x100) and would store the wrong number. That bare-leaf
shape is also the one P3 already folds.

Measured: GED on O0-bash-bash-time_command 55 (recorded) / 26 (today's build)
-> 6; 675/675 PARITY OK with the flip and no re-pin; 14 -O0 decbench binaries /
10,494 functions -> 126 functions change (1.2%), 160 diamonds collapse (81
positive, 79 negated), and a mechanical audit of all 160 confirms every emitted
expression is boolean-valued at its top level; interleaved medians of 5 show no
speed cost.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo
@mahaloz
mahaloz merged commit b57aa9e into main Aug 1, 2026
9 checks passed
@mahaloz
mahaloz deleted the feat/decbench-iteboolean branch August 1, 2026 23:42
mahaloz added a commit that referenced this pull request Aug 2, 2026
…IV-52) (#242)

* [AUTOMATED] fix(p9): (NOVEL) one local declaration per ScopeLocal Symbol (DIV-51)

`PrintC::emitLocalVarDecls` walks HighVariables; upstream `emitScopeVarDecls`
walks the ScopeLocal *Symbol* table (printc.cc:2667/2696), which is what makes
one symbol one declaration.  When two live ranges of one mapped stack slot did
not merge, the shared-storage naming gave both the same name and P5 recovered
different types for them, so the function opened with the same identifier
declared twice at two widths:

    void applyLedFixedLayers(void)   // betaflight_STM32F405, O2-noinline
    {
      ...
      unsigned int v12; // stack - 0x24
      uint4 v12;        // stack - 0x24

That is not compilable C, and a reader cannot tell which `v12` any body
occurrence means.  Ghidra emits one `undefined4 local_24;`, IDA one `int v23;`.

The only collapse that existed, `option dedupvardecls` (DIV-7, default on),
keys on the fully rendered LINE, so two spellings of one slot both survive by
construction -- its own module doc recorded that residual as intentional.  The
composite (array/struct/union) collapse sitting beside it was already
Symbol-keyed; the scalar case was the documented gap ("primitive types are
shared by every scalar local of that type", so the type-Rc key does not
identify a symbol).

Upstream-fidelity verdict: an UNPORTED rule, not a mis-ported or deliberately
simplified one.  The scalar collapse is now Symbol-keyed too, inside that same
option: highs whose declaration representative resolves to the same containing
ScopeLocal Symbol -- base-byte containment, the query C++ `Funcdata::linkSymbol`
itself uses (funcdata_varnode.cc:1190) -- AND that render the same identifier
emit one declaration.

Requiring the identifier to match is what makes the collapse incapable of
removing the last declaration of a referenced name, i.e. the mirror-image
failure #131 fixed.  It is load-bearing: on the campaign function nine highs of
symbol 5v13 are named `v12` (all whole 4-byte covers, so naming them alike is
correct) while its partial covers carry their own names `v14`/`v15`/`v16`, and
those must all keep their declarations.  The duplicate NAME is therefore not a
naming defect -- naming per symbol is right, and the declaration layer is where
the rule was missing.

Type arbitration when the collapsing highs disagree: the Symbol's own type,
which is what C++ `emitVarDecl` declares (`sym->getType()`, printc.cc:1719) --
unless it is narrower than the widest storage the group covers, in which case
the widest member wins.  kuna's ScopeLocal ranges are sometimes narrower than
the accesses that reach them (upstream `restructure` would have grown the
symbol), and declaring a 2-byte object for a slot the body writes 4 bytes into
and passes by address would be a new defect rather than a faithful one.  A
group that already agrees keeps its recovered type, which is sharper than the
usually-`undefined<N>` symbol type.

Strict bug fix inside an existing default-on option, so no new flag; recorded
as DIV-51.  `option dedupvardecls off` still restores the per-high rendering.

Measured before/after on 14 decbench binaries / 11,874 functions (x86-64 and
ARM Cortex-M, -O0 and -O2), the first measurement of this bug's real scope:
functions emitting a duplicate local declaration 18 -> 0.  The blast radius is
exactly those 18 -- no other function changes a byte, 21 declaration lines
disappear (35,412 -> 35,391), no function loses a declared name and none gains
one.  Every survivor is at least as wide as every access it absorbed
(`undefined3`/`unsigned short`/`char` shadows of a 4-byte slot become one
`unsigned int`).  The collapse only runs where two declarations already share an
identifier, so the symbol lookups are skipped on nearly every function;
interleaved medians of `decompile-all --mode reliable`: betaflight STM32F405
(6,387 functions) 69,782 -> 69,754 ms (-0.04%), bzip2 9,926 -> 9,863 ms
(-0.63%), gzip 3,162 -> 3,211 ms (+1.55%, 9 pairs).

`verify_declared_vars` now asserts both failure modes on the `declmerge`
fixture: no name undeclared (#131) and no name declared twice.
`tests/stages/ghdec-symbol-keyed-local-decls.xml` is the end-to-end witness over
a real binary -> decompile(addr) path (4 of 6 assertions pass pre-fix, 6/6
post-fix); it uses the smallest function in the same firmware showing the same
defect, with `option dedupvardecls off` as pass 2 pinning the bug form.

This function was already tied-best on the benchmark (kuna GED 25 == ghidra 25),
so the fix moves zero benchmark points; its value is that the output stops
being invalid C.

Gates: make test PARITY OK (675/675, baseline untouched), make test-stages
PARITY OK (352/352, re-recorded -- delta is purely the 6 new keys), make
rust-test green, make check-spec OK, kuna catalog --check OK.

inspiration = "decbench:O2-noinline-betaflight-betaflight_STM32F405-applyLedFixedLayers; NOVEL pool"

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

* [AUTOMATED] renumber DIV-51 -> DIV-52 (DIV-51 taken by #241 iteboolean)

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant