Skip to main content

ddc_dec/
method.rs

1//! Per-method decompilation pipeline:
2//! DEX code units → CFG → register→IR lifting (fixpoint with merge phis) →
3//! `jdc-core` structuring → statement conversion → refinement passes.
4
5use jdc_core::FxHashMap as HashMap;
6
7use ddc_dex::insn::InsnKind;
8use jdc_core::convert::Converter;
9use jdc_core::ir::build::BlockResult;
10use jdc_core::ir::expr::{Expr, TypeRef};
11use jdc_core::ir::stmt::Stmt;
12use jdc_core::structure::{reverse_postorder, Structurer};
13use jdc_core::types::{JavaType, MethodDescriptor};
14use jdc_core::var::VarTable;
15
16use crate::cfg::DexCfg;
17use crate::lift::{entry_regs, Lifter, MethodEnv, OutState, Reg};
18use crate::passes;
19use crate::{DexPool, PoolClass, PoolMethod};
20
21pub struct MethodBody {
22    pub body: Stmt,
23    pub vt: VarTable,
24    pub desc: MethodDescriptor,
25}
26
27/// Catch types for the ranges a block handles (drives move-exception typing).
28/// Debug-env reads, cached: `env::var` is an environ lock+scan — a
29/// per-METHOD cost across 716k methods shows up as __NSGetEnviron in
30/// profiles. Once per process is the right granularity.
31fn trace_on() -> bool {
32    static T: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
33    *T.get_or_init(|| std::env::var("DDC_TRACE").is_ok())
34}
35
36fn walk_budget_override() -> Option<u64> {
37    static T: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
38    *T.get_or_init(|| {
39        std::env::var("DDC_WALKBUDGET")
40            .ok()
41            .and_then(|v| v.parse().ok())
42    })
43}
44
45fn walk_work_override() -> Option<u64> {
46    static T: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
47    *T.get_or_init(|| {
48        std::env::var("DDC_WALKWORK")
49            .ok()
50            .and_then(|v| v.parse().ok())
51    })
52}
53
54fn walk_ms_override() -> Option<u64> {
55    static T: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
56    *T.get_or_init(|| std::env::var("DDC_WALKMS").ok().and_then(|v| v.parse().ok()))
57}
58
59fn handler_types_for(cfg: &DexCfg, bid: usize) -> Vec<Option<std::sync::Arc<str>>> {
60    cfg.blocks[bid]
61        .handlers
62        .iter()
63        .filter_map(|&ri| cfg.exc_ranges.get(ri).map(|r| r.catch_type.clone()))
64        .collect()
65}
66
67/// Decompile one method. `Err` only for malformed input; unsupported
68/// constructs degrade to comments inside the statement tree.
69pub fn decompile_method(
70    pool: &DexPool,
71    class: &PoolClass,
72    m: &PoolMethod,
73) -> Result<Option<MethodBody>, String> {
74    let t0 = std::time::Instant::now();
75    if m.is_abstract_or_native() {
76        return Ok(None);
77    }
78    let desc = m
79        .parsed_desc()
80        .ok_or_else(|| format!("bad descriptor {}", m.desc))?;
81    let dex = pool.dex(m.dex_idx).ok_or("missing dex image")?;
82    let dex = &*dex;
83    let Some(mut code) = dex.code_at(m.code_off) else {
84        return Ok(None);
85    };
86    let insn_count = code.insns.len();
87    let param_names = dex.parameter_names(m.debug_info_off);
88    // Pool-cached Arc class names: the closure ran dex.class_name
89    // (fresh String) per exception range of every method.
90    let cfg = DexCfg::build(&mut code, &|ty| pool.type_name_arc(m.dex_idx, ty));
91    // Method-wide final-read set for the alloc-inline decisions (the
92    // per-block computation mistook a block-tail read for the
93    // generation's last read — cross-block alloc consumers minted
94    // never-assigned int locals).
95    let method_final_reads = crate::lift::compute_final_reads(&cfg.insns);
96    let n = cfg.blocks.len();
97    let env = MethodEnv {
98        pool,
99        di: m.dex_idx,
100        dex,
101        code: &code,
102        class_name: class.name.clone(),
103        method_name: m.name.clone(),
104        desc: desc.clone(),
105        debug_locals: dex.debug_locals(m.debug_info_off),
106        is_static: m.is_static(),
107        code_units: cfg.code_units,
108    };
109    let mut vt = VarTable::default();
110    let entry = entry_regs(&mut vt, &env, &param_names);
111    if n == 0 {
112        return Ok(None);
113    }
114    // Pathological inputs (R8-merged model classes, obfuscated switch
115    // cascades) can explode the copied-tail rendering; guard up front.
116    if insn_count > 30_000 || n > 8_000 {
117        return Ok(Some(stub_body(
118            format!(
119                "$DDC: method too large to decompile ({} insns, {} blocks)",
120                insn_count, n
121            ),
122            desc,
123        )));
124    }
125
126    // Visiting order: reverse postorder, then any stragglers (so every block
127    // is built at least once even when unreachable).
128    let core_for_order = cfg.to_core();
129    let universe: jdc_core::FxHashSet<usize> = (0..n).collect();
130    let mut order = reverse_postorder(&core_for_order, core_for_order.entry, &universe);
131    {
132        let mut seen: jdc_core::FxHashSet<usize> = order.iter().copied().collect();
133        for b in &cfg.blocks {
134            if seen.insert(b.id) {
135                order.push(b.id);
136            }
137        }
138    }
139
140    // Handler blocks: entry state approximated by the try-entry state (the
141    // dominant pattern: catch reads values established before the try).
142    let mut handler_entry_block: HashMap<usize, usize> = HashMap::default();
143    for b in &cfg.blocks {
144        if b.handlers.is_empty() {
145            continue;
146        }
147        let mut best: Option<(u32, usize)> = None;
148        for &ri in &b.handlers {
149            if let Some(r) = cfg.exc_ranges.get(ri) {
150                if best.map(|(s, _)| r.start < s).unwrap_or(true) {
151                    if let Some(eb) = cfg.block_at(r.start) {
152                        best = Some((r.start, eb));
153                    }
154                }
155            }
156        }
157        if let Some((_, eb)) = best {
158            handler_entry_block.insert(b.id, eb);
159        }
160    }
161
162    // ---- fixpoint: register states across blocks ----
163    let mut results: Vec<BlockResult> = Vec::with_capacity(n);
164    results.resize_with(n, || BlockResult {
165        stmts: vec![],
166        out_stack: vec![],
167        term: jdc_core::ir::build::Term::Return(None),
168    });
169    let mut out_states: Vec<Option<OutState>> = vec![None; n];
170    // Stable (block, register) → var ids across worklist rebuilds: keeps
171    // re-lifts id-deterministic so the fixpoint CONVERGES instead of
172    // cascading (was: 30M block-lifts on weibo, ~60 per block).
173    let mut stable_vars: HashMap<(usize, u16, u64), u32> = HashMap::default();
174    // Method feature flags OR-merged from every block lift: gates
175    // post-lift passes that can only match if the bytecode contained the
176    // feature (most methods contain none).
177    let mut mflags = crate::lift::MethodFlags::none();
178    // Try-entry INPUT snapshots (for handler-block approximation) — only
179    // try-entry starts (rare) keep their input state; no persistent
180    // per-block copies.
181    let mut try_entry_snapshots: HashMap<usize, Vec<Reg>> = HashMap::default();
182    let mut built_once = vec![false; n];
183    let mut errors: HashMap<usize, String> = HashMap::default();
184    // (merge block, register) → phi var id.
185    let mut phis: HashMap<(usize, u16), u32> = HashMap::default();
186    // pred → (write_pc, phi var, value) materializations.
187
188    let entry_is_handler = handler_entry_block.contains_key(&0);
189
190    // Per-visit costs hoisted out of the worklist loop: the try-entry scan
191    // (all exc ranges × a binary search per range) and the handler catch
192    // types (String clones) re-ran on EVERY visit — visits average 2.5×
193    // blocks on real code, far more on monsters.
194    let try_entry_flags: Vec<bool> = (0..n)
195        .map(|b| {
196            !cfg.blocks[b].handlers.is_empty()
197                || cfg
198                    .exc_ranges
199                    .iter()
200                    .any(|r| cfg.block_at(r.start) == Some(b))
201        })
202        .collect();
203    let handler_types: Vec<Vec<Option<std::sync::Arc<str>>>> =
204        (0..n).map(|b| handler_types_for(&cfg, b)).collect();
205
206    // Worklist fixpoint with version stamps: a block rebuilds only when the
207    // OUT-state versions of its inputs changed. This avoids the previous
208    // every-round full pass, which deep-cloned and deep-compared the whole
209    // register state (Expr trees) of every block — the dominant cost of
210    // large methods.
211    let mut ver: Vec<u64> = vec![0; n]; // out-state version per block
212    let mut built_ver: Vec<u64> = vec![u64::MAX; n]; // input signature when built
213                                                     // input signature: entry=0; otherwise XOR/sum of (pred, ver[pred]) pairs.
214    fn input_sig(cfg: &DexCfg, bid: usize, ver: &[u64]) -> u64 {
215        let mut h: u64 = 1;
216        for &p in &cfg.blocks[bid].pred {
217            h = h
218                .wrapping_mul(31)
219                .wrapping_add(p as u64)
220                .wrapping_mul(31)
221                .wrapping_add(ver[p]);
222        }
223        // Handler blocks also depend on their try-entry block's input.
224        h
225    }
226    let mut queue: std::collections::VecDeque<usize> = std::collections::VecDeque::new();
227    let mut queued: Vec<bool> = vec![false; n];
228    for &bid in &order {
229        queue.push_back(bid);
230        queued[bid] = true;
231    }
232    // merge bid → [(pred, write_pc, phi var, value)] — re-recorded whole on
233    // each visit of the merge block (stale rounds must not accumulate).
234    let mut appends: HashMap<usize, Vec<(usize, u32, u32, Expr)>> = HashMap::default();
235    let mut total_visits: usize = 0;
236    let visit_cap: usize = 64 * n + 256;
237
238    while let Some(bid) = queue.pop_front() {
239        queued[bid] = false;
240        total_visits += 1;
241        if total_visits > visit_cap {
242            CAP_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
243            CAP_INSNS.fetch_add(
244                insn_count as u64 * 1000 + n as u64,
245                std::sync::atomic::Ordering::Relaxed,
246            );
247            break; // degenerate oscillation guard
248        }
249        let is_handler = handler_entry_block.contains_key(&bid);
250        // 1. Signature gate FIRST: a visit whose input versions are
251        //    unchanged skips the (clone-heavy) input-state computation
252        //    entirely — that clone was the fixpoint's dominant cost.
253        let sig = input_sig(&cfg, bid, &ver)
254            ^ (if is_handler {
255                let eb = handler_entry_block[&bid];
256                (eb as u64) << 32
257            } else {
258                0
259            });
260        let need_build = !built_once[bid] || built_ver[bid] != sig;
261        if !need_build {
262            // Handler blocks depend on their try-entry block's INPUT —
263            // when that entry is re-visited, the handler is re-queued; a
264            // skipped visit here means the recorded state is current.
265            continue;
266        }
267        // 2. Input register state (only on rebuild).
268        let ins: Vec<Reg> = if bid == cfg.entry {
269            if cfg.blocks[0].pred.is_empty() || entry_is_handler {
270                entry.clone()
271            } else {
272                // A loop back into pc 0: params are one side of the merge.
273                // Sides are BORROWED (cloning each pred's state here was a
274                // top fixpoint cost).
275                let mut sides: Vec<&[Reg]> = vec![entry.as_slice()];
276                for p in cfg.blocks[bid].pred.clone() {
277                    if let Some(o) = &out_states[p] {
278                        sides.push(o.regs.as_slice());
279                    }
280                }
281                let merged =
282                    merge_states(&mut vt, &mut phis, bid, &sides, &env.debug_locals, cfg.blocks[bid].start);
283                // The entry side's phi contributions become leading
284                // assignments in the entry block (virtual pred). The entry
285                // block may be re-visited by the worklist — each visit
286                // replaces (not appends) its records.
287                let mut recs: Vec<(usize, u32, u32, Expr)> = Vec::new();
288                for (r, st) in entry.iter().enumerate() {
289                    if let Some(&phi) = phis.get(&(bid, r as u16)) {
290                        let value = match st {
291                            Reg::Live(v) if *v == phi => continue,
292                            Reg::Live(v) => Expr::Local {
293                                var: *v,
294                                ty: vt.var(*v).ty.clone(),
295                            },
296                            Reg::Pending(e) | Reg::PendingCall(e) => e.clone(),
297                            Reg::Undef | Reg::WideHi => continue,
298                        };
299                        recs.push((usize::MAX, 0, phi, value));
300                    }
301                }
302                appends.insert(bid, recs);
303                merged
304            }
305        } else if is_handler {
306            let eb = handler_entry_block[&bid];
307            try_entry_snapshots
308                .get(&eb)
309                .cloned()
310                .unwrap_or_else(|| vec![Reg::Undef; env.code.registers_size as usize])
311        } else {
312            // Borrowed sides; the single-pred fast path clones once (the
313            // lifter needs an owned copy anyway).
314            let mut sides: Vec<&[Reg]> = Vec::new();
315            for p in cfg.blocks[bid].pred.clone() {
316                if let Some(o) = &out_states[p] {
317                    sides.push(o.regs.as_slice());
318                }
319            }
320            if sides.is_empty() {
321                vec![Reg::Undef; env.code.registers_size as usize]
322            } else if sides.len() == 1 {
323                sides[0].to_vec()
324            } else {
325                merge_states(
326                    &mut vt,
327                    &mut phis,
328                    bid,
329                    &sides,
330                    &env.debug_locals,
331                    cfg.blocks[bid].start,
332                )
333            }
334        };
335
336        // 3. Phi materialization records for predecessors — recomputed for
337        //    this block only; later pred rebuilds re-visit the merge and
338        //    refresh them (the last visit wins).
339        if phis_for_merge(bid, &phis) {
340            let mut recs: Vec<(usize, u32, u32, Expr)> = Vec::new();
341            record_appends(&cfg, bid, &out_states, &phis, &vt, &mut recs);
342            // Entry-merge visits also carry the entry-side contributions —
343            // preserve those (recorded above when bid == entry).
344            if bid == cfg.entry {
345                if let Some(prev) = appends.get(&bid) {
346                    for (p, pc, v, e) in prev.iter() {
347                        if *p == usize::MAX {
348                            recs.push((*p, *pc, *v, e.clone()));
349                        }
350                    }
351                }
352            }
353            appends.insert(bid, recs);
354        }
355
356        // 4. Build (signature known changed). The lifter CONSUMES `ins`
357        //    (moved, not cloned); try-entry snapshots preserve the input
358        //    state for the handler blocks approximating from it.
359        built_once[bid] = true;
360        built_ver[bid] = sig;
361        if try_entry_flags[bid] {
362            try_entry_snapshots.insert(bid, ins.clone());
363        }
364        BUILD_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
365        INSN_LIFTED.fetch_add(
366            cfg.block_ins(&cfg.blocks[bid]).len() as u64,
367            std::sync::atomic::Ordering::Relaxed,
368        );
369        let htypes = &handler_types[bid];
370        let block_ins = cfg.block_ins(&cfg.blocks[bid]);
371        let lifter = Lifter::new(&env, &mut vt, ins, bid, &mut stable_vars, &mut mflags);
372        let rebuilt = match lifter.build_block(block_ins, htypes, method_final_reads.clone()) {
373            Ok((r, out)) => {
374                results[bid] = r;
375                let changed = match &out_states[bid] {
376                    Some(prev) => prev.regs != out.regs,
377                    None => true,
378                };
379                out_states[bid] = Some(out);
380                changed
381            }
382            Err(msg) => {
383                results[bid] = BlockResult {
384                    stmts: vec![Stmt::Comment(format!("$DDC-BLOCK-ERROR: {msg}"))],
385                    out_stack: vec![],
386                    term: jdc_core::ir::build::Term::Return(None),
387                };
388                out_states[bid] = Some(OutState {
389                    regs: vec![Reg::Undef; env.code.registers_size as usize],
390                    write_pc: vec![0; env.code.registers_size as usize],
391                });
392                errors.insert(bid, msg);
393                false
394            }
395        };
396        if rebuilt {
397            ver[bid] += 1;
398            // Successors re-check their input signature.
399            for &succ in &cfg.blocks[bid].succ {
400                if !queued[succ] && succ < n {
401                    queue.push_back(succ);
402                    queued[succ] = true;
403                }
404            }
405            // Handler blocks watch their try-entry block's INPUT — cheap
406            // approximation: also queue the handler of every range this
407            // block belongs to.
408            if is_handler {
409                let eb = handler_entry_block[&bid];
410                if !queued[eb] && eb < n {
411                    queue.push_back(eb);
412                    queued[eb] = true;
413                }
414            }
415            // Try-entry inputs: when this block feeds a handler entry via a
416            // try range, queue that handler.
417            for &ri in &cfg.blocks[bid].handlers {
418                if let Some(r) = cfg.exc_ranges.get(ri) {
419                    if let Some(hb) = cfg.block_at(r.handler) {
420                        if !queued[hb] && hb < n {
421                            queue.push_back(hb);
422                            queued[hb] = true;
423                        }
424                    }
425                }
426            }
427        }
428    }
429
430    // Entry-side phi contributions: carried as declaration-with-init and
431    // prepended to the method body AFTER conversion (the entry block may be
432    // a loop header — its statements re-execute per iteration).
433    // Entry-side phi contributions (the virtual pred): captured for the
434    // method-top declarations; the REAL preds' records stay in `appends`
435    // for the commit loop (removing the whole entry key would lose the
436    // loop-body assignments — the phis would collapse to their entry
437    // values).
438    let mut entry_phi_inits: Vec<(u32, Expr)> = Vec::new();
439    if let Some(recs) = appends.get_mut(&cfg.entry) {
440        let mut entry_side: Vec<(u32, Expr)> = Vec::new();
441        recs.retain(|(p, _, v, e)| {
442            if *p == usize::MAX {
443                entry_side.push((*v, e.clone()));
444                false
445            } else {
446                true
447            }
448        });
449        entry_side.sort_by_key(|(v, _)| *v);
450        entry_phi_inits = entry_side;
451    }
452
453    // Commit phi materializations: each pred assigns its outgoing value to
454    // the merge var, ordered by the pc of the instruction that produced it.
455    // Values that REFERENCE a sibling phi are snapshotted into a fresh temp
456    // first: register rotations (`a = b; b = a % b`) would otherwise read
457    // the already-reassigned phi (stale capture).
458    // Regroup: merge-keyed records → per-pred statement lists.
459    //
460    // Deterministic order: `adds.sort_by_key(pc)` below is a STABLE sort,
461    // so same-pc records (one jump feeding several merge vars) keep
462    // their push order — iterating `appends` in map order made that
463    // order hasher-dependent (SipHash seeds per process: output was NOT
464    // byte-stable across runs; 243/5579 files wobbled on reqable).
465    // Sorted block ids here + sorted preds below pin every tie.
466    let mut merge_order: Vec<usize> = appends.keys().copied().collect();
467    merge_order.sort_unstable();
468    let mut per_pred: HashMap<usize, Vec<(u32, u32, Expr)>> = HashMap::default();
469    for bid in merge_order {
470        for (p, pc, v, e) in &appends[&bid] {
471            per_pred.entry(*p).or_default().push((*pc, *v, e.clone()));
472        }
473    }
474    let mut pred_order: Vec<usize> = per_pred.keys().copied().collect();
475    pred_order.sort_unstable();
476    for p in pred_order {
477        let mut adds = per_pred.remove(&p).unwrap();
478        if p == usize::MAX {
479            continue;
480        }
481        adds.sort_by_key(|(pc, _, _)| *pc);
482        let term_is_exit = matches!(
483            results[p].term,
484            jdc_core::ir::build::Term::Return(_) | jdc_core::ir::build::Term::Throw(_)
485        );
486        if term_is_exit {
487            continue;
488        }
489        let phi_set: std::collections::HashSet<u32> = adds.iter().map(|(_, v, _)| *v).collect();
490        let mut snapshots: Vec<Stmt> = Vec::new();
491        // (phi, value) pairs with snapshot temps substituted.
492        let mut emitted: Vec<(u32, Expr)> = Vec::new();
493        for (_, v, e) in &adds {
494            let mut e = e.clone();
495            let mut refs_phi = false;
496            visit_phi_refs(&e, &phi_set, &mut refs_phi);
497            if refs_phi {
498                // Snapshot: emit `temp = value` BEFORE any phi assignment.
499                let ty = e.type_ref();
500                let id = vt.vars.len() as u32;
501                let name = format!("v{}", id);
502                vt.vars.push(jdc_core::var::VarInfo {
503                    id,
504                    slot: u16::MAX,
505                    name,
506                    ty: ty.clone(),
507                    is_param: false,
508                    range_start: 0,
509                    range_end: u16::MAX,
510                    synthetic_name: true,
511                });
512                snapshots.push(Stmt::LocalDef {
513                    var: id,
514                    init: Some(e),
515                    is_final: false,
516                    force_type: true,
517                });
518                e = Expr::Local { var: id, ty };
519            }
520            emitted.push((*v, e));
521        }
522        for st in snapshots {
523            results[p].stmts.push(st);
524        }
525        for (v, e) in emitted {
526            results[p].stmts.push(Stmt::ExprStmt(Expr::Assign {
527                target: Box::new(Expr::Local {
528                    var: v,
529                    ty: vt.var(v).ty.clone(),
530                }),
531                op: jdc_core::ir::expr::AssignOp::Plain,
532                value: Box::new(e),
533            }));
534        }
535    }
536
537    let t_fix = t0;
538    phase_hit_n(0, n, t_fix);
539    // ---- single-block fast path ----
540    // A lone basic block is straight-line code (any branch/switch/handler
541    // splits the graph): no merges, no phis, no control flow to structure.
542    // Bypassing the structurer + converter + the control-flow passes for
543    // these (over half of R8-produced methods) cuts the dominant cost.
544    if n == 1 && !entry_is_handler && cfg.blocks[0].pred.is_empty() {
545        let r = std::mem::replace(
546            &mut results[0],
547            BlockResult {
548                stmts: vec![],
549                out_stack: vec![],
550                term: jdc_core::ir::build::Term::Goto,
551            },
552        );
553        let mut body = r.stmts;
554        match r.term {
555            jdc_core::ir::build::Term::Return(Some(e)) => {
556                body.push(Stmt::Return(Some(e)));
557            }
558            jdc_core::ir::build::Term::Return(None) => {}
559            jdc_core::ir::build::Term::Throw(e) => body.push(Stmt::Throw(e)),
560            _ => {}
561        }
562        let mut body = Stmt::Block(body);
563        passes::fused_expr_rewrites(&mut body, &vt);
564        if mflags.has_sb() {
565            passes::fold_string_builders(&mut body, &vt);
566        }
567        passes::forward_single_use(&mut body, &vt);
568        passes::cleanup(&mut body);
569        passes::inline_accessors(&mut body, pool);
570        passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
571        passes::split_generations(&mut vt, &mut body);
572        passes::insert_object_narrowing_casts(&vt, &mut body);
573        passes::fix_incomparable_equality(&mut body, &vt, pool);
574        passes::fix_primitive_assign_casts(&vt, &mut body, &desc.ret);
575        passes::fix_primitive_arg_bridges(&mut body, &vt, pool);
576        passes::fix_bool_xor(&mut body, &vt, matches!(desc.ret, JavaType::Boolean));
577        passes::apply_local_names(&mut vt, &body);
578        passes::remove_kotlin_checks(&mut body);
579        passes::rewrite_kotlin_facades(&mut body, pool);
580        passes::platform_constants(&mut body);
581        passes::drop_dead_locals(&mut body);
582    passes::ensure_declared(&mut body, &vt);
583    // AFTER the declaration hoisting: ensure_declared inserts bare
584    // top-of-method declarations, and a local declaration ahead of the
585    // super() call is still "super must be first statement".
586    if &*m.name == "<init>" {
587        if class.is_enum() {
588            passes::strip_enum_ctor_super(&mut body);
589        } else {
590            passes::fix_ctor_delegation_arg_defs(&mut body);
591            passes::fix_ctor_conditional_super(&mut body);
592            passes::fix_ctor_super_first(&mut body);
593            passes::dedupe_ctor_delegations(&mut body);
594        }
595        // The delegation merges/hoists can leave prelude decls dead
596        // (their defs were inlined into the merged call) — the dropper
597        // ran BEFORE the ctor passes, so re-run it on their output.
598        passes::drop_dead_locals(&mut body);
599    }
600        passes::strip_trailing_void_return(&mut body);
601        passes::cleanup(&mut body);
602        passes::invert_empty_thens(&mut body);
603        passes::fold_short_circuits(&mut body);
604        passes::resolve_dangling_gotos(&mut body);
605        if !errors.is_empty() {
606            passes::prepend_comment(
607                &mut body,
608                format!("$DDC: {} block(s) failed to decompile", errors.len()),
609            );
610        }
611        phase_hit_n(2, n, t_fix);
612        record_bucket(n, t0);
613        return Ok(Some(MethodBody { body, vt, desc }));
614    }
615
616    // ---- structure + convert ----
617    // jcdc's copy-budget degradation: a rendering whose statement tree
618    // explodes past the guard retries at a halved copy budget (the
619    // structurer's tail-copying is the exponential mechanism).
620    const TREE_GUARD: usize = 20_000;
621    let core_cfg = cfg.to_core();
622    #[allow(unused_assignments)]
623    let mut body: Option<Stmt> = None;
624    // Copy budget scales with graph size: many-block methods are where the
625    // exponential tail-copy blowups live (weibo: 389 methods >100 blocks
626    // = 40% of all CPU at budget 512). Starting lower converges without
627    // the 6-round halving.
628    let mut budget: u32 = if n > 100 {
629        64
630    } else if n > 20 {
631        128
632    } else {
633        512
634    };
635    // Shared once-per-method artifacts: the O(groups²) exception-group
636    // scan and the full-graph dominator tree used to run TWICE per
637    // method (Structurer + Converter) and once more per copy-budget
638    // retry — monster classes (gson adapters) spent the bulk of their
639    // time there.
640    let groups = jdc_core::structure::group_exceptions_with(&core_cfg, Some(&results));
641    let dom_universe: jdc_core::FxHashSet<usize> = (0..core_cfg.blocks.len()).collect();
642    let dom = jdc_core::structure::compute_dominators(&core_cfg, &dom_universe, core_cfg.entry);
643    if trace_on() {
644        eprintln!("[mshape] {}.{} blocks={}", class.name, m.name, n);
645    }
646    #[cfg(feature = "visit-stats")]
647    {
648        jdc_core::structure::reset_visit_stats();
649    }
650    // Walk-visit budget, proportional to the block count: walk() runs
651    // roughly once per structured scope for sane CFGs, so 40n+512 is
652    // generous headroom — but the EXPONENTIAL explorations (Telegram
653    // SendMessagesHelper family: deep if/loop/try nesting whose scope
654    // count multiplies) consume visits geometrically and get cut to a
655    // Goto, which terminates the walk. Without this a single <16k-insn
656    // method can recurse for effectively forever while the worker (and
657    // the process) never finishes — Telegram's full run wrote every file
658    // yet hung for 300+ seconds on 25 such classes.
659    let walk_budget: u64 = walk_budget_override().unwrap_or(8 * n as u64 + 128);
660    // WORK budget (Σ universe.len() per visit): deterministic bound on
661    // total walk cost — the count budget above under-bounds per-visit
662    // cost for big-block exponential explorations (Telegram family),
663    // which the wall-clock deadline used to catch nondeterministically.
664    // 2M sits 10× above the 4-corpus legit census max (~203k work), so
665    // it never fires on healthy classes (battery outputs stay
666    // byte-identical — the count budget keeps cutting exactly where it
667    // always did) while bounding Telegram-scale explosions at ~2M work
668    // units regardless of machine load.
669    let walk_work_budget: u64 = walk_work_override()
670        .unwrap_or(2_000_000 + 128 * n as u64);
671    // Wall-clock guard — UNCHANGED original 1500ms. (It was briefly
672    // suspected of the run-to-run output flips under worker contention
673    // and scaled up; the real culprit was the shared static DUMMY in
674    // VarTable::var — fixed in jdc-core — and the larger deadlines only
675    // let pathological walks burn seconds longer: weixin +3s at 5.5s,
676    // +3.5s more at 46s. Legit methods finish ~10× under this bound.)
677    let walk_deadline = std::time::Instant::now()
678        + std::time::Duration::from_millis(
679            walk_ms_override().unwrap_or(1500),
680        );
681    loop {
682        jdc_core::structure::set_budget_override(Some(budget));
683        jdc_core::structure::set_walk_visit_budget(Some(walk_budget));
684        jdc_core::structure::set_walk_work_budget(Some(walk_work_budget));
685        jdc_core::structure::set_walk_deadline(Some(walk_deadline));
686        let mut st = Structurer::with_shared_groups(
687            &core_cfg,
688            &results,
689            &groups,
690            Default::default(),
691            Default::default(),
692        );
693        let region = st.structure_method();
694        let mut converter = Converter::with_precomputed_ref(&core_cfg, &results, &groups, &dom);
695        let candidate = converter.convert(region);
696        jdc_core::structure::set_budget_override(None);
697        jdc_core::structure::set_walk_visit_budget(None);
698        jdc_core::structure::set_walk_work_budget(None);
699        jdc_core::structure::set_walk_deadline(None);
700        let size = {
701            let mut c = 0usize;
702            passes::count_stmts_deep(&candidate, &mut c);
703            c
704        };
705        if trace_on() {
706            eprintln!("[guard] {}.{} size={} budget={}", class.name, m.name, size, budget);
707        }
708        if size <= TREE_GUARD {
709            body = Some(candidate);
710            break;
711        }
712        if budget <= 16 {
713            return Ok(Some(stub_body(
714                format!(
715                    "$DDC: statement tree exploded ({} nodes) even at copy budget 16",
716                    size
717                ),
718                desc,
719            )));
720        }
721        budget /= 2;
722    }
723    #[cfg(feature = "visit-stats")]
724    if trace_on() && n > 3 {
725        let used = jdc_core::structure::walk_visits_consumed();
726        eprintln!(
727            "[visits] {}.{} blocks={} consumed={} ratio={:.1}",
728            class.name,
729            m.name,
730            n,
731            used,
732            used as f64 / n as f64
733        );
734    }
735    phase_hit_n(1, n, t_fix);
736    let mut body = body.unwrap();
737    if !entry_phi_inits.is_empty() {
738        let head: Vec<Stmt> = entry_phi_inits
739            .into_iter()
740            .map(|(v, e)| Stmt::LocalDef {
741                var: v,
742                init: Some(e),
743                is_final: false,
744                force_type: true,
745            })
746            .collect();
747        body = match body {
748            Stmt::Block(v) => {
749                let mut nv = head;
750                nv.extend(v);
751                Stmt::Block(nv)
752            }
753            other => {
754                let mut nv = head;
755                nv.push(other);
756                Stmt::Block(nv)
757            }
758        };
759    }
760
761    passes::bind_catches(&mut body, &mut vt);
762    passes::prune_unreachable(&mut body);
763    // One traversal for cmp residuals + null compares + const-first flips
764    // (three separate full-tree walks before).
765    passes::fused_expr_rewrites(&mut body, &vt);
766    if mflags.has_sb() {
767        passes::fold_string_builders(&mut body, &vt);
768    }
769    passes::ternary_fold(&mut body);
770    if mflags.has_monitor() {
771        passes::fold_synchronized(&mut body);
772    }
773    passes::forward_single_use(&mut body, &vt);
774    passes::cleanup(&mut body);
775    passes::inline_accessors(&mut body, pool);
776    passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
777    passes::split_generations(&mut vt, &mut body);
778    // Post-booleanize re-split, gated on a nonzero conversion count:
779    // conversions expose register reuse across boolean/numeric kinds no
780    // earlier pass could see (`int v150` copying converted `boolean
781    // v131` — weixin ConstraintLayout ×1.4k); with nothing converted
782    // the fixpoint walk is pure decomp-time cost (the weixin 16→24s
783    // regression).
784    if passes::booleanize(&mut vt, &mut body, matches!(desc.ret, JavaType::Boolean)) > 0 {
785        passes::split_generations(&mut vt, &mut body);
786    }
787    if matches!(desc.ret, JavaType::Int | JavaType::Long | JavaType::Short | JavaType::Byte) {
788        passes::fix_int_returns(&vt, &mut body);
789    }
790    passes::insert_object_narrowing_casts(&vt, &mut body);
791    passes::fix_incomparable_equality(&mut body, &vt, pool);
792    passes::fix_primitive_assign_casts(&vt, &mut body, &desc.ret);
793    passes::fix_primitive_arg_bridges(&mut body, &vt, pool);
794    passes::fix_bool_xor(&mut body, &vt, matches!(desc.ret, JavaType::Boolean));
795    passes::apply_local_names(&mut vt, &body);
796    passes::remove_kotlin_checks(&mut body);
797    passes::rewrite_kotlin_facades(&mut body, pool);
798    passes::platform_constants(&mut body);
799    passes::drop_dead_locals(&mut body);
800    passes::ensure_declared(&mut body, &vt);
801    // AFTER the declaration hoisting: ensure_declared inserts bare
802    // top-of-method declarations, and a local declaration ahead of the
803    // super() call is still "super must be first statement".
804    if &*m.name == "<init>" {
805        if class.is_enum() {
806            passes::strip_enum_ctor_super(&mut body);
807        } else {
808            passes::fix_ctor_delegation_arg_defs(&mut body);
809            passes::fix_ctor_conditional_super(&mut body);
810            passes::fix_ctor_super_first(&mut body);
811            passes::dedupe_ctor_delegations(&mut body);
812        }
813        // The delegation merges/hoists can leave prelude decls dead
814        // (their defs were inlined into the merged call) — the dropper
815        // ran BEFORE the ctor passes, so re-run it on their output.
816        passes::drop_dead_locals(&mut body);
817    }
818    if &*m.name == "<clinit>" {
819        passes::strip_clinit_returns(&mut body);
820    }
821    passes::strip_trailing_void_return(&mut body);
822    passes::cleanup(&mut body);
823    // Short-circuit folding last: the diamond shapes are final only
824    // after cleanup merges singleton blocks.
825    passes::invert_empty_thens(&mut body);
826    passes::fold_short_circuits(&mut body);
827    passes::resolve_dangling_gotos(&mut body);
828
829    if !errors.is_empty() {
830        passes::prepend_comment(
831            &mut body,
832            format!("$DDC: {} block(s) failed to decompile", errors.len()),
833        );
834    }
835
836    phase_hit_n(2, n, t_fix);
837    record_bucket(n, t0);
838    Ok(Some(MethodBody { body, vt, desc }))
839}
840
841static PHASE_MICROS: [std::sync::atomic::AtomicU64; 5] = [
842    std::sync::atomic::AtomicU64::new(0),
843    std::sync::atomic::AtomicU64::new(0),
844    std::sync::atomic::AtomicU64::new(0),
845    std::sync::atomic::AtomicU64::new(0),
846    std::sync::atomic::AtomicU64::new(0),
847];
848/// Phase × bucket attribution (5 phases × 5 buckets, row-major).
849static PHASE_BUCKET_MICROS: [std::sync::atomic::AtomicU64; 25] = [
850    std::sync::atomic::AtomicU64::new(0),
851    std::sync::atomic::AtomicU64::new(0),
852    std::sync::atomic::AtomicU64::new(0),
853    std::sync::atomic::AtomicU64::new(0),
854    std::sync::atomic::AtomicU64::new(0),
855    std::sync::atomic::AtomicU64::new(0),
856    std::sync::atomic::AtomicU64::new(0),
857    std::sync::atomic::AtomicU64::new(0),
858    std::sync::atomic::AtomicU64::new(0),
859    std::sync::atomic::AtomicU64::new(0),
860    std::sync::atomic::AtomicU64::new(0),
861    std::sync::atomic::AtomicU64::new(0),
862    std::sync::atomic::AtomicU64::new(0),
863    std::sync::atomic::AtomicU64::new(0),
864    std::sync::atomic::AtomicU64::new(0),
865    std::sync::atomic::AtomicU64::new(0),
866    std::sync::atomic::AtomicU64::new(0),
867    std::sync::atomic::AtomicU64::new(0),
868    std::sync::atomic::AtomicU64::new(0),
869    std::sync::atomic::AtomicU64::new(0),
870    std::sync::atomic::AtomicU64::new(0),
871    std::sync::atomic::AtomicU64::new(0),
872    std::sync::atomic::AtomicU64::new(0),
873    std::sync::atomic::AtomicU64::new(0),
874    std::sync::atomic::AtomicU64::new(0),
875];
876static PHASE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
877
878fn bucket_of(n: usize) -> usize {
879    if n <= 1 {
880        0
881    } else if n <= 5 {
882        1
883    } else if n <= 20 {
884        2
885    } else if n <= 100 {
886        3
887    } else {
888        4
889    }
890}
891
892pub(crate) fn phase_hit_n(i: usize, n: usize, t: std::time::Instant) {
893    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
894        return;
895    }
896    let us = t.elapsed().as_micros() as u64;
897    PHASE_MICROS[i].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
898    PHASE_BUCKET_MICROS[i * 5 + bucket_of(n)].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
899}
900
901pub(crate) fn phase_hit(i: usize, t: std::time::Instant) {
902    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
903        return;
904    }
905    PHASE_MICROS[i].fetch_add(
906        t.elapsed().as_micros() as u64,
907        std::sync::atomic::Ordering::Relaxed,
908    );
909}
910
911/// Enable phase timers (DDC_PHASES=1).
912pub fn phases_enable() {
913    PHASE_ON.store(true, std::sync::atomic::Ordering::Relaxed);
914}
915
916/// (fixpoint, structure+convert, passes, print, total) in micros.
917pub fn phases_dump() -> [u64; 5] {
918    let mut out = [0u64; 5];
919    for i in 0..5 {
920        out[i] = PHASE_MICROS[i].load(std::sync::atomic::Ordering::Relaxed);
921    }
922    out
923}
924
925/// Per-bucket phase micros: 5 phases × 5 buckets, row-major.
926pub fn phases_bucket_dump() -> [[u64; 5]; 5] {
927    let mut out = [[0u64; 5]; 5];
928    for i in 0..5 {
929        for b in 0..5 {
930            out[i][b] = PHASE_BUCKET_MICROS[i * 5 + b].load(std::sync::atomic::Ordering::Relaxed);
931        }
932    }
933    out
934}
935
936static CAP_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
937static CAP_INSNS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
938
939static BUILD_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
940static INSN_LIFTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
941
942static BUCKET_COUNT: [std::sync::atomic::AtomicU64; 5] = [
943    std::sync::atomic::AtomicU64::new(0),
944    std::sync::atomic::AtomicU64::new(0),
945    std::sync::atomic::AtomicU64::new(0),
946    std::sync::atomic::AtomicU64::new(0),
947    std::sync::atomic::AtomicU64::new(0),
948];
949static BUCKET_MICROS: [std::sync::atomic::AtomicU64; 5] = [
950    std::sync::atomic::AtomicU64::new(0),
951    std::sync::atomic::AtomicU64::new(0),
952    std::sync::atomic::AtomicU64::new(0),
953    std::sync::atomic::AtomicU64::new(0),
954    std::sync::atomic::AtomicU64::new(0),
955];
956
957/// Dump build/insn counters.
958pub fn dump_builds() -> (u64, u64) {
959    (
960        BUILD_COUNT.load(std::sync::atomic::Ordering::Relaxed),
961        INSN_LIFTED.load(std::sync::atomic::Ordering::Relaxed),
962    )
963}
964
965/// (cap-hit methods, sum of insns*1000+blocks for cap-hit methods).
966pub fn dump_caps() -> (u64, u64) {
967    (
968        CAP_HITS.load(std::sync::atomic::Ordering::Relaxed),
969        CAP_INSNS.load(std::sync::atomic::Ordering::Relaxed),
970    )
971}
972
973/// Dump DDC_BUCKETS statistics (global atomics).
974pub fn dump_buckets() -> [(u64, u64); 5] {
975    let mut out = [(0u64, 0u64); 5];
976    for i in 0..5 {
977        out[i] = (
978            BUCKET_COUNT[i].load(std::sync::atomic::Ordering::Relaxed),
979            BUCKET_MICROS[i].load(std::sync::atomic::Ordering::Relaxed),
980        );
981    }
982    out
983}
984
985/// Dominator-recompute counters from jdc-core (perf diagnostics).
986pub fn dom_counters() -> (u64, u64) {
987    (
988        jdc_core::structure::DOM_CALLS.load(std::sync::atomic::Ordering::Relaxed),
989        jdc_core::structure::DOM_BLOCKS.load(std::sync::atomic::Ordering::Relaxed),
990    )
991}
992
993/// Enable dominator-recompute counters (diagnostics; jdc-core gate).
994pub fn dom_counters_enable() {
995    jdc_core::structure::set_dom_counters(true);
996}
997
998/// A minimal body carrying a diagnostic comment.
999fn stub_body(msg: String, desc: MethodDescriptor) -> MethodBody {
1000    MethodBody {
1001        body: Stmt::Block(vec![Stmt::Comment(msg)]),
1002        vt: VarTable::default(),
1003        desc,
1004    }
1005}
1006
1007/// True when any phi belongs to merge block `bid`.
1008fn phis_for_merge(bid: usize, phis: &HashMap<(usize, u16), u32>) -> bool {
1009    phis.keys().any(|(b, _)| *b == bid)
1010}
1011
1012/// Phi materialization records for `bid`'s predecessors (pred-tagged).
1013fn record_appends(
1014    cfg: &DexCfg,
1015    bid: usize,
1016    out_states: &[Option<OutState>],
1017    phis: &HashMap<(usize, u16), u32>,
1018    vt: &jdc_core::var::VarTable,
1019    out: &mut Vec<(usize, u32, u32, Expr)>,
1020) {
1021    for p in cfg.blocks[bid].pred.clone() {
1022        let Some(o) = &out_states[p] else { continue };
1023        for (r, st) in o.regs.iter().enumerate() {
1024            if let Some(&phi) = phis.get(&(bid, r as u16)) {
1025                let value = match st {
1026                    Reg::Live(v) if *v == phi => continue,
1027                    Reg::Live(v) => Expr::Local {
1028                        var: *v,
1029                        ty: vt.var(*v).ty.clone(),
1030                    },
1031                    Reg::Pending(e) | Reg::PendingCall(e) => e.clone(),
1032                    Reg::Undef | Reg::WideHi => continue,
1033                };
1034                out.push((p, o.write_pc.get(r).copied().unwrap_or(0), phi, value));
1035            }
1036        }
1037    }
1038}
1039
1040#[allow(unused)]
1041fn record_bucket(n: usize, t0: std::time::Instant) {
1042    // (Perf: env::var is a lock+lookup — per-METHOD cost on 716k-method
1043    // runs; resolve once via OnceLock.)
1044    static BUCKETS_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1045    if !*BUCKETS_ON.get_or_init(|| std::env::var("DDC_BUCKETS").is_ok()) {
1046        return;
1047    }
1048    let bucket = if n <= 1 {
1049        0
1050    } else if n <= 5 {
1051        1
1052    } else if n <= 20 {
1053        2
1054    } else if n <= 100 {
1055        3
1056    } else {
1057        4
1058    };
1059    BUCKET_COUNT[bucket].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1060    BUCKET_MICROS[bucket].fetch_add(
1061        t0.elapsed().as_micros() as u64,
1062        std::sync::atomic::Ordering::Relaxed,
1063    );
1064}
1065
1066/// True when the expression references any of the phi vars.
1067fn visit_phi_refs(e: &Expr, phis: &std::collections::HashSet<u32>, hit: &mut bool) {
1068    if *hit {
1069        return;
1070    }
1071    if let Expr::Local { var, .. } = e {
1072        if phis.contains(var) {
1073            *hit = true;
1074        }
1075        return;
1076    }
1077    let mut kids: Vec<&Expr> = Vec::new();
1078    match e {
1079        Expr::Un { e, .. } | Expr::Cast { e, .. } | Expr::InstanceOf { e, .. } => kids.push(e),
1080        Expr::Bin { l, r, .. } => {
1081            kids.push(l);
1082            kids.push(r);
1083        }
1084        Expr::Cond { c, t, f } => {
1085            kids.push(c);
1086            kids.push(t);
1087            kids.push(f);
1088        }
1089        Expr::Assign { target, value, .. } => {
1090            kids.push(target);
1091            kids.push(value);
1092        }
1093        Expr::PreIncDec { e, .. } | Expr::PostIncDec { e, .. } => kids.push(e),
1094        Expr::Field { owner: Some(o), .. } => kids.push(o),
1095        Expr::Method {
1096            owner: Some(o),
1097            args,
1098            ..
1099        } => {
1100            kids.push(o);
1101            kids.extend(args.iter());
1102        }
1103        Expr::ArrayIndex { array, index } => {
1104            kids.push(array);
1105            kids.push(index);
1106        }
1107        Expr::New { args, .. } => kids.extend(args.iter()),
1108        Expr::NewArray { dims, init, .. } => {
1109            kids.extend(dims.iter());
1110            if let Some(v) = init {
1111                kids.extend(v.iter());
1112            }
1113        }
1114        Expr::NewMultiArray { dims, .. } => kids.extend(dims.iter()),
1115        _ => {}
1116    }
1117    for k in kids {
1118        visit_phi_refs(k, phis, hit);
1119        if *hit {
1120            return;
1121        }
1122    }
1123}
1124
1125/// Merge several predecessor register states: pass identical values
1126/// through, otherwise materialize into a phi var for `(block, register)`.
1127/// Debug-info name covering `(pc, slot)`, sanitized (shared by the
1128/// lifter and the merge path).
1129fn debug_name_at(
1130    locals: &[ddc_dex::DebugLocal],
1131    slot: u16,
1132    pc: u32,
1133    ty: &jdc_core::types::JavaType,
1134) -> Option<String> {
1135    if locals.is_empty() {
1136        return None;
1137    }
1138    let hit = locals.iter().find(|l| {
1139        l.reg == slot
1140            && pc >= l.start
1141            && pc < l.end
1142            && l.ty.as_deref().map(|d| &crate::desc_type(d) == ty).unwrap_or(true)
1143    })?;
1144    let n = crate::classdec::java_ident(&hit.name);
1145    if n.is_empty() {
1146        None
1147    } else {
1148        Some(n.into_owned())
1149    }
1150}
1151
1152fn merge_states(
1153    vt: &mut VarTable,
1154    phis: &mut HashMap<(usize, u16), u32>,
1155    bid: usize,
1156    sides: &[&[Reg]],
1157    debug_locals: &[ddc_dex::DebugLocal],
1158    merge_pc: u32,
1159) -> Vec<Reg> {
1160    let len = sides.iter().map(|s| s.len()).max().unwrap_or(0);
1161    let mut out = vec![Reg::Undef; len];
1162    for (r, slot) in out.iter_mut().enumerate() {
1163        let mut all_eq = true;
1164        let mut first: Option<&Reg> = None;
1165        for s in sides {
1166            let v = s.get(r);
1167            match (first, v) {
1168                (None, v) => first = v,
1169                (Some(f), Some(v)) if f == v => {}
1170                _ => all_eq = false,
1171            }
1172        }
1173        if all_eq {
1174            *slot = first.cloned().unwrap_or(Reg::Undef);
1175            continue;
1176        }
1177        // Diverged: phi var.
1178        let key = (bid, r as u16);
1179        let phi = match phis.get(&key) {
1180            Some(&v) => v,
1181            None => {
1182                let ty = join_side_types(vt, sides, r);
1183                // Loop-carried values are usually THE source local (the
1184                // `char[] out` / `int i` of a loop): name the phi from the
1185                // debug range covering the merge block's head. When a var
1186                // of that name+type already exists, REUSE it — per-block
1187                // copies of one source local degrade to out/out2/out3
1188                // suffix soup, and one register+type = one Java local is
1189                // exactly Dalvik semantics.
1190                if let Some(n) = debug_name_at(debug_locals, r as u16, merge_pc, &ty.erased()) {
1191                    let unified = vt
1192                        .vars
1193                        .iter()
1194                        .find(|v| {
1195                            v.slot == r as u16
1196                                && !v.synthetic_name
1197                                && v.name == n
1198                                && v.ty.erased() == ty.erased()
1199                        })
1200                        .map(|v| v.id);
1201                    let id = match unified {
1202                        Some(id) => id,
1203                        None => {
1204                            let id = vt.vars.len() as u32;
1205                            vt.vars.push(jdc_core::var::VarInfo {
1206                                id,
1207                                slot: r as u16,
1208                                name: n,
1209                                ty,
1210                                is_param: false,
1211                                range_start: 0,
1212                                range_end: u16::MAX,
1213                                synthetic_name: false,
1214                            });
1215                            while vt.by_slot.len() <= r {
1216                                vt.by_slot.push(Vec::new());
1217                            }
1218                            vt.by_slot[r].push((0, u16::MAX, id));
1219                            id
1220                        }
1221                    };
1222                    phis.insert(key, id);
1223                    id
1224                } else {
1225                    let id = vt.vars.len() as u32;
1226                    vt.vars.push(jdc_core::var::VarInfo {
1227                        id,
1228                        slot: r as u16,
1229                        name: format!("v{}", id),
1230                        ty,
1231                        is_param: false,
1232                        range_start: 0,
1233                        range_end: u16::MAX,
1234                        synthetic_name: true,
1235                    });
1236                    while vt.by_slot.len() <= r {
1237                        vt.by_slot.push(Vec::new());
1238                    }
1239                    vt.by_slot[r].push((0, u16::MAX, id));
1240                    phis.insert(key, id);
1241                    id
1242                }
1243            }
1244        };
1245        *slot = Reg::Live(phi);
1246    }
1247    out
1248}
1249
1250/// Type of a phi var: join of the non-null side values' erased types.
1251fn join_side_types(vt: &VarTable, sides: &[&[Reg]], r: usize) -> TypeRef {
1252    let mut ty: Option<JavaType> = None;
1253    for s in sides {
1254        let st = s.get(r).cloned().unwrap_or(Reg::Undef);
1255        let e = match st {
1256            Reg::Pending(e) | Reg::PendingCall(e) => e,
1257            Reg::Live(v) => Expr::Local {
1258                var: v,
1259                ty: vt.var(v).ty.clone(),
1260            },
1261            _ => continue,
1262        };
1263        let t = e.type_ref().erased();
1264        ty = Some(match ty {
1265            None => t,
1266            Some(prev) => join_types(&prev, &t),
1267        });
1268    }
1269    TypeRef::J(ty.unwrap_or(JavaType::Int))
1270}
1271
1272fn join_types(a: &JavaType, b: &JavaType) -> JavaType {
1273    if a == b {
1274        return a.clone();
1275    }
1276    let num = |t: &JavaType| {
1277        matches!(
1278            t,
1279            JavaType::Boolean
1280                | JavaType::Byte
1281                | JavaType::Char
1282                | JavaType::Short
1283                | JavaType::Int
1284                | JavaType::Long
1285                | JavaType::Float
1286                | JavaType::Double
1287        )
1288    };
1289    if num(a) && num(b) {
1290        // Numeric promotion.
1291        return match (a, b) {
1292            (JavaType::Double, _) | (_, JavaType::Double) => JavaType::Double,
1293            (JavaType::Float, _) | (_, JavaType::Float) => JavaType::Float,
1294            (JavaType::Long, _) | (_, JavaType::Long) => JavaType::Long,
1295            _ => JavaType::Int,
1296        };
1297    }
1298    if let (JavaType::Object(x), JavaType::Object(y)) = (a, b) {
1299        if x == y {
1300            return a.clone();
1301        }
1302        // Char/int ternaries join to int; otherwise objects join to Object.
1303        return JavaType::Object("java/lang/Object".into());
1304    }
1305    JavaType::Object("java/lang/Object".into())
1306}
1307
1308/// True when the block's terminator exits (used by callers to skip appends).
1309#[allow(dead_code)]
1310fn is_exit_term(term: &jdc_core::ir::build::Term) -> bool {
1311    matches!(
1312        term,
1313        jdc_core::ir::build::Term::Return(_) | jdc_core::ir::build::Term::Throw(_)
1314    )
1315}
1316
1317#[allow(dead_code)]
1318fn unused(_: &InsnKind) {}