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