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