Skip to main content

ddc_dec/
lift.rs

1//! Register-machine expression lifting: Dalvik instructions → jdc-core IR.
2//!
3//! The register file is modeled as per-register *views* of values:
4//! * `Live(v)` — the register equals local `v`, whose defining statement was
5//!   already emitted (SSA-ish: every materialization allocates a fresh var,
6//!   so a `Local` reference can never go stale);
7//! * `Pending(e)` — the register holds the expression `e`, whose store is
8//!   deferred so consumers can nest it (`return a + b`);
9//! * `PendingCall(e)` — the value of a just-executed invoke /
10//!   filled-new-array whose statement has not been emitted yet: consumed
11//!   exactly once (a materialization, a term, or a discarded-value
12//!   statement), never duplicated;
13//! * `WideHi` — the high half of a J/D pair.
14//!
15//! At block exit the terminator is built FIRST (terms may carry pending
16//! call expressions: `return foo();`), then unconsumed calls become
17//! statements and impure pendings materialize, so cross-block states only
18//! carry pure values, locals, and open `new`/`new-array` views.
19
20use ddc_dex::insn::{ArithOp, CmpKind, CmpOp, Insn, InsnKind, InvokeKind, Payload};
21use ddc_dex::{CodeItem, DexFile};
22use jdc_core::ir::build::{has_side_effects, BlockResult, SwitchTargets, Term};
23use jdc_core::ir::expr::{AssignOp, BinOp, ConcatPart, ConstVal, Expr, TypeRef, UnOp};
24use jdc_core::ir::stmt::Stmt;
25use jdc_core::types::{JavaType, MethodDescriptor};
26use jdc_core::var::{VarInfo, VarTable};
27
28use crate::DexPool;
29
30pub type BResult<T> = Result<T, String>;
31
32/// Cheap per-method feature flags accumulated by the lifter: which
33/// post-lift passes could possibly match anything. Most methods use none of
34/// these — gating their passes skips full-tree analysis walks.
35#[derive(Clone, Copy, Default, PartialEq)]
36pub struct MethodFlags(u8);
37
38impl MethodFlags {
39    const SB: u8 = 1;
40    const MONITOR: u8 = 2;
41    const CMP: u8 = 4;
42    pub fn none() -> MethodFlags {
43        MethodFlags(0)
44    }
45    pub fn with_sb(self) -> MethodFlags {
46        MethodFlags(self.0 | Self::SB)
47    }
48    pub fn with_monitor(self) -> MethodFlags {
49        MethodFlags(self.0 | Self::MONITOR)
50    }
51    pub fn with_cmp(self) -> MethodFlags {
52        MethodFlags(self.0 | Self::CMP)
53    }
54    pub fn has_sb(self) -> bool {
55        self.0 & Self::SB != 0
56    }
57    pub fn has_monitor(self) -> bool {
58        self.0 & Self::MONITOR != 0
59    }
60    pub fn has_cmp(self) -> bool {
61        self.0 & Self::CMP != 0
62    }
63    pub fn merge(self, o: MethodFlags) -> MethodFlags {
64        MethodFlags(self.0 | o.0)
65    }
66}
67
68/// Everything one method body needs from its DEX image.
69pub struct MethodEnv<'a> {
70    pub pool: &'a DexPool,
71    /// Image index of `dex` in the pool (keys the pool's ref caches).
72    pub di: usize,
73    pub dex: &'a DexFile,
74    pub code: &'a CodeItem,
75    pub class_name: String,
76    pub method_name: std::sync::Arc<str>,
77    pub desc: MethodDescriptor,
78    /// Debug-info local table (empty for release/stripped builds):
79    /// real source names per (register, pc-range).
80    pub debug_locals: Vec<ddc_dex::DebugLocal>,
81    pub is_static: bool,
82    /// Total code units — the CFG owns the insns stream, so the lifter reads
83    /// the extent from here instead of `code.insns` (hollowed after the
84    /// CFG build moved it).
85    pub code_units: u32,
86}
87
88impl<'a> MethodEnv<'a> {
89    pub fn type_name(&self, idx: u32) -> String {
90        self.dex.type_name(idx).to_string()
91    }
92    pub fn java_type(&self, idx: u32) -> JavaType {
93        // Shared per-image parse (was desc-reparse per instruction).
94        (*self.pool.type_java(self.di, idx)).clone()
95    }
96    pub fn type_name_arc(&self, idx: u32) -> std::sync::Arc<str> {
97        self.pool.type_name_arc(self.di, idx)
98    }
99    pub fn field_ref(
100        &self,
101        idx: u32,
102    ) -> (
103        std::sync::Arc<str>,
104        std::sync::Arc<str>,
105        JavaType,
106    ) {
107        let f = self.dex.field(idx);
108        let owner = std::sync::Arc::from(self.dex.class_name(f.class_idx).as_str());
109        let raw = self.dex.string(f.name_idx);
110        // Colliding obfuscated field names (synthetic outer ref renamed
111        // to a one-char name beside a real field) resolve differently per
112        // site in source — run the shared rename registry so every
113        // reference prints the same display name as the declaration.
114        let name = if jdc_core::rename::owner_has_renames(&owner) {
115            jdc_core::rename::field_display(&owner, raw, self.dex.type_name(f.type_idx))
116                .map(std::sync::Arc::from)
117                .unwrap_or_else(|| std::sync::Arc::from(raw))
118        } else {
119            std::sync::Arc::from(raw)
120        };
121        (owner, name, self.java_type(f.type_idx))
122    }
123    pub fn method_ref(
124        &self,
125        idx: u32,
126    ) -> (
127        std::sync::Arc<str>,
128        std::sync::Arc<str>,
129        std::sync::Arc<MethodDescriptor>,
130    ) {
131        // Was: N param Strings + format! + descriptor RE-PARSE per invoke
132        // (6-10 allocations per call instruction). All three components
133        // are shared table entries now — refcount bumps.
134        let m = self.dex.method(idx);
135        let owner = std::sync::Arc::from(self.dex.class_name(m.class_idx).as_str());
136        let desc = self.pool.proto_desc_parsed(self.di, m.proto_idx);
137        // Sanitizer-collapsed method names (whole `ERROR_中文` families on
138        // weibo render one `ERROR________`) need the shared member-rename
139        // registry so declarations and call sites agree. Cold path only:
140        // clean corpora never rebuild the descriptor string.
141        let name = if jdc_core::rename::owner_has_renames(&owner) {
142            let raw = self.dex.string(m.name_idx);
143            jdc_core::rename::field_display(&owner, raw, &desc.to_string())
144                .map(std::sync::Arc::from)
145                .unwrap_or_else(|| std::sync::Arc::from(raw))
146        } else {
147            std::sync::Arc::from(self.dex.string(m.name_idx))
148        };
149        (owner, name, desc)
150    }
151}
152
153/// Per-register value view (see module docs).
154#[derive(Debug, Clone, PartialEq)]
155pub enum Reg {
156    Undef,
157    Live(u32),
158    Pending(Expr),
159    PendingCall(Expr),
160    WideHi,
161}
162
163/// Block-exit register state (machine-neutral view plus origin tracking).
164#[derive(Debug, Clone)]
165pub struct OutState {
166    pub regs: Vec<Reg>,
167    /// Per register: the pc of the instruction that produced its value
168    /// (orders merge materializations by original instruction order).
169    pub write_pc: Vec<u32>,
170}
171
172/// The registers an instruction READS as operands (receivers, arguments,
173/// move sources — destination registers excluded). Drives the block
174/// lookahead that decides when an allocation view must materialize.
175fn src_regs(kind: &InsnKind) -> Vec<u16> {
176    let mut out: Vec<u16> = Vec::with_capacity(4);
177    let mut push = |r: u16| out.push(r);
178    match kind {
179        InsnKind::Nop
180        | InsnKind::ReturnVoid
181        | InsnKind::Unknown
182        | InsnKind::NewInstance { .. }
183        | InsnKind::SGet { .. } => {}
184        InsnKind::Move { src, .. }
185        | InsnKind::Un { src, .. }
186        | InsnKind::Return { src }
187        | InsnKind::ArrayLength { src, .. } => push(*src),
188        InsnKind::MonitorEnter { reg }
189        | InsnKind::MonitorExit { reg }
190        | InsnKind::Throw { reg }
191        | InsnKind::CheckCast { reg, .. }
192        | InsnKind::FillArrayData { reg, .. }
193        | InsnKind::PackedSwitch { reg, .. }
194        | InsnKind::SparseSwitch { reg, .. } => push(*reg),
195        InsnKind::MoveResult { .. } | InsnKind::MoveException { .. } => {}
196        InsnKind::Const { .. }
197        | InsnKind::ConstClass { .. }
198        | InsnKind::ConstString { .. }
199        | InsnKind::ConstMethodHandle { .. }
200        | InsnKind::ConstMethodType { .. } => {}
201        InsnKind::InstanceOf { src, .. } => {
202            push(*src);
203        }
204        InsnKind::NewArray { size, .. } => {
205            push(*size);
206        }
207        InsnKind::FilledNewArray { regs, .. } | InsnKind::InvokeCustom { regs, .. } => {
208            for r in regs {
209                push(*r);
210            }
211        }
212        InsnKind::Goto { .. } => {}
213        InsnKind::Cmp { a, b, .. } | InsnKind::Bin { a, b, .. } => {
214            push(*a);
215            push(*b);
216        }
217        InsnKind::BinLit { a, .. } => push(*a),
218        InsnKind::If { a, b, z, .. } => {
219            push(*a);
220            if !*z {
221                push(*b);
222            }
223        }
224        InsnKind::AGet { array, index, .. } => {
225            push(*array);
226            push(*index);
227        }
228        InsnKind::APut {
229            value,
230            array,
231            index,
232            ..
233        } => {
234            push(*value);
235            push(*array);
236            push(*index);
237        }
238        InsnKind::IGet { obj, .. } => {
239            push(*obj);
240        }
241        InsnKind::IPut { value, obj, .. } => {
242            push(*value);
243            push(*obj);
244        }
245        InsnKind::SPut { value, .. } => {
246            push(*value);
247        }
248        InsnKind::Invoke { regs, .. } => {
249            for r in regs {
250                push(*r);
251            }
252        }
253    }
254    out
255}
256
257/// Registers an instruction READS as operands.
258/// Registers an instruction DEFINES (new value generations).
259fn dst_regs(kind: &InsnKind) -> Vec<u16> {
260    let mut out: Vec<u16> = Vec::with_capacity(2);
261    let mut push = |r: u16| out.push(r);
262    match kind {
263        InsnKind::Move { dst, .. }
264        | InsnKind::MoveResult { dst }
265        | InsnKind::MoveException { dst }
266        | InsnKind::Const { dst, .. }
267        | InsnKind::ConstClass { dst, .. }
268        | InsnKind::ConstString { dst, .. }
269        | InsnKind::ConstMethodHandle { dst, .. }
270        | InsnKind::ConstMethodType { dst, .. }
271        | InsnKind::NewInstance { dst, .. }
272        | InsnKind::NewArray { dst, .. }
273        | InsnKind::InstanceOf { dst, .. }
274        | InsnKind::ArrayLength { dst, .. }
275        | InsnKind::Cmp { dst, .. }
276        | InsnKind::AGet { dst, .. }
277        | InsnKind::IGet { dst, .. }
278        | InsnKind::SGet { dst, .. }
279        | InsnKind::Un { dst, .. }
280        | InsnKind::Bin { dst, .. }
281        | InsnKind::BinLit { dst, .. } => push(*dst),
282        _ => {}
283    }
284    out
285}
286
287/// The (pc, reg) reads that are the final read of the register's current
288/// generation: walking the register's events in pc order, a read is
289/// final when no other read of the same register precedes its next WRITE
290/// (a write starts a new generation — the old value is dead there).
291pub(crate) fn compute_final_reads(
292    ins: &[Insn],
293) -> std::sync::Arc<jdc_core::FxHashSet<(u32, u16)>> {
294    use jdc_core::FxHashMap as HashMap;
295    // reg → (pc, is_read) events, pc order (ins is already pc-sorted).
296    let mut events: HashMap<u16, Vec<(u32, bool)>> = HashMap::default();
297    for i in ins {
298        for r in src_regs(&i.kind) {
299            events.entry(r).or_default().push((i.pc, true));
300        }
301        for r in dst_regs(&i.kind) {
302            events.entry(r).or_default().push((i.pc, false));
303        }
304    }
305    let mut out = jdc_core::FxHashSet::default();
306    for (reg, evs) in events {
307        let mut dedup: Vec<(u32, bool)> = Vec::with_capacity(evs.len());
308        for (pc, is_read) in evs {
309            if dedup.last() != Some(&(pc, is_read)) {
310                dedup.push((pc, is_read));
311            }
312        }
313        for (i, &(pc, is_read)) in dedup.iter().enumerate() {
314            if !is_read {
315                continue;
316            }
317            // Final read of the current generation: no other read before
318            // the register's next write.
319            let mut final_ = true;
320            if let Some(&(_, is_read2)) = dedup.get(i + 1) {
321                if is_read2 {
322                    final_ = false;
323                }
324            }
325            if final_ {
326                out.insert((pc, reg));
327            }
328        }
329    }
330    std::sync::Arc::new(out)
331}
332
333pub struct Lifter<'a> {
334    pub env: &'a MethodEnv<'a>,
335    pub vt: &'a mut VarTable,
336    /// Owning block id (stable-var registry key).
337    block_id: usize,
338    /// (block, register) → var id, shared across REBUILDS: a re-lift of
339    /// the same block with the same input reuses the same materialized
340    /// variables, so the output state is id-stable. Without this, every
341    /// rebuild allocated fresh ids, the out-state compared unequal, and
342    /// the worklist cascaded re-queuing until the visit cap (~60
343    /// rebuilds per block, 30M lifts on weibo).
344    stable: &'a mut jdc_core::FxHashMap<(usize, u16, u64), u32>,
345    regs: Vec<Reg>,
346    write_pc: Vec<u32>,
347    stmts: Vec<Stmt>,
348    pending_call: Option<Expr>,
349    code_units: u32,
350    /// Current instruction's pc (drives the allocation materialization
351    /// lookahead below).
352    cur_pc: u32,
353    /// (pc, register) reads that are the FINAL read of the register's
354    /// current value generation: no other read before the register's
355    /// next write. An allocation view (post-fold `New` / `NewArray`)
356    /// may only be inlined at a final read; a register reused for a
357    /// call result and read again (greet → move-result v0 → println(v0))
358    /// is a new generation, not another use of the allocation.
359    final_read: std::sync::Arc<jdc_core::FxHashSet<(u32, u16)>>,
360    /// Method-level feature flags, merged in place as features are seen
361    /// (build_block consumes the lifter, so the flags must escape via a
362    /// shared reference rather than a field read afterwards).
363    mflags: &'a mut MethodFlags,
364}
365
366impl<'a> Lifter<'a> {
367    pub fn new(
368        env: &'a MethodEnv<'a>,
369        vt: &'a mut VarTable,
370        in_regs: Vec<Reg>,
371        block_id: usize,
372        stable: &'a mut jdc_core::FxHashMap<(usize, u16, u64), u32>,
373        mflags: &'a mut MethodFlags,
374    ) -> Lifter<'a> {
375        let n = env.code.registers_size as usize;
376        let n = n.max(in_regs.len()).max(1);
377        let mut regs = in_regs;
378        regs.resize(n, Reg::Undef);
379        Lifter {
380            env,
381            vt,
382            regs,
383            write_pc: vec![0; n],
384            stmts: Vec::new(),
385            block_id,
386            stable,
387            pending_call: None,
388            code_units: env.code_units,
389            cur_pc: 0,
390            final_read: std::sync::Arc::new(jdc_core::FxHashSet::default()),
391            mflags,
392        }
393    }
394
395    // -- variable creation ---------------------------------------------------
396
397    /// Cheap 64-bit type fingerprint for the stable-var key: hashing the
398    /// JavaType itself (string bytes + tuple) ran on EVERY register
399    /// materialization; the fingerprint is one pass with no clones
400    /// (`erased()` deep-clones Array chains). G is unreachable in DEX
401    /// lift (no generic signatures) — a coarse tag suffices.
402    fn ty_key(ty: &TypeRef) -> u64 {
403        use std::hash::{Hash, Hasher};
404        fn jt_key(j: &JavaType, h: &mut jdc_core::fx::FxHasher) {
405            match j {
406                JavaType::Void => 1u64.hash(h),
407                JavaType::Boolean => 2u64.hash(h),
408                JavaType::Byte => 3u64.hash(h),
409                JavaType::Char => 4u64.hash(h),
410                JavaType::Short => 5u64.hash(h),
411                JavaType::Int => 6u64.hash(h),
412                JavaType::Float => 7u64.hash(h),
413                JavaType::Long => 8u64.hash(h),
414                JavaType::Double => 9u64.hash(h),
415                JavaType::Object(n) => {
416                    10u64.hash(h);
417                    n.hash(h);
418                }
419                JavaType::Array(inner) => {
420                    11u64.hash(h);
421                    jt_key(inner, h);
422                }
423            }
424        }
425        let mut h = jdc_core::fx::FxHasher::default();
426        match ty {
427            TypeRef::J(j) => jt_key(j, &mut h),
428            TypeRef::G(_) => 99u64.hash(&mut h),
429        }
430        h.finish()
431    }
432
433    fn fresh_var(&mut self, slot: u16, ty: TypeRef) -> u32 {
434        // Keyed by TYPE as well as (block, slot): d8 reuses one register
435        // for values of different types (`v1: byte[]` then `v1: String`
436        // in the same method — the lab package's Main.run). A Java local
437        // cannot change type — the old (block, slot) key reused one var
438        // and then RETYPED it in place, emitting `byte[] v1 = …; v1 =
439        // Obf.s(v1, 90);` (String into byte[]) and kin all over the
440        // corpus. Distinct types mint distinct vars; rebuild stability
441        // (the worklist-convergence fix) holds because the key is a pure
442        // function of the instruction stream.
443        let key = (self.block_id, slot, Self::ty_key(&ty));
444        if let Some(&id) = self.stable.get(&key) {
445            return id;
446        }
447        // Real source name from the debug-info local table when a range
448        // covers (pc, slot); otherwise the synthetic `vN`. apply_local_
449        // names never renames non-synthetic vars and de-duplicates the
450        // (legal-in-source, illegal-in-flat-Java) same-name scopes.
451        if let Some(name) = self.debug_name(slot, &ty) {
452            // Unify same register+type+name vars across blocks: the debug
453            // table says they are ONE source local, and per-block copies
454            // degrade to `out`/`out2`/`out3` suffix soup after de-dup.
455            // Dalvik registers are method-scoped, so one Java local shared
456            // by every write site is exactly register semantics.
457            let tkey = Self::ty_key(&ty);
458            if let Some(id) = self
459                .vt
460                .vars
461                .iter()
462                .find(|v| {
463                    v.slot == slot
464                        && !v.synthetic_name
465                        && v.name == name
466                        && Self::ty_key(&v.ty) == tkey
467                })
468                .map(|v| v.id)
469            {
470                self.stable.insert(key, id);
471                return id;
472            }
473            let id = self.vt.vars.len() as u32;
474            self.stable.insert(key, id);
475            self.push_var(id, slot, name, ty, false);
476            return id;
477        }
478        let id = self.vt.vars.len() as u32;
479        let name = format!("v{}", id);
480        self.stable.insert(key, id);
481        self.push_var(id, slot, name, ty, true);
482        id
483    }
484
485    fn push_var(&mut self, id: u32, slot: u16, name: String, ty: TypeRef, synthetic: bool) {
486        self.vt.vars.push(VarInfo {
487            id,
488            slot,
489            name,
490            ty,
491            is_param: false,
492            range_start: 0,
493            range_end: u16::MAX,
494            synthetic_name: synthetic,
495        });
496        while self.vt.by_slot.len() <= slot as usize {
497            self.vt.by_slot.push(Vec::new());
498        }
499        self.vt.by_slot[slot as usize].push((0, u16::MAX, id));
500    }
501
502    /// The source-level name covering `(cur_pc, slot)` in the debug
503    /// local table, sanitized into a legal Java identifier. Linear scan:
504    /// the table is empty in release APKs (early-out) and small in
505    /// debug builds.
506    fn debug_name(&self, slot: u16, ty: &TypeRef) -> Option<String> {
507        let locals = &self.env.debug_locals;
508        if locals.is_empty() {
509            return None;
510        }
511        let want = ty.erased();
512        let covers = |pc: u32| {
513            locals.iter().find(|l| {
514                l.reg == slot
515                    && pc >= l.start
516                    && pc < l.end
517                    // Type gate: register reuse mints vars of a DIFFERENT
518                    // type inside the same range (`new-array v0, v0` reads
519                    // the old v0 as an int size inside the new v0's [C
520                    // range) — naming that junk var stole the real name.
521                    && l.ty.as_deref().map(|d| crate::desc_type(d) == want).unwrap_or(true)
522            })
523        };
524        // Materializations at block merges run BEFORE any instruction of
525        // the block (cur_pc is stale/zero) — fall back to the pc where
526        // the register's current value was BORN (write_pc), which is
527        // what the debug range actually describes.
528        let hit = covers(self.cur_pc).or_else(|| {
529            let wpc = *self.write_pc.get(slot as usize)?;
530            if wpc == 0 {
531                None
532            } else {
533                covers(wpc)
534            }
535        })?;
536        let name = crate::classdec::java_ident(&hit.name);
537        if name.is_empty() {
538            return None;
539        }
540        Some(name.into_owned())
541    }
542
543    fn local_expr(&self, v: u32) -> Expr {
544        Expr::Local {
545            var: v,
546            ty: self.vt.var(v).ty.clone(),
547        }
548    }
549
550    /// Registers still holding a move-object alias of the folded
551    /// construction in `r`. The ctor fold writes one `new C(args)` view
552    /// into every copy of the allocation (keyed by the origin write_pc
553    /// the Move handler propagates from the new-instance site): one
554    /// copy being consumed or materialized must retire the whole set —
555    /// a surviving copy would re-emit the construction.
556    fn folded_new_aliases(&self, r: u16) -> Vec<usize> {
557        let Some(w) = self.write_pc.get(r as usize).copied() else {
558            return Vec::new();
559        };
560        (0..self.regs.len())
561            .filter(|&rr| {
562                rr != r as usize
563                    && self.write_pc.get(rr).copied() == Some(w)
564                    && matches!(self.regs[rr], Reg::Pending(Expr::New { raw: false, .. }))
565            })
566            .collect()
567    }
568
569    // -- register access -----------------------------------------------------
570
571    /// Read for nesting into another expression (clones the value).
572    #[track_caller]
573    fn read_nest(&mut self, r: u16) -> Expr {
574        match self.regs.get(r as usize).cloned().unwrap_or(Reg::Undef) {
575            Reg::Undef | Reg::WideHi => {
576                // Reading a register never written on this path (or beyond
577                // the frame): a fresh (never-assigned) local keeps the
578                // output compilable.
579                let ty = TypeRef::J(JavaType::Int);
580                let v = self.fresh_var(r, ty);
581                if (r as usize) < self.regs.len() {
582                    self.regs[r as usize] = Reg::Live(v);
583                }
584                self.local_expr(v)
585            }
586            Reg::Live(v) => self.local_expr(v),
587            Reg::Pending(e) => {
588                // An allocation view (`NewArray`, or a post-fold `New`)
589                // may be emitted inline only when THIS read is the
590                // register's final one: any later read would re-emission
591                // a FRESH allocation (`sput v0, sparse; aput v2, v0, v1`
592                // printed three distinct `new byte[4]`; a discarded-
593                // result StringBuilder chain printed one `new
594                // StringBuilder()` per append). Materialize when a later
595                // read exists; inline the last use, keeping
596                // `foo(new Bar())` nesting. `New { raw: true }` is
597                // always exempt: the constructor fold consumes the raw
598                // view at the invoke-direct site.
599                //
600                // A folded construction ALIASED into a second register
601                // (move-object) counts as a later read too — one `new
602                // C(args)` cannot be inlined at one alias and survive as
603                // a pending copy on the other. Materialize so both
604                // aliases share the single construction var.
605                let alias_needs_share = matches!(&e, Expr::New { raw: false, .. })
606                    && self.folded_new_aliases(r).iter().any(|&rr| {
607                        self.final_read
608                            .iter()
609                            .any(|&(pc2, r2)| r2 == rr as u16 && pc2 >= self.cur_pc)
610                    });
611                let alloc = alias_needs_share
612                    || matches!(&e, Expr::NewArray { .. })
613                    || (matches!(&e, Expr::New { raw: false, .. })
614                        && !self.final_read.contains(&(self.cur_pc, r)));
615                if alloc {
616                    let v = self.materialize(r);
617                    self.local_expr(v)
618                } else {
619                    // Inline AND consume: this is the register's final
620                    // read in the block, yet leaving the Pending view in
621                    // place made the block-exit materialization emit the
622                    // SAME allocation a second time (`this.last = new
623                    // Report(..); new Report(..);` — a duplicated
624                    // observable side effect; lab package Guard.report).
625                    // `New { raw: true }` is EXEMPT: the ctor fold reads
626                    // the raw view at the invoke-direct site and must
627                    // still find it (consuming it there broke every
628                    // constructor fold).
629                    if matches!(&e, Expr::NewArray { .. })
630                        || matches!(&e, Expr::New { raw: false, .. })
631                    {
632                        let aliases = if matches!(&e, Expr::New { raw: false, .. }) {
633                            self.folded_new_aliases(r)
634                        } else {
635                            Vec::new()
636                        };
637                        if let Some(slot) = self.regs.get_mut(r as usize) {
638                            *slot = Reg::Undef;
639                        }
640                        // Consuming the last use retires the aliased
641                        // copies too (none of them is read again — the
642                        // share branch above materialized otherwise).
643                        for rr in aliases {
644                            self.regs[rr] = Reg::Undef;
645                        }
646                    }
647                    e
648                }
649            }
650            Reg::PendingCall(_) => {
651                let v = self.materialize(r);
652                self.local_expr(v)
653            }
654        }
655    }
656
657    /// Read for a context that evaluates exactly once (term payloads): the
658    /// value is consumed, not cloned — otherwise the block-exit
659    /// materialization would emit it a second time.
660    fn read_term(&mut self, r: u16) -> Expr {
661        match self.regs.get(r as usize).cloned().unwrap_or(Reg::Undef) {
662            Reg::PendingCall(e) | Reg::Pending(e) => {
663                // Terms terminate the block: no later read can follow, so a
664                // folded construction consumed here retires its aliased
665                // copies as well.
666                let aliases = if matches!(&e, Expr::New { raw: false, .. }) {
667                    self.folded_new_aliases(r)
668                } else {
669                    Vec::new()
670                };
671                if (r as usize) < self.regs.len() {
672                    self.regs[r as usize] = Reg::Undef;
673                }
674                for rr in aliases {
675                    self.regs[rr] = Reg::Undef;
676                }
677                self.pending_call = None;
678                e
679            }
680            _ => self.read_nest(r),
681        }
682    }
683
684    fn write(&mut self, r: u16, e: Expr, pc: u32, wide: bool) {
685        if r as usize >= self.regs.len() {
686            return;
687        }
688        self.write_pc[r as usize] = pc;
689        // Loop-carried Pending trees grow multiplicatively across fixpoint
690        // rounds (merge clones the whole tree per side per visit); past
691        // this size the register materializes, which caps every state at
692        // a bounded expression over stable locals.
693        if expr_size(&e) > 32 {
694            self.write_pc[r as usize] = pc;
695            let v = self.materialize_value(r, e);
696            if (r as usize) < self.regs.len() {
697                self.regs[r as usize] = Reg::Live(v);
698            }
699            if wide {
700                self.mark_wide_hi(r + 1, pc);
701            }
702            return;
703        }
704        self.regs[r as usize] = Reg::Pending(e);
705        if wide {
706            self.mark_wide_hi(r + 1, pc);
707        }
708    }
709
710    /// Materialize WITHOUT consuming the register slot's caller contract:
711    /// emit `v = e` and return the var id (used by the size cap).
712    fn materialize_value(&mut self, r: u16, e: Expr) -> u32 {
713        let e = value_of_cmp(&e);
714        let ty = e.type_ref();
715        // fresh_var is type-keyed: a retyped register gets a FRESH var,
716        // so no in-place retyping here (each var keeps its mint type and
717        // its LocalDef label always matches its init).
718        let v = self.fresh_var(r, ty);
719        self.stmts.push(Stmt::LocalDef {
720            var: v,
721            init: Some(e),
722            is_final: false,
723            force_type: true,
724        });
725        v
726    }
727
728    /// Write a value whose evaluation already happened (invoke /
729    /// filled-new-array results): consumed exactly once.
730    fn write_call_result(&mut self, r: u16, e: Expr, pc: u32) {
731        if r as usize >= self.regs.len() {
732            return;
733        }
734        self.write_pc[r as usize] = pc;
735        self.regs[r as usize] = Reg::PendingCall(e);
736    }
737
738    fn mark_wide_hi(&mut self, r: u16, pc: u32) {
739        if (r as usize) < self.regs.len() {
740            self.regs[r as usize] = Reg::WideHi;
741            self.write_pc[r as usize] = pc;
742        }
743    }
744
745    /// Emit `v = expr` and mark the register `Live(v)`.
746    fn materialize(&mut self, r: u16) -> u32 {
747        let cur = self.regs.get(r as usize).cloned().unwrap_or(Reg::Undef);
748        let e = match cur {
749            Reg::Pending(e) | Reg::PendingCall(e) => e,
750            Reg::Live(v) => return v,
751            // Undef (a value flowing in from an unanalyzed path): a fresh
752            // local, NOT Const 0 — `0.new a()` was not even valid Java.
753            _ => {
754                let v = self.fresh_var(r, TypeRef::J(JavaType::Object("java/lang/Object".into())));
755                self.stmts.push(Stmt::LocalDef {
756                    var: v,
757                    init: None,
758                    is_final: false,
759                    force_type: false,
760                });
761                if (r as usize) < self.regs.len() {
762                    self.regs[r as usize] = Reg::Live(v);
763                }
764                return v;
765            }
766        };
767        // cmp sentinels stored as values become library compare calls.
768        let e = value_of_cmp(&e);
769        let ty = e.type_ref();
770        // fresh_var is type-keyed: a retyped register gets a FRESH var,
771        // so no in-place retyping here (each var keeps its mint type and
772        // its LocalDef label always matches its init).
773        let v = self.fresh_var(r, ty);
774        self.stmts.push(Stmt::LocalDef {
775            var: v,
776            init: Some(e),
777            is_final: false,
778            force_type: true,
779        });
780        if (r as usize) < self.regs.len() {
781            self.regs[r as usize] = Reg::Live(v);
782        }
783        // A folded construction materialized from ONE alias binds every
784        // alias to the same var — the copies would otherwise re-emit the
785        // construction at their own read (or orphan at block exit).
786        for rr in self.folded_new_aliases(r) {
787            self.regs[rr] = Reg::Live(v);
788        }
789        v
790    }
791
792    /// Discard an unconsumed call result (invoke without move-result).
793    fn drop_pending_call(&mut self) {
794        if let Some(e) = self.pending_call.take() {
795            let e = value_of_cmp(&e);
796            if has_side_effects(&e) {
797                self.stmts.push(Stmt::ExprStmt(e));
798            }
799        }
800    }
801
802    // -- helpers -------------------------------------------------------------
803
804    fn owner_expr(&self, obj: Expr, cls: &str) -> Option<Box<Expr>> {
805        if cls == self.env.class_name && matches!(obj, Expr::This) {
806            return None;
807        }
808        Some(Box::new(obj))
809    }
810
811    fn arith_op(op: ArithOp) -> BinOp {
812        match op {
813            ArithOp::Add => BinOp::Add,
814            ArithOp::Sub => BinOp::Sub,
815            ArithOp::Mul => BinOp::Mul,
816            ArithOp::Div => BinOp::Div,
817            ArithOp::Rem => BinOp::Rem,
818            ArithOp::And => BinOp::And,
819            ArithOp::Or => BinOp::Or,
820            ArithOp::Xor => BinOp::Xor,
821            ArithOp::Shl => BinOp::Shl,
822            ArithOp::Shr => BinOp::Shr,
823            ArithOp::Ushr => BinOp::Ushr,
824        }
825    }
826
827    fn cmp_op(op: CmpOp) -> BinOp {
828        match op {
829            CmpOp::Eq => BinOp::Eq,
830            CmpOp::Ne => BinOp::Ne,
831            CmpOp::Lt => BinOp::Lt,
832            CmpOp::Ge => BinOp::Ge,
833            CmpOp::Gt => BinOp::Gt,
834            CmpOp::Le => BinOp::Le,
835        }
836    }
837
838    fn cmp_sentinel(kind: CmpKind, l: Expr, r: Expr) -> Expr {
839        let name = match kind {
840            CmpKind::CmplF => "\0cmpl-float",
841            CmpKind::CmpgF => "\0cmpg-float",
842            CmpKind::CmplD => "\0cmpl-double",
843            CmpKind::CmpgD => "\0cmpg-double",
844            CmpKind::CmpJ => "\0cmp-long",
845        };
846        Expr::Invokedynamic {
847            name: name.into(),
848            desc: MethodDescriptor {
849                args: vec![],
850                ret: JavaType::Int,
851            },
852            args: vec![l, r],
853            bsm_text: String::new(),
854            bsm_static_args: vec![],
855        }
856    }
857
858    // -- the main loop ---------------------------------------------------------
859
860    /// Lift one block. `handler_types` gives catch types for ranges this
861    /// block handles (for move-exception typing).
862    pub fn build_block(
863        mut self,
864        ins: &[Insn],
865        handler_types: &[Option<std::sync::Arc<str>>],
866        final_read: std::sync::Arc<jdc_core::FxHashSet<(u32, u16)>>,
867    ) -> BResult<(BlockResult, OutState)> {
868        let payloads = &self.env.code.payloads;
869        // METHOD-wide final-read set (computed once by the caller over
870        // the full instruction stream). The block-scoped computation
871        // this replaced marked a block's LAST read of a register as
872        // final even when LATER BLOCKS read the same generation: the
873        // alloc inlined-and-consumed at the block tail, and the
874        // downstream reads minted fresh never-assigned int locals
875        // (`new c(..).e = new HashMap();` + `v28.e` with `int v28` —
876        // weixin tf5/e, the dominant 无法取消引用int shape once the
877        // obscuring cascades stopped suppressing it).
878        self.final_read = final_read;
879        for ins in ins {
880            self.cur_pc = ins.pc;
881            match &ins.kind {
882                InsnKind::Nop => {}
883                InsnKind::Unknown => {
884                    return Err(format!(
885                        "unsupported opcode {:#04x} ({}) at pc {}",
886                        ins.op,
887                        ddc_dex::insn::op_name(ins.op),
888                        ins.pc
889                    ));
890                }
891                InsnKind::Move { dst, src } => {
892                    // Impure / call values are consumed once: materialize the
893                    // source so both registers share one evaluation. A raw
894                    // `new-instance` view is exempt (as at block exit): the
895                    // ctor fold consumes it at the invoke-direct site, and
896                    // the invoke-range receiver shuffle (`new-instance v0;
897                    // move-object v5, v0; invoke/range {v5..}`) must keep it
898                    // pending — materializing here emitted an empty `new C()`
899                    // while the real construction orphaned at the receiver
900                    // (Kotlin default-arg ctors: every enum constant got an
901                    // empty shell).
902                    let src_state = self.regs.get(*src as usize).cloned().unwrap_or(Reg::Undef);
903                    if matches!(src_state, Reg::PendingCall(_))
904                        || matches!(&src_state, Reg::Pending(e)
905                            if has_side_effects(e) && !matches!(e, Expr::New { raw: true, .. }))
906                    {
907                        self.materialize(*src);
908                    }
909                    let st = self.regs.get(*src as usize).cloned().unwrap_or(Reg::Undef);
910                    let wide = reg_is_wide(&st, self.vt);
911                    if (*dst as usize) < self.regs.len() {
912                        self.regs[*dst as usize] = st;
913                        self.write_pc[*dst as usize] =
914                            self.write_pc.get(*src as usize).copied().unwrap_or(0);
915                    }
916                    if wide {
917                        self.mark_wide_hi(*dst + 1, ins.pc);
918                    }
919                }
920                InsnKind::MoveResult { dst } => {
921                    if let Some(e) = self.pending_call.take() {
922                        let wide =
923                            matches!(e.type_ref().erased(), JavaType::Long | JavaType::Double);
924                        self.write_call_result(*dst, e, ins.pc);
925                        if wide {
926                            self.mark_wide_hi(*dst + 1, ins.pc);
927                        }
928                    } else {
929                        // move-result without a pending call: fresh var.
930                        let v = self.fresh_var(*dst, TypeRef::J(JavaType::Int));
931                        if (*dst as usize) < self.regs.len() {
932                            self.regs[*dst as usize] = Reg::Live(v);
933                        }
934                    }
935                }
936                InsnKind::MoveException { dst } => {
937                    let ty = handler_types
938                        .iter()
939                        .flatten()
940                        .next()
941                        .map(|t| TypeRef::J(JavaType::Object(t.clone())))
942                        .unwrap_or_else(|| {
943                            TypeRef::J(JavaType::Object("java/lang/Throwable".into()))
944                        });
945                    let v = self.fresh_var(*dst, ty);
946                    self.stmts.push(Stmt::LocalDef {
947                        var: v,
948                        init: None,
949                        is_final: false,
950                        force_type: true,
951                    });
952                    if (*dst as usize) < self.regs.len() {
953                        self.regs[*dst as usize] = Reg::Live(v);
954                    }
955                }
956                InsnKind::ReturnVoid
957                | InsnKind::Return { .. }
958                | InsnKind::Throw { .. }
959                | InsnKind::Goto { .. }
960                | InsnKind::PackedSwitch { .. }
961                | InsnKind::SparseSwitch { .. }
962                | InsnKind::If { .. } => {}
963                InsnKind::Const { dst, val, wide } => {
964                    let e = if *wide {
965                        Expr::Const(ConstVal::Long(*val))
966                    } else {
967                        Expr::Const(ConstVal::Int(*val as i32))
968                    };
969                    self.write(*dst, e, ins.pc, *wide);
970                }
971                InsnKind::ConstString { dst, str_idx } => {
972                    let s = std::sync::Arc::from(self.env.dex.string(*str_idx));
973                    self.write(*dst, Expr::Const(ConstVal::Str(s)), ins.pc, false);
974                }
975                InsnKind::ConstClass { dst, type_idx } => {
976                    let ty = TypeRef::J(self.env.java_type(*type_idx));
977                    self.write(*dst, Expr::Const(ConstVal::ClassLit(ty)), ins.pc, false);
978                }
979                InsnKind::MonitorEnter { reg } => {
980                    let e = self.read_nest(*reg);
981                    *self.mflags = self.mflags.with_monitor();
982                    self.stmts.push(Stmt::MonitorEnter(e));
983                }
984                InsnKind::MonitorExit { reg } => {
985                    let e = self.read_nest(*reg);
986                    *self.mflags = self.mflags.with_monitor();
987                    self.stmts.push(Stmt::MonitorExit(e));
988                }
989                InsnKind::CheckCast { reg, type_idx } => {
990                    let e = self.read_nest(*reg);
991                    let ty = TypeRef::J(self.env.java_type(*type_idx));
992                    self.write(*reg, Expr::Cast { ty, e: Box::new(e) }, ins.pc, false);
993                }
994                InsnKind::InstanceOf { dst, src, type_idx } => {
995                    let e = self.read_nest(*src);
996                    let ty = TypeRef::J(self.env.java_type(*type_idx));
997                    self.write(*dst, Expr::InstanceOf { e: Box::new(e), ty }, ins.pc, false);
998                }
999                InsnKind::ArrayLength { dst, src } => {
1000                    let e = self.read_nest(*src);
1001                    let length = Expr::Field {
1002                        owner: Some(Box::new(e)),
1003                        cls: std::sync::Arc::from(""),
1004                        name: "length".into(),
1005                        ty: TypeRef::J(JavaType::Int),
1006                        is_static: false,
1007                    };
1008                    self.write(*dst, length, ins.pc, false);
1009                }
1010                InsnKind::NewInstance { dst, type_idx } => {
1011                    let cls = self.env.type_name_arc(*type_idx);
1012                    let ty = TypeRef::J(JavaType::Object(cls.clone()));
1013                    self.write(
1014                        *dst,
1015                        Expr::New {
1016                            cls,
1017                            ty,
1018                            args: vec![],
1019                            arg_tys: Vec::new(),
1020                            raw: true,
1021                        },
1022                        ins.pc,
1023                        false,
1024                    );
1025                }
1026                InsnKind::NewArray {
1027                    dst,
1028                    size,
1029                    type_idx,
1030                } => {
1031                    let elem_desc = self.env.type_name(*type_idx);
1032                    // The type id names the ARRAY type: strip one `[`.
1033                    let elem = crate::desc_type(elem_desc.trim_start_matches('['));
1034                    // `new-array vB, vC, T@` allocates ONE dimension (vC) of
1035                    // elements whose type is T@ with a single `[` stripped.
1036                    // When T@ is itself an array (`[[I` = int[][]), the extra
1037                    // `[` levels are trailing empty dims: `new int[size][]`.
1038                    // Counting only the first `[` as the sized dim and the
1039                    // rest as trailing_dims (elem keeps the fully-stripped
1040                    // base) — the old trim_start_matches('[') dropped every
1041                    // level, rendering int[][] as `new int[size]` and the
1042                    // element stores as `a[i] = (int[]) x` ("int[]无法转换
1043                    // 为int", 267 on reqable).
1044                    let n_brackets = elem_desc.chars().take_while(|&c| c == '[').count();
1045                    let trailing_dims = n_brackets.saturating_sub(1).min(u8::MAX as usize) as u8;
1046                    let dims = self.read_nest(*size);
1047                    self.write(
1048                        *dst,
1049                        Expr::NewArray {
1050                            elem: TypeRef::J(elem),
1051                            dims: vec![dims],
1052                            trailing_dims,
1053                            init: None,
1054                        },
1055                        ins.pc,
1056                        false,
1057                    );
1058                }
1059                InsnKind::FilledNewArray { regs, type_idx } => {
1060                    self.drop_pending_call();
1061                    let elem_desc = self.env.type_name(*type_idx);
1062                    let elem = crate::desc_type(elem_desc.trim_start_matches('['));
1063                    // A wide element (long/double) occupies TWO
1064                    // register slots per element — walking the cursor by
1065                    // the element width groups them correctly (reading
1066                    // every register minted fresh locals from the WideHi
1067                    // slots).
1068                    let wide = elem.is_wide();
1069                    let mut args: Vec<Expr> = Vec::with_capacity(regs.len());
1070                    let mut it = regs.iter();
1071                    while let Some(&r) = it.next() {
1072                        args.push(self.read_nest(r));
1073                        if wide {
1074                            it.next();
1075                        }
1076                    }
1077                    self.pending_call = Some(Expr::NewArray {
1078                        elem: TypeRef::J(elem),
1079                        dims: vec![],
1080                        trailing_dims: 0,
1081                        init: Some(args),
1082                    });
1083                }
1084                InsnKind::FillArrayData { reg, payload_pc } => {
1085                    if let Some(Payload::ArrayData {
1086                        elem_width,
1087                        size,
1088                        data,
1089                    }) = payloads.get(payload_pc)
1090                    {
1091                        let elems = payload_consts(*elem_width, *size, data);
1092                        let cur = self.regs.get(*reg as usize).cloned().unwrap_or(Reg::Undef);
1093                        if let Reg::Pending(Expr::NewArray { elem, init, .. }) = cur {
1094                            if init.is_none() {
1095                                self.write(
1096                                    *reg,
1097                                    Expr::NewArray {
1098                                        elem,
1099                                        dims: vec![Expr::Const(ConstVal::Int(*size as i32))],
1100                                        trailing_dims: 0,
1101                                        init: Some(elems),
1102                                    },
1103                                    ins.pc,
1104                                    false,
1105                                );
1106                                continue;
1107                            }
1108                        }
1109                        // Not the new-array+fill pattern: element stores.
1110                        let arr = self.read_nest(*reg);
1111                        for (i, e) in elems.into_iter().enumerate() {
1112                            let idx = Expr::Const(ConstVal::Int(i as i32));
1113                            let target = Expr::ArrayIndex {
1114                                array: Box::new(arr.clone()),
1115                                index: Box::new(idx),
1116                            };
1117                            self.stmts.push(Stmt::ExprStmt(Expr::Assign {
1118                                target: Box::new(target),
1119                                op: AssignOp::Plain,
1120                                value: Box::new(e),
1121                            }));
1122                        }
1123                    }
1124                }
1125                InsnKind::Cmp { dst, a, b, kind } => {
1126                    let l = self.read_nest(*a);
1127                    let r = self.read_nest(*b);
1128                    *self.mflags = self.mflags.with_cmp();
1129                    self.write(*dst, Self::cmp_sentinel(*kind, l, r), ins.pc, false);
1130                }
1131                InsnKind::AGet {
1132                    dst, array, index, ..
1133                } => {
1134                    let a = self.read_nest(*array);
1135                    let i = self.read_nest(*index);
1136                    self.write(
1137                        *dst,
1138                        Expr::ArrayIndex {
1139                            array: Box::new(a),
1140                            index: Box::new(i),
1141                        },
1142                        ins.pc,
1143                        false,
1144                    );
1145                }
1146                InsnKind::APut {
1147                    value,
1148                    array,
1149                    index,
1150                    ..
1151                } => {
1152                    self.drop_pending_call();
1153                    let v = self.read_nest(*value);
1154                    let a = self.read_nest(*array);
1155                    let i = self.read_nest(*index);
1156                    let target = Expr::ArrayIndex {
1157                        array: Box::new(a),
1158                        index: Box::new(i),
1159                    };
1160                    self.stmts.push(Stmt::ExprStmt(Expr::Assign {
1161                        target: Box::new(target),
1162                        op: AssignOp::Plain,
1163                        value: Box::new(v),
1164                    }));
1165                }
1166                InsnKind::IGet {
1167                    dst,
1168                    obj,
1169                    field_idx,
1170                } => {
1171                    self.drop_pending_call();
1172                    let (cls, name, ty) = self.env.field_ref(*field_idx);
1173                    let owner = self.read_nest(*obj);
1174                    let owner_opt = self.owner_expr(owner, &cls);
1175                    self.write(
1176                        *dst,
1177                        Expr::Field {
1178                            owner: owner_opt,
1179                            cls,
1180                            name,
1181                            ty: TypeRef::J(ty),
1182                            is_static: false,
1183                        },
1184                        ins.pc,
1185                        false,
1186                    );
1187                }
1188                InsnKind::IPut {
1189                    value,
1190                    obj,
1191                    field_idx,
1192                } => {
1193                    self.drop_pending_call();
1194                    let (cls, name, ty) = self.env.field_ref(*field_idx);
1195                    let v = null_in_obj_ctx(self.read_nest(*value), &ty);
1196                    let owner = self.read_nest(*obj);
1197                    let owner_opt = self.owner_expr(owner, &cls);
1198                    let target = Expr::Field {
1199                        owner: owner_opt,
1200                        cls,
1201                        name,
1202                        ty: TypeRef::J(ty),
1203                        is_static: false,
1204                    };
1205                    self.stmts.push(Stmt::ExprStmt(Expr::Assign {
1206                        target: Box::new(target),
1207                        op: AssignOp::Plain,
1208                        value: Box::new(v),
1209                    }));
1210                }
1211                InsnKind::SGet { dst, field_idx } => {
1212                    self.drop_pending_call();
1213                    let (cls, name, ty) = self.env.field_ref(*field_idx);
1214                    self.write(
1215                        *dst,
1216                        Expr::Field {
1217                            owner: None,
1218                            cls,
1219                            name,
1220                            ty: TypeRef::J(ty),
1221                            is_static: true,
1222                        },
1223                        ins.pc,
1224                        false,
1225                    );
1226                }
1227                InsnKind::SPut { value, field_idx } => {
1228                    self.drop_pending_call();
1229                    let (cls, name, ty) = self.env.field_ref(*field_idx);
1230                    let v = null_in_obj_ctx(self.read_nest(*value), &ty);
1231                    let target = Expr::Field {
1232                        owner: None,
1233                        cls,
1234                        name,
1235                        ty: TypeRef::J(ty),
1236                        is_static: true,
1237                    };
1238                    self.stmts.push(Stmt::ExprStmt(Expr::Assign {
1239                        target: Box::new(target),
1240                        op: AssignOp::Plain,
1241                        value: Box::new(v),
1242                    }));
1243                }
1244                InsnKind::Invoke {
1245                    kind,
1246                    regs,
1247                    method_idx,
1248                } => {
1249                    self.drop_pending_call();
1250                    self.do_invoke(*kind, regs, *method_idx, ins.pc)?;
1251                }
1252                InsnKind::InvokeCustom {
1253                    call_site_idx,
1254                    regs,
1255                } => {
1256                    self.drop_pending_call();
1257                    let e = self.build_invoke_custom(*call_site_idx, regs, ins.pc);
1258                    self.pending_call = Some(e);
1259                }
1260                InsnKind::Un {
1261                    dst,
1262                    src,
1263                    op,
1264                    from: _,
1265                    to,
1266                } => {
1267                    let e = self.read_nest(*src);
1268                    let ne = match op {
1269                        ddc_dex::insn::UnArith::Neg => Expr::Un {
1270                            op: UnOp::Neg,
1271                            e: Box::new(e),
1272                        },
1273                        ddc_dex::insn::UnArith::Not => Expr::Un {
1274                            op: UnOp::BitNot,
1275                            e: Box::new(e),
1276                        },
1277                        ddc_dex::insn::UnArith::Conv => Expr::Cast {
1278                            ty: TypeRef::J(primitive_type(*to)),
1279                            e: Box::new(e),
1280                        },
1281                    };
1282                    let wide = matches!(*to, 'J' | 'D');
1283                    self.write(*dst, ne, ins.pc, wide);
1284                }
1285                InsnKind::Bin { op, dst, a, b, ty } => {
1286                    let l = self.read_nest(*a);
1287                    let r = self.read_nest(*b);
1288                    let jt = primitive_type(*ty);
1289                    let e = Expr::Bin {
1290                        op: Self::arith_op(*op),
1291                        l: Box::new(l),
1292                        r: Box::new(r),
1293                        ty: Some(TypeRef::J(jt)),
1294                    };
1295                    let wide = matches!(*ty, 'J' | 'D');
1296                    self.write(*dst, e, ins.pc, wide);
1297                }
1298                InsnKind::BinLit {
1299                    op,
1300                    dst,
1301                    a,
1302                    lit,
1303                    rsub,
1304                } => {
1305                    let av = self.read_nest(*a);
1306                    let e = if *rsub {
1307                        Expr::Bin {
1308                            op: BinOp::Sub,
1309                            l: Box::new(Expr::Const(ConstVal::Int(*lit))),
1310                            r: Box::new(av),
1311                            ty: Some(TypeRef::J(JavaType::Int)),
1312                        }
1313                    } else {
1314                        Expr::Bin {
1315                            op: Self::arith_op(*op),
1316                            l: Box::new(av),
1317                            r: Box::new(Expr::Const(ConstVal::Int(*lit))),
1318                            ty: Some(TypeRef::J(JavaType::Int)),
1319                        }
1320                    };
1321                    self.write(*dst, e, ins.pc, false);
1322                }
1323                InsnKind::ConstMethodHandle { dst, handle_idx } => {
1324                    self.drop_pending_call();
1325                    let e = self.method_handle_expr(*handle_idx);
1326                    self.write(*dst, e, ins.pc, false);
1327                }
1328                InsnKind::ConstMethodType { dst, proto_idx } => {
1329                    self.drop_pending_call();
1330                    let proto = self.env.dex.proto(*proto_idx);
1331                    let desc = format!(
1332                        "({}){}",
1333                        self.env
1334                            .dex
1335                            .proto_params(*proto_idx)
1336                            .iter()
1337                            .map(|&t| self.env.dex.type_name(t))
1338                            .collect::<Vec<_>>()
1339                            .join(""),
1340                        self.env.dex.type_name(proto.return_type_idx)
1341                    );
1342                    self.write(*dst, Expr::Raw(desc), ins.pc, false);
1343                }
1344            }
1345        }
1346
1347        // Terminator first: terms may consume PendingCall values directly.
1348        let term = self.block_term(ins);
1349
1350        // Exit cleanup: unconsumed call → statement; impure pendings → vars.
1351        // Open `new`/`new-array` views stay pending (their consumer may live
1352        // in a later block).
1353        self.drop_pending_call();
1354        self.materialize_impure_at_exit();
1355
1356        // Move (not clone): the lifter is consumed after build_block, and
1357        // these two clones — regs deep-copies boxed Exprs for any Pending
1358        // states — ran 3.7M times on weibo.
1359        let out = OutState {
1360            regs: std::mem::take(&mut self.regs),
1361            write_pc: std::mem::take(&mut self.write_pc),
1362        };
1363        Ok((
1364            BlockResult {
1365                stmts: std::mem::take(&mut self.stmts),
1366                out_stack: Vec::new(),
1367                term,
1368            },
1369            out,
1370        ))
1371    }
1372
1373    fn do_invoke(
1374        &mut self,
1375        kind: InvokeKind,
1376        regs: &[u16],
1377        method_idx: u32,
1378        pc: u32,
1379    ) -> BResult<()> {
1380        let (cls, name, md) = self.env.method_ref(method_idx);
1381        if cls.as_ref() == "java/lang/StringBuilder" || cls.as_ref() == "java/lang/StringBuffer" {
1382            *self.mflags = self.mflags.with_sb();
1383        }
1384        let is_static = matches!(kind, InvokeKind::Static);
1385        let receiver_reg = if is_static {
1386            None
1387        } else {
1388            regs.first().copied()
1389        };
1390        let arg_regs: Vec<u16> = if is_static {
1391            regs.to_vec()
1392        } else {
1393            regs.iter().skip(1).copied().collect()
1394        };
1395        let mut args: Vec<Expr> = Vec::with_capacity(md.args.len());
1396        // A WIDE parameter (long/double) occupies TWO register slots in
1397        // the instruction's register list — indexing by PARAMETER
1398        // position shifted every argument after a wide one (weixin
1399        // yieldTransaction(JZ L) read the boolean from the long's HIGH
1400        // register and the signal from the boolean's — the root of the
1401        // call-argument int↔bool family and ~11k dangling `int vN`
1402        // reads). Advance the register cursor by the arg's width.
1403        let mut ri = 0usize;
1404        for at in md.args.iter() {
1405            let r = arg_regs.get(ri).copied().unwrap_or(0);
1406            args.push(null_in_obj_ctx(self.read_nest(r), at));
1407            ri += if at.is_wide() { 2 } else { 1 };
1408        }
1409        let recv_expr = receiver_reg.map(|r| self.read_nest(r));
1410
1411        // Constructor call: fold `new C` receivers; this/super otherwise.
1412        if name.as_ref() == "<init>" && matches!(kind, InvokeKind::Direct) {
1413            let recv_reg = receiver_reg.unwrap_or(0);
1414            let recv_state = self
1415                .regs
1416                .get(recv_reg as usize)
1417                .cloned()
1418                .unwrap_or(Reg::Undef);
1419            if let Reg::Pending(Expr::New {
1420                raw: true, cls: nc, ..
1421            }) = &recv_state
1422            {
1423                if nc == &cls {
1424                    let folded = Expr::New {
1425                        cls: cls.clone(),
1426                        ty: TypeRef::J(JavaType::Object(cls.clone())),
1427                        arg_tys: md.args.clone(),
1428                        args,
1429                        raw: false,
1430                    };
1431                    // The raw pending may live in SEVERAL registers:
1432                    // `move-object` copies it for the invoke-range
1433                    // receiver shuffle. Writing only the receiver left
1434                    // the original register's raw view behind, so the
1435                    // following `sput v0` inlined an EMPTY `new C()`
1436                    // while the real construction orphaned at the
1437                    // receiver. Carry the fold to every alias, keyed by
1438                    // the origin write_pc the Move handler propagates.
1439                    let origin = self.write_pc.get(recv_reg as usize).copied();
1440                    let aliases: Vec<usize> = origin
1441                        .map(|w| {
1442                            (0..self.regs.len())
1443                                .filter(|&r| {
1444                                    r != recv_reg as usize
1445                                        && self.write_pc.get(r).copied() == Some(w)
1446                                        && matches!(
1447                                            &self.regs[r],
1448                                            Reg::Pending(Expr::New { raw: true, cls: c, .. })
1449                                                if c == nc
1450                                        )
1451                                })
1452                                .collect()
1453                        })
1454                        .unwrap_or_default();
1455                    self.write(recv_reg, folded.clone(), pc, false);
1456                    // write()'s size cap may have materialized the
1457                    // construction into a local — share that var with the
1458                    // aliases instead of pending copies of the same
1459                    // allocation.
1460                    match self.regs.get(recv_reg as usize) {
1461                        Some(Reg::Live(v)) => {
1462                            let v = *v;
1463                            for r in aliases {
1464                                self.regs[r] = Reg::Live(v);
1465                            }
1466                        }
1467                        _ => {
1468                            for r in aliases {
1469                                self.regs[r] = Reg::Pending(folded.clone());
1470                                self.write_pc[r] = pc;
1471                            }
1472                        }
1473                    }
1474                    return Ok(());
1475                }
1476            }
1477            let owner_expr_v = recv_expr.unwrap_or(Expr::This);
1478            // Normalize the receiver: in an instance method the `this`
1479            // parameter is ALWAYS var 0 (entry_regs pushes it first).
1480            // read_nest hands back Local{var:0}, which the emitter's
1481            // is_this/lost_alloc checks do not recognize — a plain
1482            // `super()` arrived there as a non-this receiver and printed
1483            // `new Object();` (every default ctor in every app).
1484            let owner_expr_v = if !self.env.is_static
1485                && matches!(&owner_expr_v, Expr::Local { var: 0, .. })
1486            {
1487                Expr::This
1488            } else {
1489                owner_expr_v
1490            };
1491            let is_super = cls.as_ref() != self.env.class_name.as_str();
1492            let owner = if matches!(owner_expr_v, Expr::This) && is_super {
1493                None
1494            } else {
1495                Some(Box::new(owner_expr_v))
1496            };
1497            let call = Expr::Method {
1498                owner,
1499                cls,
1500                name: "<init>".into(),
1501                desc: md,
1502                args,
1503                is_static: false,
1504                is_interface: false,
1505                is_special: true,
1506                is_super,
1507                is_dynamic: false,
1508                type_args: vec![],
1509            };
1510            self.stmts.push(Stmt::ExprStmt(call));
1511            return Ok(());
1512        }
1513
1514        let is_interface = matches!(kind, InvokeKind::Interface);
1515        // `super.` only when the receiver is THIS. R8/d8 desugar an
1516        // inner-class/lambda `outer.super.m()` into a STATIC synthetic
1517        // accessor `w(Outer p) { invoke-special p, Super.m() }` — a
1518        // nonvirtual call on a PARAMETER. The `super` keyword is illegal
1519        // there ("无法从静态上下文中引用非静态 变量 super", weixin 318 +
1520        // lark 176), and Java cannot express special dispatch on an
1521        // arbitrary instance, so a plain call on the receiver is the
1522        // only legal render.
1523        // The receiver may reach here as Expr::This, the Raw("\u{3}")
1524        // placeholder, or — most often — the `this` LOCAL (read_nest of
1525        // register v0; the VarInfo is named "this" and emit prints the
1526        // keyword). All three are the this-receiver; anything else (a
1527        // real parameter/local) is not.
1528        let recv_is_this = match &recv_expr {
1529            Some(Expr::This) => true,
1530            Some(Expr::Raw(t)) => t == "\u{3}" || t == "this",
1531            Some(Expr::Local { var, .. }) => {
1532                (*var as usize) < self.vt.vars.len() && self.vt.vars[*var as usize].name == "this"
1533            }
1534            _ => false,
1535        };
1536        let is_super = match kind {
1537            InvokeKind::Super | InvokeKind::Direct => {
1538                recv_is_this && cls.as_ref() != self.env.class_name.as_str()
1539            }
1540            _ => false,
1541        };
1542        let owner: Option<Box<Expr>> = match recv_expr {
1543            None => None,
1544            Some(o) => {
1545                if is_super && matches!(o, Expr::This) {
1546                    None
1547                } else {
1548                    self.owner_expr(o, &cls)
1549                }
1550            }
1551        };
1552        let is_dynamic = matches!(kind, InvokeKind::Polymorphic);
1553        let call = Expr::Method {
1554            owner,
1555            cls,
1556            name,
1557            desc: md,
1558            args,
1559            is_static,
1560            is_interface,
1561            is_special: matches!(kind, InvokeKind::Direct),
1562            is_super,
1563            is_dynamic,
1564            type_args: vec![],
1565        };
1566        self.pending_call = Some(call);
1567        Ok(())
1568    }
1569
1570    /// Resolve a method-handle constant into a readable expression
1571    /// (`Cls::name` for method kinds).
1572    fn method_handle_expr(&mut self, handle_idx: u32) -> Expr {
1573        let Some(h) = self.env.dex.method_handle(handle_idx) else {
1574            return Expr::Raw(format!("methodHandle@{}", handle_idx));
1575        };
1576        if h.is_field {
1577            let f = self.env.dex.field(h.target_id);
1578            let cls = self.env.dex.class_name(f.class_idx);
1579            let name = self.env.dex.string(f.name_idx).to_string();
1580            return Expr::Raw(format!("{}::{}", cls.replace('/', "."), name));
1581        }
1582        let m = self.env.dex.method(h.target_id);
1583        let cls = self.env.dex.class_name(m.class_idx);
1584        let name = self.env.dex.string(m.name_idx).to_string();
1585        Expr::Raw(format!("{}::{}", cls.replace('/', "."), name))
1586    }
1587
1588    /// Build the expression for an invoke-custom site.
1589    fn build_invoke_custom(&mut self, cs_idx: u32, regs: &[u16], pc: u32) -> Expr {
1590        let Some(cs) = self.env.dex.call_site(cs_idx).cloned() else {
1591            return Expr::Invokedynamic {
1592                name: format!("call-site#{}", cs_idx),
1593                desc: jdc_core::types::MethodDescriptor {
1594                    args: vec![],
1595                    ret: JavaType::Object("java/lang/Object".into()),
1596                },
1597                args: vec![],
1598                bsm_text: "unresolved".into(),
1599                bsm_static_args: vec![],
1600            };
1601        };
1602        let site_name = self.env.dex.string(cs.name_idx).to_string();
1603        let params: Vec<JavaType> = self
1604            .env
1605            .dex
1606            .proto_params(cs.proto_idx)
1607            .iter()
1608            .map(|&t| self.env.java_type(t))
1609            .collect();
1610        let ret = self
1611            .env
1612            .java_type(self.env.dex.proto(cs.proto_idx).return_type_idx);
1613
1614        let (bs_cls, bs_name) = match self.env.dex.method_handle(cs.bootstrap_handle) {
1615            Some(h) if !h.is_field => {
1616                let m = self.env.dex.method(h.target_id);
1617                (
1618                    self.env.dex.class_name(m.class_idx),
1619                    self.env.dex.string(m.name_idx).to_string(),
1620                )
1621            }
1622            _ => (String::new(), String::new()),
1623        };
1624
1625        // Dynamic arguments (the SAM parameters for lambdas). A wide
1626        // parameter occupies TWO register slots — index a walking cursor
1627        // by the param's width, not the param position (same bug class
1628        // as the invoke arg lift).
1629        let mut args: Vec<Expr> = Vec::with_capacity(params.len().min(regs.len()));
1630        let mut ri = 0usize;
1631        for at in params.iter() {
1632            if let Some(&r) = regs.get(ri) {
1633                args.push(self.read_nest(r));
1634            }
1635            ri += if at.is_wide() { 2 } else { 1 };
1636        }
1637
1638        // StringConcatFactory: fold the recipe into `+`.
1639        if bs_name == "makeConcatWithConstants" {
1640            let recipe = cs
1641                .linker_args
1642                .iter()
1643                .find_map(|v| match v {
1644                    ddc_dex::annotations::EncodedValue::String(s) => {
1645                        Some(self.env.dex.string(*s).to_string())
1646                    }
1647                    _ => None,
1648                })
1649                .unwrap_or_default();
1650            return concat_from_recipe(&recipe, args);
1651        }
1652
1653        // LambdaMetafactory: linker args are [samType (erased),
1654        // implMethod (handle), instantiatedMethodType]. The instantiated
1655        // type carries the source-level SAM parameters.
1656        let mut impl_m = None;
1657        let mut instantiated_proto: Option<u32> = None;
1658        if bs_name == "metafactory" || bs_name == "altMetafactory" {
1659            let mut seen_handle = false;
1660            for lv in &cs.linker_args {
1661                match lv {
1662                    ddc_dex::annotations::EncodedValue::MethodHandle(hi) => {
1663                        if !seen_handle {
1664                            seen_handle = true;
1665                            if let Some(h) = self.env.dex.method_handle(*hi) {
1666                                if !h.is_field {
1667                                    let m = self.env.dex.method(h.target_id);
1668                                    impl_m = Some((
1669                                        self.env.dex.class_name(m.class_idx).replace('/', "."),
1670                                        self.env.dex.string(m.name_idx).to_string(),
1671                                    ));
1672                                }
1673                            }
1674                        }
1675                    }
1676                    ddc_dex::annotations::EncodedValue::MethodType(p) if seen_handle => {
1677                        instantiated_proto = Some(*p);
1678                    }
1679                    _ => {}
1680                }
1681            }
1682        }
1683        let _ = pc;
1684
1685        // Remaining registers are the captured values.
1686        let mut captures = Vec::new();
1687        for &r in regs.iter().skip(params.len().min(regs.len())) {
1688            captures.push(self.read_nest(r));
1689        }
1690
1691        if let Some((impl_cls, impl_name)) = impl_m {
1692            if captures.is_empty() {
1693                // Non-capturing: render real Java syntax. A synthetic
1694                // `lambda$` impl is a lambda; anything else is a method
1695                // reference (`Cls::name`).
1696                if impl_name.starts_with("lambda$") {
1697                    // Source-level parameter count comes from the
1698                    // instantiated SAM type, not the site proto (which is
1699                    // the functional-interface factory view: `()Function`).
1700                    let n_params = match instantiated_proto {
1701                        Some(p) => self.env.dex.proto_params(p).len(),
1702                        None => params.len(),
1703                    };
1704                    let pnames: Vec<String> = (0..n_params).map(|i| format!("a{}", i)).collect();
1705                    return Expr::Raw(format!(
1706                        "({}) -> {}.{}({})",
1707                        pnames.join(", "),
1708                        impl_cls,
1709                        impl_name,
1710                        pnames.join(", ")
1711                    ));
1712                }
1713                return Expr::Raw(format!("{}::{}", impl_cls, impl_name));
1714            }
1715            // Capturing: the captures are real expressions; emit the
1716            // desugared call shape (impl applies SAM params then captures).
1717            let mut call_args = args;
1718            call_args.extend(captures);
1719            return Expr::Invokedynamic {
1720                name: format!("{} -> {}.{}", site_name, impl_cls, impl_name),
1721                desc: jdc_core::types::MethodDescriptor { args: params, ret },
1722                args: call_args,
1723                bsm_text: format!("{}::{}", bs_cls, bs_name),
1724                bsm_static_args: vec![],
1725            };
1726        }
1727
1728        Expr::Invokedynamic {
1729            name: site_name,
1730            desc: jdc_core::types::MethodDescriptor { args: params, ret },
1731            args: captures,
1732            bsm_text: format!("{}::{}", bs_cls, bs_name),
1733            bsm_static_args: vec![],
1734        }
1735    }
1736
1737    fn materialize_impure_at_exit(&mut self) {
1738        let n = self.regs.len();
1739        for r in 0..n {
1740            let st = self.regs[r].clone();
1741            let impure = match &st {
1742                Reg::PendingCall(_) => true,
1743                Reg::Pending(e) => {
1744                    has_side_effects(e)
1745                        && !matches!(e, Expr::New { raw: true, .. })
1746                        && !matches!(e, Expr::NewArray { init: None, .. })
1747                }
1748                _ => false,
1749            };
1750            if impure {
1751                self.materialize(r as u16);
1752            }
1753        }
1754    }
1755
1756    /// Terminator for the block, from its last instruction.
1757    fn block_term(&mut self, ins: &[Insn]) -> Term {
1758        let Some(last) = ins.last() else {
1759            return Term::Goto;
1760        };
1761        match &last.kind {
1762            InsnKind::Goto { .. } => Term::Goto,
1763            InsnKind::ReturnVoid => Term::Return(None),
1764            InsnKind::Return { src } => {
1765                let v = null_in_obj_ctx(self.read_term(*src), &self.env.desc.ret);
1766                Term::Return(Some(v))
1767            }
1768            InsnKind::Throw { reg } => {
1769                // throw is always an object context.
1770                let mut v = self.read_term(*reg);
1771                if let Expr::Const(ConstVal::Int(0)) = v {
1772                    v = Expr::Const(ConstVal::Null);
1773                }
1774                Term::Throw(v)
1775            }
1776            InsnKind::If { op, a, b, z, .. } => {
1777                let cond = if *z {
1778                    let v = self.read_nest(*a);
1779                    let (l, r, realop) = jdc_core::ir::build::unfold_cmp(v, Self::cmp_op(*op));
1780                    Expr::Bin {
1781                        op: realop,
1782                        l: Box::new(l),
1783                        r: Box::new(r),
1784                        ty: Some(TypeRef::J(JavaType::Boolean)),
1785                    }
1786                } else {
1787                    let l = self.read_nest(*a);
1788                    let r = self.read_nest(*b);
1789                    Expr::Bin {
1790                        op: Self::cmp_op(*op),
1791                        l: Box::new(l),
1792                        r: Box::new(r),
1793                        ty: Some(TypeRef::J(JavaType::Boolean)),
1794                    }
1795                };
1796                Term::Cond { cond }
1797            }
1798            InsnKind::PackedSwitch { reg, payload_pc }
1799            | InsnKind::SparseSwitch { reg, payload_pc } => {
1800                let selector = self.read_term(*reg);
1801                let default = Some(last.pc + last.size);
1802                let targets = match self.env.code.payloads.get(payload_pc) {
1803                    Some(Payload::Packed { first_key, targets }) => SwitchTargets::Table {
1804                        low: *first_key,
1805                        targets: targets
1806                            .iter()
1807                            .map(|t| (last.pc as i64 + *t as i64) as u32)
1808                            .collect(),
1809                    },
1810                    Some(Payload::Sparse { pairs }) => SwitchTargets::Lookup {
1811                        pairs: pairs
1812                            .iter()
1813                            .map(|(k, t)| (*k, (last.pc as i64 + *t as i64) as u32))
1814                            .collect(),
1815                    },
1816                    _ => SwitchTargets::Lookup { pairs: vec![] },
1817                };
1818                Term::Switch {
1819                    selector,
1820                    targets,
1821                    default,
1822                }
1823            }
1824            // Fell off the analysis end (payload region after): goto.
1825            _ => {
1826                let next = last.pc + last.size;
1827                if next < self.code_units {
1828                    Term::Fallthrough
1829                } else {
1830                    Term::Goto
1831                }
1832            }
1833        }
1834    }
1835}
1836
1837/// StringConcatFactory recipe → `+` parts: `\u{1}` slots consume the next
1838/// argument, `\u{2}` <len> <chars> emits literal text (rare), other bytes
1839/// are literal.
1840fn concat_from_recipe(recipe: &str, args: Vec<Expr>) -> Expr {
1841    use jdc_core::ir::expr::ConcatPart;
1842    let mut parts: Vec<ConcatPart> = Vec::new();
1843    let mut arg_i = 0usize;
1844    let mut const_buf = String::new();
1845    for c in recipe.chars() {
1846        match c {
1847            '\u{1}' => {
1848                if !const_buf.is_empty() {
1849                    parts.push(ConcatPart::Const(std::mem::take(&mut const_buf)));
1850                }
1851                if arg_i < args.len() {
1852                    parts.push(ConcatPart::Str(args[arg_i].clone()));
1853                    arg_i += 1;
1854                }
1855            }
1856            '\u{2}' => {
1857                // Length-prefixed literal: skip the length char and copy the
1858                // following chars until the next marker.
1859            }
1860            c => const_buf.push(c),
1861        }
1862    }
1863    if !const_buf.is_empty() {
1864        parts.push(ConcatPart::Const(const_buf));
1865    }
1866    Expr::StringConcat(parts)
1867}
1868
1869/// Node count of an expression tree (caps loop-carried growth: a Pending
1870/// tree that grows across fixpoint rounds would otherwise reach GBs — each
1871/// merge clones the whole tree per side per visit).
1872fn expr_size(e: &Expr) -> usize {
1873    let mut n = 0usize;
1874    count_nodes(e, &mut n);
1875    n
1876}
1877
1878fn count_nodes(e: &Expr, n: &mut usize) {
1879    *n += 1;
1880    if *n > 512 {
1881        return; // cap the walk itself
1882    }
1883    match e {
1884        Expr::Un { e, .. } | Expr::Cast { e, .. } | Expr::InstanceOf { e, .. } => count_nodes(e, n),
1885        Expr::Bin { l, r, .. } => {
1886            count_nodes(l, n);
1887            count_nodes(r, n);
1888        }
1889        Expr::Cond { c, t, f } => {
1890            count_nodes(c, n);
1891            count_nodes(t, n);
1892            count_nodes(f, n);
1893        }
1894        Expr::Assign { target, value, .. } => {
1895            count_nodes(target, n);
1896            count_nodes(value, n);
1897        }
1898        Expr::PreIncDec { e, .. } | Expr::PostIncDec { e, .. } => count_nodes(e, n),
1899        Expr::Field { owner: Some(o), .. } => count_nodes(o, n),
1900        Expr::Method {
1901            owner: Some(o),
1902            args,
1903            ..
1904        } => {
1905            count_nodes(o, n);
1906            for a in args {
1907                count_nodes(a, n);
1908            }
1909        }
1910        Expr::ArrayIndex { array, index } => {
1911            count_nodes(array, n);
1912            count_nodes(index, n);
1913        }
1914        Expr::New { args, .. } => {
1915            for a in args {
1916                count_nodes(a, n);
1917            }
1918        }
1919        Expr::NewArray { dims, init, .. } => {
1920            for d in dims {
1921                count_nodes(d, n);
1922            }
1923            if let Some(v) = init {
1924                for x in v {
1925                    count_nodes(x, n);
1926                }
1927            }
1928        }
1929        Expr::NewMultiArray { dims, .. } => {
1930            for d in dims {
1931                count_nodes(d, n);
1932            }
1933        }
1934        Expr::StringConcat(parts) => {
1935            for p in parts {
1936                if let ConcatPart::Str(x) = p {
1937                    count_nodes(x, n);
1938                }
1939            }
1940        }
1941        _ => {}
1942    }
1943}
1944
1945fn reg_is_wide(st: &Reg, vt: &VarTable) -> bool {
1946    match st {
1947        Reg::Pending(e) | Reg::PendingCall(e) => e.type_ref().erased().is_wide(),
1948        Reg::Live(v) => vt.var(*v).ty.erased().is_wide(),
1949        Reg::WideHi => true,
1950        Reg::Undef => false,
1951    }
1952}
1953
1954/// d8 encodes `null` as `const/4 vN, 0`; the instruction kind does not
1955/// distinguish object contexts (return/return-object share one variant),
1956/// so the surrounding DESCRIPTOR type decides: a zero constant flowing
1957/// into a reference context is `null`, not `0` (rendering `return 0;`
1958/// from a String method — lab-package feedback).
1959fn null_in_obj_ctx(mut v: Expr, ctx_ty: &JavaType) -> Expr {
1960    if ctx_ty.is_reference() {
1961        if let Expr::Const(ConstVal::Int(0)) = v {
1962            v = Expr::Const(ConstVal::Null);
1963        }
1964    }
1965    v
1966}
1967
1968/// Turn a stored cmp sentinel into a `Long.compare`-style call.
1969fn value_of_cmp(e: &Expr) -> Expr {
1970    if let Expr::Invokedynamic { name, args, .. } = e {
1971        if name.starts_with('\0') && args.len() == 2 {
1972            let (cls, ty) = match name.as_str() {
1973                "\0cmp-long" => ("java/lang/Long", JavaType::Long),
1974                "\0cmpl-float" | "\0cmpg-float" => ("java/lang/Float", JavaType::Float),
1975                _ => ("java/lang/Double", JavaType::Double),
1976            };
1977            let desc = MethodDescriptor {
1978                args: vec![ty.clone(), ty],
1979                ret: JavaType::Int,
1980            };
1981            return Expr::Method {
1982                owner: None,
1983                cls: cls.into(),
1984                name: "compare".into(),
1985                desc: std::sync::Arc::new(desc),
1986                args: args.clone(),
1987                is_static: true,
1988                is_interface: false,
1989                is_special: false,
1990                is_super: false,
1991                is_dynamic: false,
1992                type_args: vec![],
1993            };
1994        }
1995    }
1996    e.clone()
1997}
1998
1999pub fn primitive_type(c: char) -> JavaType {
2000    match c {
2001        'Z' => JavaType::Boolean,
2002        'B' => JavaType::Byte,
2003        'C' => JavaType::Char,
2004        'S' => JavaType::Short,
2005        'F' => JavaType::Float,
2006        'J' => JavaType::Long,
2007        'D' => JavaType::Double,
2008        _ => JavaType::Int,
2009    }
2010}
2011
2012/// Constant elements from a fill-array-data payload, typed by width (the
2013/// consuming new-array's element type refines them later).
2014fn payload_consts(elem_width: u16, size: u32, data: &[u8]) -> Vec<Expr> {
2015    let n = (size as usize).min(data.len() / elem_width.max(1) as usize);
2016    let mut out = Vec::with_capacity(n);
2017    for i in 0..n {
2018        let off = i * elem_width as usize;
2019        let e = match elem_width {
2020            1 => Expr::Const(ConstVal::Int(data[off] as i8 as i32)),
2021            2 => {
2022                let v = i16::from_le_bytes([data[off], data[off + 1]]);
2023                Expr::Const(ConstVal::Int(v as i32))
2024            }
2025            4 => {
2026                let mut b = [0u8; 4];
2027                b.copy_from_slice(&data[off..off + 4]);
2028                Expr::Const(ConstVal::Int(i32::from_le_bytes(b)))
2029            }
2030            8 => {
2031                let mut b = [0u8; 8];
2032                b.copy_from_slice(&data[off..off + 8]);
2033                Expr::Const(ConstVal::Long(i64::from_le_bytes(b)))
2034            }
2035            _ => Expr::Const(ConstVal::Int(0)),
2036        };
2037        out.push(e);
2038    }
2039    out
2040}
2041
2042/// Entry register state from parameters. Returns the register state.
2043pub fn entry_regs(vt: &mut VarTable, env: &MethodEnv, param_names: &[Option<String>]) -> Vec<Reg> {
2044    let code = env.code;
2045    let n = code.registers_size as usize;
2046    let mut regs = vec![Reg::Undef; n.max(1)];
2047    let ins = code.ins_size.min(code.registers_size) as usize;
2048    let mut reg = n.saturating_sub(ins);
2049    let mut pidx = 0;
2050    if !env.is_static && reg < n {
2051        // `this` occupies the first incoming register.
2052        let id = vt.vars.len() as u32;
2053        vt.vars.push(VarInfo {
2054            id,
2055            slot: reg as u16,
2056            name: "this".into(),
2057            ty: TypeRef::J(JavaType::Object(env.class_name.as_str().into())),
2058            is_param: true,
2059            range_start: 0,
2060            range_end: u16::MAX,
2061            synthetic_name: false,
2062        });
2063        while vt.by_slot.len() <= reg {
2064            vt.by_slot.push(Vec::new());
2065        }
2066        vt.by_slot[reg].push((0, u16::MAX, id));
2067        regs[reg] = Reg::Live(id);
2068        reg += 1;
2069        pidx += 1;
2070    }
2071    for (i, arg) in env.desc.args.iter().enumerate() {
2072        if reg >= n {
2073            break;
2074        }
2075        let dbg = param_names.get(i).and_then(|o| o.clone());
2076        let named = dbg.is_some();
2077        // Debug-info names are ARBITRARY DEX strings — obfuscated apps
2078        // ship params named `25` (reqable a4/e: rendered `25 = 25;`, a
2079        // javac parse error). Run them through the same deterministic
2080        // sanitizer as every other declared identifier.
2081        let name = dbg
2082            .map(|d| crate::classdec::java_ident(&d).into_owned())
2083            .unwrap_or_else(|| format!("p{}", pidx));
2084        let id = vt.vars.len() as u32;
2085        vt.vars.push(VarInfo {
2086            id,
2087            slot: reg as u16,
2088            name,
2089            ty: TypeRef::J(arg.clone()),
2090            is_param: true,
2091            range_start: 0,
2092            range_end: u16::MAX,
2093            synthetic_name: !named,
2094        });
2095        while vt.by_slot.len() <= reg {
2096            vt.by_slot.push(Vec::new());
2097        }
2098        vt.by_slot[reg].push((0, u16::MAX, id));
2099        regs[reg] = Reg::Live(id);
2100        reg += if arg.is_wide() { 2 } else { 1 };
2101        pidx += 1;
2102    }
2103    regs
2104}