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    // SSA Phase 0 census (read-only, DDC_SSA_REPORT-gated).
122    if crate::ssa_census::enabled() {
123        crate::ssa_census::census_method(&cfg, &env);
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, &class.name);
570        passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
571        passes::fix_ref_null_assigns(&vt, &mut body);
572        passes::fix_null_sentinels(&mut body, &vt, &desc.ret);
573        passes::split_generations(&mut vt, &mut body, pool);
574        passes::insert_object_narrowing_casts(&vt, &mut body, pool, &desc.ret);
575        passes::fix_field_owner_downcasts(&mut body, &vt, pool);
576        passes::fix_shadowed_super_fields(&mut body, &vt, pool, &class.name);
577        passes::fix_incomparable_equality(&mut body, &vt, pool);
578        passes::fix_primitive_assign_casts(&vt, &mut body, &desc.ret);
579        passes::fix_primitive_arg_bridges(&mut body, &vt, pool);
580        passes::fix_bool_xor(&mut body, &vt, matches!(desc.ret, JavaType::Boolean));
581        passes::fix_int_operand_bridges(&mut body, &vt);
582        passes::fix_ref_array_null_consts(&mut body);
583        passes::idiom_compounds(&mut body, &vt);
584        passes::rescue_primitive_receivers(&mut body, &vt, pool);
585        passes::fix_this0_owners(&mut body, &class.name);
586        passes::apply_local_names(&mut vt, &body);
587    passes::deshadow_locals(&mut vt, pool, &class.name, &body);
588        passes::remove_kotlin_checks(&mut body);
589        passes::rewrite_kotlin_facades(&mut body, pool);
590        passes::platform_constants(&mut body);
591        passes::drop_dead_locals(&mut body);
592    passes::drop_dead_raw_news(&mut body);
593    passes::drop_empty_finallies(&mut body);
594    passes::drop_pure_value_stmts(&mut body);
595    passes::mark_field_owner_concrete(&mut vt, &mut body);
596    passes::ensure_declared(&mut body, &vt);
597    passes::rescue_arg_return_swaps(&mut body, &vt, pool, &desc.ret);
598    // AFTER the declaration hoisting: ensure_declared inserts bare
599    // top-of-method declarations, and a local declaration ahead of the
600    // super() call is still "super must be first statement".
601    if &*m.name == "<init>" {
602        // Boolean value-diamond folds ahead of the delegation machinery:
603        // a branched bridge ctor whose else arm COMPUTES the defaulted
604        // boolean (`v=false; if(x!=null){u=x.m(); v=false; if(u){v=true}}`)
605        // is Dirty for split_branch — folded to `v = x!=null && x.m()`
606        // (interleaved forwarding inlines the impure `u` the fold
607        // exposes) the arm is linear defs and merge_at lifts the this()
608        // (lark MmCreateAudioRequest, this-not-first ×456 family).
609        passes::fold_bool_value_diamonds(&mut body, &vt);
610        passes::fold_value_diamonds(&mut body, &vt);
611        passes::fix_ctor_this_aliases(&mut body, &vt);
612        // Vendor hotfix ctor guards wrap the delegation inside an If and
613        // fire for ENUM ctors too (alipay InstantRun fallback enums are
614        // the whole 1,436 ctor-not-first population) — run before the
615        // enum/regular split, and before the classdec trace-param store
616        // injection whose delegation-first probe must see the real head.
617        passes::strip_ctor_hotfix_guards(&mut body);
618        if class.is_enum() {
619            passes::fold_enum_default_arg_bridge(&mut body);
620            // Strip the implicit Enum.<init> super() ONLY for the enum
621            // BASE (super is java/lang/Enum or Object — a true `enum`
622            // decl or the fallback `/* enum */ class`, both get an
623            // implicit Object/Enum super). An enum CONSTANT SUBCLASS
624            // (j$6, super = the enum base j) renders as a plain
625            // `class j$6 extends j`; its ctor MUST forward
626            // `super(name, ordinal, ..)` or the implicit no-arg super()
627            // fails ("对于j(没有参数), 找不到合适的构造器", weibo jsoup
628            // TokeniserState ×134).
629            let const_subclass = class
630                .super_name
631                .as_ref()
632                .map(|s| s != "java/lang/Object" && s != "java/lang/Enum")
633                .unwrap_or(false);
634            if !const_subclass {
635                passes::strip_enum_ctor_super(&mut body);
636            }
637        } else {
638            passes::fix_ctor_delegation_arg_defs(&mut body);
639            passes::fix_ctor_conditional_super(&mut body);
640            passes::fix_ctor_super_first(&mut body, &vt);
641            passes::dedupe_ctor_delegations(&mut body);
642            passes::strip_secondary_delegations(&mut body);
643            passes::hoist_branch_delegations(&mut body, &vt);
644            passes::extract_branched_delegation_helper(&mut body, &vt, pool, class, &desc.to_string());
645        }
646        // The delegation merges/hoists can leave prelude decls dead
647        // (their defs were inlined into the merged call) — the dropper
648        // ran BEFORE the ctor passes, so re-run it on their output.
649        passes::drop_dead_locals(&mut body);
650    }
651        passes::strip_trailing_void_return(&mut body);
652        passes::cleanup(&mut body);
653        passes::invert_empty_thens(&mut body);
654        passes::fold_short_circuits(&mut body);
655        passes::resolve_dangling_gotos(&mut body);
656    passes::dedupe_multicatch(&mut body, pool);
657    passes::strip_phantom_field_writes(&mut body, pool);
658    passes::init_bare_decls(&mut body, &vt);
659        if !errors.is_empty() {
660            passes::prepend_comment(
661                &mut body,
662                format!("$DDC: {} block(s) failed to decompile", errors.len()),
663            );
664        }
665        phase_hit_n(2, n, t_fix);
666        record_bucket(n, t0);
667        return Ok(Some(MethodBody { body, vt, desc }));
668    }
669
670    // ---- structure + convert ----
671    // jcdc's copy-budget degradation: a rendering whose statement tree
672    // explodes past the guard retries at a halved copy budget (the
673    // structurer's tail-copying is the exponential mechanism).
674    const TREE_GUARD: usize = 20_000;
675    let core_cfg = cfg.to_core();
676    #[allow(unused_assignments)]
677    let mut body: Option<Stmt> = None;
678    let mut prev_size: Option<usize> = None;
679    // Copy budget scales with graph size: many-block methods are where the
680    // exponential tail-copy blowups live (weibo: 389 methods >100 blocks
681    // = 40% of all CPU at budget 512). Starting lower converges without
682    // the 6-round halving.
683    let mut budget: u32 = if n > 100 {
684        64
685    } else if n > 20 {
686        128
687    } else {
688        512
689    };
690    // Shared once-per-method artifacts: the O(groups²) exception-group
691    // scan and the full-graph dominator tree used to run TWICE per
692    // method (Structurer + Converter) and once more per copy-budget
693    // retry — monster classes (gson adapters) spent the bulk of their
694    // time there.
695    let groups = jdc_core::structure::group_exceptions_with(&core_cfg, Some(&results));
696    let dom_universe: jdc_core::FxHashSet<usize> = (0..core_cfg.blocks.len()).collect();
697    let dom = jdc_core::structure::compute_dominators(&core_cfg, &dom_universe, core_cfg.entry);
698    if trace_on() {
699        eprintln!("[mshape] {}.{} blocks={}", class.name, m.name, n);
700    }
701    // Deterministic giant-method stub: at ~2.1k+ CFG blocks a single
702    // structuring walk can burn 9s+ of wall time (weibo Gson doRead:
703    // 2,179/3,230 blocks — per-visit dominator-pass cost scales far
704    // faster than the Σ universe.len() charge model can bound, and the
705    // spread across CFG shapes defeats any charge calibration). Healthy
706    // methods below the line (JsonUserInfoTypeAdapter, 1,997 blocks)
707    // structure fully, so stubbing beats both alternatives: burning the
708    // class watchdog DROPS the whole file (every referrer cannot-finds)
709    // and the old wall-clock deadline flipped output nondeterministically
710    // under worker contention.
711    if n >= 2_100 {
712        return Ok(Some(stub_body(
713            format!(
714                "$DDC: method too large ({} blocks) — body elided for determinism",
715                n
716            ),
717            desc,
718        )));
719    }
720    #[cfg(feature = "visit-stats")]
721    {
722        jdc_core::structure::reset_visit_stats();
723    }
724    // Walk-visit budget, proportional to the block count: walk() runs
725    // roughly once per structured scope for sane CFGs, so 40n+512 is
726    // generous headroom — but the EXPONENTIAL explorations (Telegram
727    // SendMessagesHelper family: deep if/loop/try nesting whose scope
728    // count multiplies) consume visits geometrically and get cut to a
729    // Goto, which terminates the walk. Without this a single <16k-insn
730    // method can recurse for effectively forever while the worker (and
731    // the process) never finishes — Telegram's full run wrote every file
732    // yet hung for 300+ seconds on 25 such classes.
733    let walk_budget: u64 = walk_budget_override().unwrap_or(8 * n as u64 + 128);
734    // WORK budget (Σ universe.len() per visit): deterministic bound on
735    // total walk cost — the count budget above under-bounds per-visit
736    // cost for big-block exponential explorations (Telegram family),
737    // which the wall-clock deadline used to catch nondeterministically.
738    // A visit's REAL cost grows with the universe (dominator-style
739    // passes: weibo doRead n=2179 burned 15µs per charge unit vs 5µs at
740    // n=1533), so a flat charge budget still lets giants run 9s+ per
741    // rung and trip the class watchdog (dropped files — every referrer
742    // cannot-finds — are strictly worse than walk-cut degradation).
743    let walk_work_budget: u64 = walk_work_override()
744        .unwrap_or(600_000 + 128 * n as u64);
745    // No wall-clock deadline here: the work budget above bounds walk
746    // cost deterministically, and the old 1500ms guard flipped
747    // borderline giants (weixin vm/a0.n, 28.5k nodes) between full body
748    // and exploded stub run-to-run under worker contention. The
749    // class-level 5s watchdog in classdec remains as the hang safety
750    // net for pathological CFGs.
751    loop {
752        jdc_core::structure::set_budget_override(Some(budget));
753        jdc_core::structure::set_walk_visit_budget(Some(walk_budget));
754        jdc_core::structure::set_walk_work_budget(Some(walk_work_budget));
755        let mut st = Structurer::with_shared_groups(
756            &core_cfg,
757            &results,
758            &groups,
759            Default::default(),
760            Default::default(),
761        );
762        let tw0 = std::time::Instant::now();
763        let region = st.structure_method();
764        let tw1 = std::time::Instant::now();
765        let mut converter = Converter::with_precomputed_ref(&core_cfg, &results, &groups, &dom);
766        let candidate = converter.convert(region);
767        let tw2 = std::time::Instant::now();
768        if trace_on() {
769            eprintln!(
770                "[rung] {}.{} budget={} walk={:?} convert={:?}",
771                class.name, m.name, budget, tw1 - tw0, tw2 - tw1
772            );
773        }
774        jdc_core::structure::set_budget_override(None);
775        jdc_core::structure::set_walk_visit_budget(None);
776        jdc_core::structure::set_walk_work_budget(None);
777        let size = {
778            let mut c = 0usize;
779            passes::count_stmts_deep(&candidate, &mut c);
780            c
781        };
782        if trace_on() {
783            eprintln!("[guard] {}.{} size={} budget={}", class.name, m.name, size, budget);
784        }
785        if size <= TREE_GUARD {
786            body = Some(candidate);
787            break;
788        }
789        // Giant short-circuit: deep in the ladder (budget ≤ 64), a tree
790        // still 3× over the guard will not shrink under further copy-budget
791        // halving (weixin cdp/l1.w: 72,782 nodes at 64, ~2.8s of walk PER
792        // rung) — stub now instead of burning two more rungs and tripping
793        // the classdec 5s watchdog, which DROPS the whole file (every
794        // referrer cannot-finds — strictly worse than one stubbed body).
795        // Deterministic: driven by measured size, not wall-clock.
796        if budget <= 64 && size > 3 * TREE_GUARD {
797            return Ok(Some(stub_body(
798                format!(
799                    "$DDC: statement tree exploded ({} nodes) — pathological CFG, body elided",
800                    size
801                ),
802                desc,
803            )));
804        }
805        // No-progress short-circuit: the copy budget only bounds tail
806        // duplication — if halving it did not shrink the tree at all,
807        // further rungs cannot either (weixin vm/a0.n sits at ~28.5k
808        // across every rung, burning a full work-budget walk each).
809        // Deterministic, and saves the giant methods ~3 rungs of walk.
810        if budget <= 32 && prev_size.is_some_and(|p| size >= p) {
811            return Ok(Some(stub_body(
812                format!(
813                    "$DDC: statement tree exploded ({} nodes) — pathological CFG, body elided",
814                    size
815                ),
816                desc,
817            )));
818        }
819        prev_size = Some(size);
820        if budget <= 16 {
821            return Ok(Some(stub_body(
822                format!(
823                    "$DDC: statement tree exploded ({} nodes) even at copy budget 16",
824                    size
825                ),
826                desc,
827            )));
828        }
829        budget /= 2;
830    }
831    #[cfg(feature = "visit-stats")]
832    if trace_on() && n > 3 {
833        let used = jdc_core::structure::walk_visits_consumed();
834        eprintln!(
835            "[visits] {}.{} blocks={} consumed={} ratio={:.1}",
836            class.name,
837            m.name,
838            n,
839            used,
840            used as f64 / n as f64
841        );
842    }
843    phase_hit_n(1, n, t_fix);
844    let mut body = body.unwrap();
845    if !entry_phi_inits.is_empty() {
846        let head: Vec<Stmt> = entry_phi_inits
847            .into_iter()
848            .map(|(v, e)| Stmt::LocalDef {
849                var: v,
850                init: Some(e),
851                is_final: false,
852                force_type: true,
853            })
854            .collect();
855        body = match body {
856            Stmt::Block(v) => {
857                let mut nv = head;
858                nv.extend(v);
859                Stmt::Block(nv)
860            }
861            other => {
862                let mut nv = head;
863                nv.push(other);
864                Stmt::Block(nv)
865            }
866        };
867    }
868
869    passes::bind_catches(&mut body, &mut vt);
870    passes::prune_unreachable(&mut body);
871    // One traversal for cmp residuals + null compares + const-first flips
872    // (three separate full-tree walks before).
873    passes::fused_expr_rewrites(&mut body, &vt);
874    if mflags.has_sb() {
875        passes::fold_string_builders(&mut body, &vt);
876    }
877    passes::ternary_fold(&mut body);
878    passes::drop_empty_finallies(&mut body);
879    passes::drop_pure_value_stmts(&mut body);
880    if mflags.has_monitor() {
881        passes::fold_synchronized(&mut body);
882    }
883    passes::forward_single_use(&mut body, &vt);
884    passes::cleanup(&mut body);
885    passes::inline_accessors(&mut body, pool, &class.name);
886    passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
887    passes::fix_ref_null_assigns(&vt, &mut body);
888    passes::fix_null_sentinels(&mut body, &vt, &desc.ret);
889    passes::split_generations(&mut vt, &mut body, pool);
890    // Post-booleanize re-split, gated on a nonzero conversion count:
891    // conversions expose register reuse across boolean/numeric kinds no
892    // earlier pass could see (`int v150` copying converted `boolean
893    // v131` — weixin ConstraintLayout ×1.4k); with nothing converted
894    // the fixpoint walk is pure decomp-time cost (the weixin 16→24s
895    // regression).
896    // Booleanize ↔ split fixpoint, bounded, ENDING on a booleanize:
897    // each split MINTS fresh generation vars that inherit the stale int
898    // type while receiving boolean values (`int v264_g160_g7_g3 =
899    // !v200` with `!= 0` reads — weixin bool→int assign family, 2.8k
900    // lines). Only a FOLLOWING booleanize retypes them and folds their
901    // `v != 0` reads; a trailing split would leave the folds undone.
902    {
903        let rb = matches!(desc.ret, JavaType::Boolean);
904        let mut rounds = 0;
905        loop {
906            let c = passes::booleanize(&mut vt, &mut body, rb);
907            rounds += 1;
908            if c == 0 || rounds >= 3 {
909                break;
910            }
911            passes::split_generations(&mut vt, &mut body, pool);
912        }
913    }
914    if matches!(
915        desc.ret,
916        JavaType::Int | JavaType::Long | JavaType::Short | JavaType::Byte | JavaType::Float | JavaType::Double
917    ) {
918        passes::fix_int_returns(&vt, &mut body);
919    }
920    if matches!(desc.ret, JavaType::Boolean) {
921        passes::fix_bool_returns(&vt, &mut body);
922    }
923    passes::insert_object_narrowing_casts(&vt, &mut body, pool, &desc.ret);
924    passes::fix_field_owner_downcasts(&mut body, &vt, pool);
925    passes::fix_shadowed_super_fields(&mut body, &vt, pool, &class.name);
926    passes::fix_incomparable_equality(&mut body, &vt, pool);
927    passes::fix_primitive_assign_casts(&vt, &mut body, &desc.ret);
928    passes::fix_primitive_arg_bridges(&mut body, &vt, pool);
929    passes::fix_bool_xor(&mut body, &vt, matches!(desc.ret, JavaType::Boolean));
930    passes::fix_int_operand_bridges(&mut body, &vt);
931    passes::fix_ref_array_null_consts(&mut body);
932    passes::idiom_compounds(&mut body, &vt);
933    passes::rescue_primitive_receivers(&mut body, &vt, pool);
934    passes::fix_this0_owners(&mut body, &class.name);
935    passes::apply_local_names(&mut vt, &body);
936    passes::deshadow_locals(&mut vt, pool, &class.name, &body);
937    passes::remove_kotlin_checks(&mut body);
938    passes::rewrite_kotlin_facades(&mut body, pool);
939    passes::platform_constants(&mut body);
940    passes::drop_dead_locals(&mut body);
941    passes::drop_dead_raw_news(&mut body);
942    passes::mark_field_owner_concrete(&mut vt, &mut body);
943    passes::ensure_declared(&mut body, &vt);
944    passes::rescue_arg_return_swaps(&mut body, &vt, pool, &desc.ret);
945    // AFTER the declaration hoisting: ensure_declared inserts bare
946    // top-of-method declarations, and a local declaration ahead of the
947    // super() call is still "super must be first statement".
948    if &*m.name == "<init>" {
949        // Boolean value-diamond folds ahead of the delegation machinery:
950        // a branched bridge ctor whose else arm COMPUTES the defaulted
951        // boolean (`v=false; if(x!=null){u=x.m(); v=false; if(u){v=true}}`)
952        // is Dirty for split_branch — folded to `v = x!=null && x.m()`
953        // (interleaved forwarding inlines the impure `u` the fold
954        // exposes) the arm is linear defs and merge_at lifts the this()
955        // (lark MmCreateAudioRequest, this-not-first ×456 family).
956        passes::fold_bool_value_diamonds(&mut body, &vt);
957        passes::fold_value_diamonds(&mut body, &vt);
958        passes::fix_ctor_this_aliases(&mut body, &vt);
959        // Vendor hotfix ctor guards wrap the delegation inside an If and
960        // fire for ENUM ctors too (alipay InstantRun fallback enums are
961        // the whole 1,436 ctor-not-first population) — run before the
962        // enum/regular split, and before the classdec trace-param store
963        // injection whose delegation-first probe must see the real head.
964        passes::strip_ctor_hotfix_guards(&mut body);
965        if class.is_enum() {
966            passes::fold_enum_default_arg_bridge(&mut body);
967            // Strip the implicit Enum.<init> super() ONLY for the enum
968            // BASE (super is java/lang/Enum or Object — a true `enum`
969            // decl or the fallback `/* enum */ class`, both get an
970            // implicit Object/Enum super). An enum CONSTANT SUBCLASS
971            // (j$6, super = the enum base j) renders as a plain
972            // `class j$6 extends j`; its ctor MUST forward
973            // `super(name, ordinal, ..)` or the implicit no-arg super()
974            // fails ("对于j(没有参数), 找不到合适的构造器", weibo jsoup
975            // TokeniserState ×134).
976            let const_subclass = class
977                .super_name
978                .as_ref()
979                .map(|s| s != "java/lang/Object" && s != "java/lang/Enum")
980                .unwrap_or(false);
981            if !const_subclass {
982                passes::strip_enum_ctor_super(&mut body);
983            }
984        } else {
985            passes::fix_ctor_delegation_arg_defs(&mut body);
986            passes::fix_ctor_conditional_super(&mut body);
987            passes::fix_ctor_super_first(&mut body, &vt);
988            passes::dedupe_ctor_delegations(&mut body);
989            passes::strip_secondary_delegations(&mut body);
990            passes::hoist_branch_delegations(&mut body, &vt);
991            passes::extract_branched_delegation_helper(&mut body, &vt, pool, class, &desc.to_string());
992        }
993        // The delegation merges/hoists can leave prelude decls dead
994        // (their defs were inlined into the merged call) — the dropper
995        // ran BEFORE the ctor passes, so re-run it on their output.
996        passes::drop_dead_locals(&mut body);
997    }
998    if &*m.name == "<clinit>" {
999        passes::strip_clinit_returns(&mut body);
1000    }
1001    passes::strip_trailing_void_return(&mut body);
1002    passes::cleanup(&mut body);
1003    // Short-circuit folding last: the diamond shapes are final only
1004    // after cleanup merges singleton blocks.
1005    passes::invert_empty_thens(&mut body);
1006    passes::fold_short_circuits(&mut body);
1007    passes::resolve_dangling_gotos(&mut body);
1008    passes::dedupe_multicatch(&mut body, pool);
1009    passes::strip_phantom_field_writes(&mut body, pool);
1010    passes::init_bare_decls(&mut body, &vt);
1011
1012    if !errors.is_empty() {
1013        passes::prepend_comment(
1014            &mut body,
1015            format!("$DDC: {} block(s) failed to decompile", errors.len()),
1016        );
1017    }
1018
1019    phase_hit_n(2, n, t_fix);
1020    record_bucket(n, t0);
1021    Ok(Some(MethodBody { body, vt, desc }))
1022}
1023
1024static PHASE_MICROS: [std::sync::atomic::AtomicU64; 5] = [
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    std::sync::atomic::AtomicU64::new(0),
1030];
1031/// Phase × bucket attribution (5 phases × 5 buckets, row-major).
1032static PHASE_BUCKET_MICROS: [std::sync::atomic::AtomicU64; 25] = [
1033    std::sync::atomic::AtomicU64::new(0),
1034    std::sync::atomic::AtomicU64::new(0),
1035    std::sync::atomic::AtomicU64::new(0),
1036    std::sync::atomic::AtomicU64::new(0),
1037    std::sync::atomic::AtomicU64::new(0),
1038    std::sync::atomic::AtomicU64::new(0),
1039    std::sync::atomic::AtomicU64::new(0),
1040    std::sync::atomic::AtomicU64::new(0),
1041    std::sync::atomic::AtomicU64::new(0),
1042    std::sync::atomic::AtomicU64::new(0),
1043    std::sync::atomic::AtomicU64::new(0),
1044    std::sync::atomic::AtomicU64::new(0),
1045    std::sync::atomic::AtomicU64::new(0),
1046    std::sync::atomic::AtomicU64::new(0),
1047    std::sync::atomic::AtomicU64::new(0),
1048    std::sync::atomic::AtomicU64::new(0),
1049    std::sync::atomic::AtomicU64::new(0),
1050    std::sync::atomic::AtomicU64::new(0),
1051    std::sync::atomic::AtomicU64::new(0),
1052    std::sync::atomic::AtomicU64::new(0),
1053    std::sync::atomic::AtomicU64::new(0),
1054    std::sync::atomic::AtomicU64::new(0),
1055    std::sync::atomic::AtomicU64::new(0),
1056    std::sync::atomic::AtomicU64::new(0),
1057    std::sync::atomic::AtomicU64::new(0),
1058];
1059static PHASE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1060
1061fn bucket_of(n: usize) -> usize {
1062    if n <= 1 {
1063        0
1064    } else if n <= 5 {
1065        1
1066    } else if n <= 20 {
1067        2
1068    } else if n <= 100 {
1069        3
1070    } else {
1071        4
1072    }
1073}
1074
1075pub(crate) fn phase_hit_n(i: usize, n: usize, t: std::time::Instant) {
1076    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
1077        return;
1078    }
1079    let us = t.elapsed().as_micros() as u64;
1080    PHASE_MICROS[i].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
1081    PHASE_BUCKET_MICROS[i * 5 + bucket_of(n)].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
1082}
1083
1084pub(crate) fn phase_hit(i: usize, t: std::time::Instant) {
1085    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
1086        return;
1087    }
1088    PHASE_MICROS[i].fetch_add(
1089        t.elapsed().as_micros() as u64,
1090        std::sync::atomic::Ordering::Relaxed,
1091    );
1092}
1093
1094/// Enable phase timers (DDC_PHASES=1).
1095pub fn phases_enable() {
1096    PHASE_ON.store(true, std::sync::atomic::Ordering::Relaxed);
1097}
1098
1099/// (fixpoint, structure+convert, passes, print, total) in micros.
1100pub fn phases_dump() -> [u64; 5] {
1101    let mut out = [0u64; 5];
1102    for i in 0..5 {
1103        out[i] = PHASE_MICROS[i].load(std::sync::atomic::Ordering::Relaxed);
1104    }
1105    out
1106}
1107
1108/// Per-bucket phase micros: 5 phases × 5 buckets, row-major.
1109pub fn phases_bucket_dump() -> [[u64; 5]; 5] {
1110    let mut out = [[0u64; 5]; 5];
1111    for i in 0..5 {
1112        for b in 0..5 {
1113            out[i][b] = PHASE_BUCKET_MICROS[i * 5 + b].load(std::sync::atomic::Ordering::Relaxed);
1114        }
1115    }
1116    out
1117}
1118
1119static CAP_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1120static CAP_INSNS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1121
1122static BUILD_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1123static INSN_LIFTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1124
1125static BUCKET_COUNT: [std::sync::atomic::AtomicU64; 5] = [
1126    std::sync::atomic::AtomicU64::new(0),
1127    std::sync::atomic::AtomicU64::new(0),
1128    std::sync::atomic::AtomicU64::new(0),
1129    std::sync::atomic::AtomicU64::new(0),
1130    std::sync::atomic::AtomicU64::new(0),
1131];
1132static BUCKET_MICROS: [std::sync::atomic::AtomicU64; 5] = [
1133    std::sync::atomic::AtomicU64::new(0),
1134    std::sync::atomic::AtomicU64::new(0),
1135    std::sync::atomic::AtomicU64::new(0),
1136    std::sync::atomic::AtomicU64::new(0),
1137    std::sync::atomic::AtomicU64::new(0),
1138];
1139
1140/// Dump build/insn counters.
1141pub fn dump_builds() -> (u64, u64) {
1142    (
1143        BUILD_COUNT.load(std::sync::atomic::Ordering::Relaxed),
1144        INSN_LIFTED.load(std::sync::atomic::Ordering::Relaxed),
1145    )
1146}
1147
1148/// (cap-hit methods, sum of insns*1000+blocks for cap-hit methods).
1149pub fn dump_caps() -> (u64, u64) {
1150    (
1151        CAP_HITS.load(std::sync::atomic::Ordering::Relaxed),
1152        CAP_INSNS.load(std::sync::atomic::Ordering::Relaxed),
1153    )
1154}
1155
1156/// Dump DDC_BUCKETS statistics (global atomics).
1157pub fn dump_buckets() -> [(u64, u64); 5] {
1158    let mut out = [(0u64, 0u64); 5];
1159    for i in 0..5 {
1160        out[i] = (
1161            BUCKET_COUNT[i].load(std::sync::atomic::Ordering::Relaxed),
1162            BUCKET_MICROS[i].load(std::sync::atomic::Ordering::Relaxed),
1163        );
1164    }
1165    out
1166}
1167
1168/// Dominator-recompute counters from jdc-core (perf diagnostics).
1169pub fn dom_counters() -> (u64, u64) {
1170    (
1171        jdc_core::structure::DOM_CALLS.load(std::sync::atomic::Ordering::Relaxed),
1172        jdc_core::structure::DOM_BLOCKS.load(std::sync::atomic::Ordering::Relaxed),
1173    )
1174}
1175
1176/// Enable dominator-recompute counters (diagnostics; jdc-core gate).
1177pub fn dom_counters_enable() {
1178    jdc_core::structure::set_dom_counters(true);
1179}
1180
1181/// A minimal body carrying a diagnostic comment.
1182fn stub_body(msg: String, desc: MethodDescriptor) -> MethodBody {
1183    MethodBody {
1184        body: Stmt::Block(vec![Stmt::Comment(msg)]),
1185        vt: VarTable::default(),
1186        desc,
1187    }
1188}
1189
1190/// True when any phi belongs to merge block `bid`.
1191fn phis_for_merge(bid: usize, phis: &HashMap<(usize, u16), u32>) -> bool {
1192    phis.keys().any(|(b, _)| *b == bid)
1193}
1194
1195/// Phi materialization records for `bid`'s predecessors (pred-tagged).
1196fn record_appends(
1197    cfg: &DexCfg,
1198    bid: usize,
1199    out_states: &[Option<OutState>],
1200    phis: &HashMap<(usize, u16), u32>,
1201    vt: &jdc_core::var::VarTable,
1202    out: &mut Vec<(usize, u32, u32, Expr)>,
1203) {
1204    for p in cfg.blocks[bid].pred.clone() {
1205        let Some(o) = &out_states[p] else { continue };
1206        for (r, st) in o.regs.iter().enumerate() {
1207            if let Some(&phi) = phis.get(&(bid, r as u16)) {
1208                let value = match st {
1209                    Reg::Live(v) if *v == phi => continue,
1210                    Reg::Live(v) => Expr::Local {
1211                        var: *v,
1212                        ty: vt.var(*v).ty.clone(),
1213                    },
1214                    Reg::Pending(e) | Reg::PendingCall(e) => e.clone(),
1215                    Reg::Undef | Reg::WideHi => continue,
1216                };
1217                out.push((p, o.write_pc.get(r).copied().unwrap_or(0), phi, value));
1218            }
1219        }
1220    }
1221}
1222
1223#[allow(unused)]
1224fn record_bucket(n: usize, t0: std::time::Instant) {
1225    // (Perf: env::var is a lock+lookup — per-METHOD cost on 716k-method
1226    // runs; resolve once via OnceLock.)
1227    static BUCKETS_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1228    if !*BUCKETS_ON.get_or_init(|| std::env::var("DDC_BUCKETS").is_ok()) {
1229        return;
1230    }
1231    let bucket = if n <= 1 {
1232        0
1233    } else if n <= 5 {
1234        1
1235    } else if n <= 20 {
1236        2
1237    } else if n <= 100 {
1238        3
1239    } else {
1240        4
1241    };
1242    BUCKET_COUNT[bucket].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1243    BUCKET_MICROS[bucket].fetch_add(
1244        t0.elapsed().as_micros() as u64,
1245        std::sync::atomic::Ordering::Relaxed,
1246    );
1247}
1248
1249/// True when the expression references any of the phi vars.
1250fn visit_phi_refs(e: &Expr, phis: &std::collections::HashSet<u32>, hit: &mut bool) {
1251    if *hit {
1252        return;
1253    }
1254    if let Expr::Local { var, .. } = e {
1255        if phis.contains(var) {
1256            *hit = true;
1257        }
1258        return;
1259    }
1260    let mut kids: Vec<&Expr> = Vec::new();
1261    match e {
1262        Expr::Un { e, .. } | Expr::Cast { e, .. } | Expr::InstanceOf { e, .. } => kids.push(e),
1263        Expr::Bin { l, r, .. } => {
1264            kids.push(l);
1265            kids.push(r);
1266        }
1267        Expr::Cond { c, t, f } => {
1268            kids.push(c);
1269            kids.push(t);
1270            kids.push(f);
1271        }
1272        Expr::Assign { target, value, .. } => {
1273            kids.push(target);
1274            kids.push(value);
1275        }
1276        Expr::PreIncDec { e, .. } | Expr::PostIncDec { e, .. } => kids.push(e),
1277        Expr::Field { owner: Some(o), .. } => kids.push(o),
1278        Expr::Method {
1279            owner: Some(o),
1280            args,
1281            ..
1282        } => {
1283            kids.push(o);
1284            kids.extend(args.iter());
1285        }
1286        Expr::ArrayIndex { array, index } => {
1287            kids.push(array);
1288            kids.push(index);
1289        }
1290        Expr::New { args, .. } => kids.extend(args.iter()),
1291        Expr::NewArray { dims, init, .. } => {
1292            kids.extend(dims.iter());
1293            if let Some(v) = init {
1294                kids.extend(v.iter());
1295            }
1296        }
1297        Expr::NewMultiArray { dims, .. } => kids.extend(dims.iter()),
1298        _ => {}
1299    }
1300    for k in kids {
1301        visit_phi_refs(k, phis, hit);
1302        if *hit {
1303            return;
1304        }
1305    }
1306}
1307
1308/// Merge several predecessor register states: pass identical values
1309/// through, otherwise materialize into a phi var for `(block, register)`.
1310/// Debug-info name covering `(pc, slot)`, sanitized (shared by the
1311/// lifter and the merge path).
1312fn debug_name_at(
1313    locals: &[ddc_dex::DebugLocal],
1314    slot: u16,
1315    pc: u32,
1316    ty: &jdc_core::types::JavaType,
1317) -> Option<String> {
1318    if locals.is_empty() {
1319        return None;
1320    }
1321    let hit = locals.iter().find(|l| {
1322        l.reg == slot
1323            && pc >= l.start
1324            && pc < l.end
1325            && l.ty.as_deref().map(|d| &crate::desc_type(d) == ty).unwrap_or(true)
1326    })?;
1327    let n = crate::classdec::java_ident(&hit.name);
1328    if n.is_empty() {
1329        None
1330    } else {
1331        Some(n.into_owned())
1332    }
1333}
1334
1335fn merge_states(
1336    vt: &mut VarTable,
1337    phis: &mut HashMap<(usize, u16), u32>,
1338    bid: usize,
1339    sides: &[&[Reg]],
1340    debug_locals: &[ddc_dex::DebugLocal],
1341    merge_pc: u32,
1342) -> Vec<Reg> {
1343    let len = sides.iter().map(|s| s.len()).max().unwrap_or(0);
1344    let mut out = vec![Reg::Undef; len];
1345    for (r, slot) in out.iter_mut().enumerate() {
1346        let mut all_eq = true;
1347        let mut first: Option<&Reg> = None;
1348        for s in sides {
1349            let v = s.get(r);
1350            match (first, v) {
1351                (None, v) => first = v,
1352                (Some(f), Some(v)) if f == v => {}
1353                _ => all_eq = false,
1354            }
1355        }
1356        if all_eq {
1357            *slot = first.cloned().unwrap_or(Reg::Undef);
1358            continue;
1359        }
1360        // Diverged: phi var.
1361        let key = (bid, r as u16);
1362        let phi = match phis.get(&key) {
1363            Some(&v) => v,
1364            None => {
1365                let ty = join_side_types(vt, sides, r);
1366                // Loop-carried values are usually THE source local (the
1367                // `char[] out` / `int i` of a loop): name the phi from the
1368                // debug range covering the merge block's head. When a var
1369                // of that name+type already exists, REUSE it — per-block
1370                // copies of one source local degrade to out/out2/out3
1371                // suffix soup, and one register+type = one Java local is
1372                // exactly Dalvik semantics.
1373                if let Some(n) = debug_name_at(debug_locals, r as u16, merge_pc, &ty.erased()) {
1374                    let unified = vt
1375                        .vars
1376                        .iter()
1377                        .find(|v| {
1378                            v.slot == r as u16
1379                                && !v.synthetic_name
1380                                && v.name == n
1381                                && v.ty.erased() == ty.erased()
1382                        })
1383                        .map(|v| v.id);
1384                    let id = match unified {
1385                        Some(id) => id,
1386                        None => {
1387                            let id = vt.vars.len() as u32;
1388                            vt.vars.push(jdc_core::var::VarInfo {
1389                                id,
1390                                slot: r as u16,
1391                                name: n,
1392                                ty,
1393                                is_param: false,
1394                                range_start: 0,
1395                                range_end: u16::MAX,
1396                                synthetic_name: false,
1397                            });
1398                            while vt.by_slot.len() <= r {
1399                                vt.by_slot.push(Vec::new());
1400                            }
1401                            vt.by_slot[r].push((0, u16::MAX, id));
1402                            id
1403                        }
1404                    };
1405                    phis.insert(key, id);
1406                    id
1407                } else {
1408                    let id = vt.vars.len() as u32;
1409                    vt.vars.push(jdc_core::var::VarInfo {
1410                        id,
1411                        slot: r as u16,
1412                        name: format!("v{}", id),
1413                        ty,
1414                        is_param: false,
1415                        range_start: 0,
1416                        range_end: u16::MAX,
1417                        synthetic_name: true,
1418                    });
1419                    while vt.by_slot.len() <= r {
1420                        vt.by_slot.push(Vec::new());
1421                    }
1422                    vt.by_slot[r].push((0, u16::MAX, id));
1423                    phis.insert(key, id);
1424                    id
1425                }
1426            }
1427        };
1428        *slot = Reg::Live(phi);
1429    }
1430    out
1431}
1432
1433/// Type of a phi var: join of the non-null side values' erased types.
1434fn join_side_types(vt: &VarTable, sides: &[&[Reg]], r: usize) -> TypeRef {
1435    let mut ty: Option<JavaType> = None;
1436    for s in sides {
1437        let st = s.get(r).cloned().unwrap_or(Reg::Undef);
1438        let e = match st {
1439            Reg::Pending(e) | Reg::PendingCall(e) => e,
1440            Reg::Live(v) => Expr::Local {
1441                var: v,
1442                ty: vt.var(v).ty.clone(),
1443            },
1444            _ => continue,
1445        };
1446        let t = e.type_ref().erased();
1447        ty = Some(match ty {
1448            None => t,
1449            Some(prev) => join_types(&prev, &t),
1450        });
1451    }
1452    TypeRef::J(ty.unwrap_or(JavaType::Int))
1453}
1454
1455fn join_types(a: &JavaType, b: &JavaType) -> JavaType {
1456    if a == b {
1457        return a.clone();
1458    }
1459    let num = |t: &JavaType| {
1460        matches!(
1461            t,
1462            JavaType::Boolean
1463                | JavaType::Byte
1464                | JavaType::Char
1465                | JavaType::Short
1466                | JavaType::Int
1467                | JavaType::Long
1468                | JavaType::Float
1469                | JavaType::Double
1470        )
1471    };
1472    if num(a) && num(b) {
1473        // Numeric promotion.
1474        return match (a, b) {
1475            (JavaType::Double, _) | (_, JavaType::Double) => JavaType::Double,
1476            (JavaType::Float, _) | (_, JavaType::Float) => JavaType::Float,
1477            (JavaType::Long, _) | (_, JavaType::Long) => JavaType::Long,
1478            _ => JavaType::Int,
1479        };
1480    }
1481    if let (JavaType::Object(x), JavaType::Object(y)) = (a, b) {
1482        if x == y {
1483            return a.clone();
1484        }
1485        // Char/int ternaries join to int; otherwise objects join to Object.
1486        return JavaType::Object("java/lang/Object".into());
1487    }
1488    JavaType::Object("java/lang/Object".into())
1489}
1490
1491/// True when the block's terminator exits (used by callers to skip appends).
1492#[allow(dead_code)]
1493fn is_exit_term(term: &jdc_core::ir::build::Term) -> bool {
1494    matches!(
1495        term,
1496        jdc_core::ir::build::Term::Return(_) | jdc_core::ir::build::Term::Throw(_)
1497    )
1498}
1499
1500#[allow(dead_code)]
1501fn unused(_: &InsnKind) {}