jdc_core/convert.rs
1//! Region tree → Stmt tree conversion.
2//!
3//! Responsibilities:
4//! * weave in per-block statements and terminals (return/throw),
5//! * resolve `Goto{target}` nodes against the enclosing loop/switch scope
6//! stack into `break` / `continue` / labeled goto,
7//! * classify loops into while / do-while / infinite forms,
8//! * assemble try/catch with exception parameter variables.
9
10use crate::fx::{FxHashMap as HashMap, FxHashSet as HashSet};
11
12use crate::cfg::Cfg;
13use crate::ir::build::{BlockResult, Term};
14use crate::ir::expr::{BinOp, ConstVal, Expr, UnOp};
15use crate::ir::stmt::{Catch, Stmt};
16use crate::structure::Region;
17
18/// A named Java statement for `break`/`continue` targets.
19#[derive(Debug)]
20pub enum Jump {
21 Break(Option<String>),
22 Continue(Option<String>),
23 /// Continue of the loop at the given depth-from-innermost, prefixed by
24 /// an emission of the target block's own statements (the jump re-runs
25 /// a shared statement-bearing tail that flows back into the header;
26 /// a bare Continue would skip those statements).
27 ContinueVia(usize, Option<String>),
28 /// Unstructured: emit `label:` + goto as comments (best effort).
29 RawGoto(usize),
30}
31
32#[derive(Debug)]
33struct LoopCtx {
34 header: usize,
35 exits: HashSet<usize>,
36 label: String,
37}
38
39#[derive(Debug)]
40struct SwitchCtx {
41 follow: Option<usize>,
42 label: String,
43 /// Loop-stack depth when the switch was entered: a `break` from a case
44 /// body only needs a label when the jump sits inside a loop that was
45 /// opened WITHIN the switch (an enclosing loop does not intercept it).
46 loops_depth: usize,
47}
48
49pub struct Converter<'a> {
50 pub cfg: &'a Cfg,
51 pub results: &'a Vec<BlockResult>,
52 pub groups: std::borrow::Cow<'a, [crate::structure::TryGroup]>,
53 /// Dominators over the full method graph (for goto fallback decisions).
54 pub dom: std::borrow::Cow<'a, crate::structure::DomInfo>,
55 /// Block whose statements are currently being converted (for postdom
56 /// checks in goto resolution).
57 cur_block: usize,
58 loops: Vec<LoopCtx>,
59 switches: Vec<SwitchCtx>,
60 /// Labels actually referenced by break/continue statements.
61 used_labels: HashSet<String>,
62 /// Follow block of each enclosing If region; a goto to the innermost
63 /// follow is natural structured flow and disappears.
64 if_follows: Vec<usize>,
65 label_counter: usize,
66 /// True while converting the last element of a Seq (a trailing Goto
67 /// there may be inlined as a copy instead of an unemittable jump).
68 goto_is_last: bool,
69 /// The block whose emission IMMEDIATELY follows the current position:
70 /// the innermost enclosing If's follow while converting its arms, or
71 /// the next Seq sibling's head. A RawGoto may elide to fallthrough
72 /// ONLY when its target is this block — the old stack-wide
73 /// `if_follows.contains` check elided jumps to OUTER follows whose
74 /// emission was separated by intervening follow/copy emissions
75 /// (jdk17 DatagramChannelImpl.receive: the b15 fall arm's Goto{SET}
76 /// elided into cur=14's follow emission, skipping
77 /// `sender = sourceSocketAddress()` on the n==0&&isOpen path;
78 /// sun.net.www.protocol.http HttpURLConnection.getInputStream0: the
79 /// clone arms' Goto{addToCache} fell into the post-loop tail — the
80 /// documented addToCache-skip residual).
81 expect_next: std::cell::Cell<Option<usize>>,
82 /// Set while converting a Seq element that DIRECTLY follows a
83 /// CopyStmts of that same block: the back-edge-stub pattern
84 /// [CopyStmts{b}, Goto{b}] already emitted b's statements, so the
85 /// Goto must not inline them again (jdk11 HttpURLConnection
86 /// getInputStream0: the clone tail rendered the clone/removeFromCache
87 /// block twice — the second removeFromCache removed the just-cloned
88 /// entry from the auth cache; a header-adjacent b would also make
89 /// ContinueVia re-emit b's statements after the copy).
90 prev_copy: std::cell::Cell<Option<usize>>,
91 /// Heads of copy-walked shared tails (from the structurer).
92 copied_tails: HashSet<usize>,
93 /// Collected label emissions: block target -> label name (for `Label` stmts).
94 pub pending_labels: HashMap<usize, String>,
95 /// Names of FINAL fields of the class being decompiled. A shared
96 /// terminator block whose statements write one of them must never be
97 /// inlined/copied at extra arrival sites: javac rejects a second
98 /// assignment to a final field (sun.security.util.Debug `hexDigits`).
99 final_fields: HashSet<String>,
100}
101
102/// Remove a trailing `Goto` whose target is the natural continuation.
103fn strip_trailing_goto(s: &mut Stmt, follow: Option<usize>) {
104 let Some(f) = follow else { return };
105 let items = match s {
106 Stmt::Block(v) => v,
107 Stmt::Goto(t) if *t as usize == f => {
108 *s = Stmt::Block(vec![]);
109 return;
110 }
111 _ => return,
112 };
113 // Single descent, no iteration: every arm either strips or stops
114 // (clippy::never_loop was right — this was a while-let in name
115 // only; `if let` states the actual control flow).
116 if let Some(last) = items.last_mut() {
117 match last {
118 Stmt::Goto(t) if *t as usize == f => {
119 items.pop();
120 }
121 Stmt::Block(inner) if !inner.is_empty() => {
122 // descend into the trailing block one level
123 let n = inner.len();
124 if matches!(inner[n - 1], Stmt::Goto(t) if t as usize == f) {
125 inner.pop();
126 }
127 }
128 _ => {}
129 }
130 }
131}
132
133impl<'a> Converter<'a> {
134 pub fn with_copied_tails(mut self, tails: HashSet<usize>) -> Self {
135 self.copied_tails = tails;
136 self
137 }
138
139 pub fn with_final_fields(mut self, finals: HashSet<String>) -> Self {
140 self.final_fields = finals;
141 self
142 }
143
144 /// True when any statement assigns a final field of this class.
145 fn stmts_write_final(&self, v: &[Stmt]) -> bool {
146 v.iter().any(|s| match s {
147 Stmt::ExprStmt(Expr::Assign { target, .. }) => {
148 matches!(&**target, Expr::Field { name, .. } if self.final_fields.contains(name.as_ref()))
149 }
150 _ => false,
151 })
152 }
153
154 /// Chain-aware twin of stmts_write_final for a tail HEAD: walks the
155 /// linear single-succ Fall/Goto chain (bounded) so a blank-final write
156 /// PAST the head still rejects the inline term-copy (URICertStore
157 /// clinit's two-field tail; mirrors structure's
158 /// terminator_writes_final chain probe).
159 fn tail_chain_writes_final(&self, t: usize) -> bool {
160 if self.final_fields.is_empty() {
161 return false;
162 }
163 let mut x = t;
164 let mut seen: HashSet<usize> = HashSet::default();
165 for _ in 0..8 {
166 if !seen.insert(x) {
167 return false;
168 }
169 if self.stmts_write_final(&self.results[x].stmts) {
170 return true;
171 }
172 if !matches!(self.results[x].term, Term::Fallthrough | Term::Goto) {
173 return false;
174 }
175 let succs = &self.cfg.blocks[x].succ;
176 if succs.len() != 1 {
177 return false;
178 }
179 x = succs[0];
180 }
181 false
182 }
183
184 pub fn new(cfg: &'a Cfg, results: &'a Vec<BlockResult>) -> Self {
185 let universe: HashSet<usize> = (0..cfg.blocks.len()).collect();
186 let dom = crate::structure::compute_dominators(cfg, &universe, cfg.entry);
187 let groups = crate::structure::group_exceptions_with(cfg, Some(results));
188 Self::from_parts(
189 cfg,
190 results,
191 std::borrow::Cow::Owned(groups),
192 std::borrow::Cow::Owned(dom),
193 )
194 }
195
196 /// `new` with the group set and dominator tree precomputed and shared
197 /// with the Structurer (see `Structurer::with_precomputed_groups`).
198 pub fn with_precomputed(
199 cfg: &'a Cfg,
200 results: &'a Vec<BlockResult>,
201 groups: Vec<crate::structure::TryGroup>,
202 dom: crate::structure::DomInfo,
203 ) -> Self {
204 Self::from_parts(
205 cfg,
206 results,
207 std::borrow::Cow::Owned(groups),
208 std::borrow::Cow::Owned(dom),
209 )
210 }
211
212 /// `with_precomputed` borrowing the shared groups/dominators instead
213 /// of taking clones: ddc computes both once per method and feeds the
214 /// SAME data to the Structurer and (per retry) the Converter — three
215 /// deep clones (groups twice, idom vec once) per method vanished.
216 pub fn with_precomputed_ref(
217 cfg: &'a Cfg,
218 results: &'a Vec<BlockResult>,
219 groups: &'a [crate::structure::TryGroup],
220 dom: &'a crate::structure::DomInfo,
221 ) -> Self {
222 Self::from_parts(
223 cfg,
224 results,
225 std::borrow::Cow::Borrowed(groups),
226 std::borrow::Cow::Borrowed(dom),
227 )
228 }
229
230 fn from_parts(
231 cfg: &'a Cfg,
232 results: &'a Vec<BlockResult>,
233 groups: std::borrow::Cow<'a, [crate::structure::TryGroup]>,
234 dom: std::borrow::Cow<'a, crate::structure::DomInfo>,
235 ) -> Self {
236 Converter {
237 cfg,
238 results,
239 groups,
240 dom,
241 cur_block: usize::MAX,
242 loops: Vec::new(),
243 switches: Vec::new(),
244 if_follows: Vec::new(),
245 used_labels: HashSet::default(),
246 label_counter: 0,
247 goto_is_last: false,
248 expect_next: std::cell::Cell::new(None),
249 prev_copy: std::cell::Cell::new(None),
250 copied_tails: HashSet::default(),
251 pending_labels: HashMap::default(),
252 final_fields: HashSet::default(),
253 }
254 }
255
256 fn next_label(&mut self) -> String {
257 self.label_counter += 1;
258 format!("L{}", self.label_counter)
259 }
260
261 fn groups_end(&self, gi: usize) -> Option<u32> {
262 self.groups.get(gi).map(|g| g.end)
263 }
264
265 pub fn convert(&mut self, r: Region) -> Stmt {
266 let mut st = self.conv(r);
267 prune_unused_labels(&mut st, &self.used_labels);
268 st
269 }
270
271 fn conv(&mut self, r: Region) -> Stmt {
272 match r {
273 Region::Empty => Stmt::Block(vec![]),
274 Region::Basic { block } => {
275 self.cur_block = block;
276 if crate::dbg_flag!("JCDC_DBG_BLOCKS") {
277 eprintln!(
278 "conv Basic {} ({} stmts)",
279 block,
280 self.results[block].stmts.len()
281 );
282 }
283 self.block_stmts(block)
284 }
285 Region::CopyStmts { block } => {
286 // Copies include the block's terminator when it is a
287 // return/throw (shared terminator blocks are inlined at
288 // every arrival site).
289 let mut v = self.results[block].stmts.clone();
290 match &self.results[block].term {
291 Term::Return(e) => v.push(Stmt::Return(e.clone())),
292 Term::Throw(e) => v.push(Stmt::Throw(e.clone())),
293 _ => {}
294 }
295 if v.len() == 1 {
296 v.into_iter().next().unwrap()
297 } else {
298 Stmt::Block(v)
299 }
300 }
301 Region::Seq(v) => {
302 let mut out = Vec::new();
303 let n = v.len();
304 let heads: Vec<usize> = v.iter().map(crate::structure::region_head_block).collect();
305 let prev_copies: Vec<Option<usize>> = (0..n)
306 .map(|k| {
307 if k > 0 {
308 match &v[k - 1] {
309 Region::CopyStmts { block } => Some(*block),
310 _ => None,
311 }
312 } else {
313 None
314 }
315 })
316 .collect();
317 for (k, x) in v.into_iter().enumerate() {
318 let save = self.goto_is_last;
319 self.goto_is_last = k + 1 == n;
320 let save_pc = self.prev_copy.get();
321 self.prev_copy.set(prev_copies[k]);
322 let save_exp = self.expect_next.get();
323 // Only override when the next emission is KNOWN: a
324 // headless tail (Goto/Empty — a jump out) must keep
325 // the inherited expectation, or a nested arm's Goto
326 // would elide against a phantom (jdk17 dci: Basic17's
327 // MAX head erased the follow expectation and Goto{16}
328 // elided past the SET).
329 if k + 1 < n && heads[k + 1] != usize::MAX {
330 self.expect_next.set(Some(heads[k + 1]));
331 }
332 out.push(self.conv(x));
333 self.expect_next.set(save_exp);
334 self.prev_copy.set(save_pc);
335 self.goto_is_last = save;
336 }
337 Stmt::Block(out)
338 }
339 Region::If {
340 block,
341 cond,
342 then_r,
343 else_r,
344 follow,
345 ternary,
346 } => {
347 self.cur_block = block;
348 let mut head = self.block_stmts_no_term(block);
349 if let Some((_tv, _fv)) = ternary {
350 // Pure value diamond: the folded conditional flows into
351 // the merge block's rebuilt input stack; nothing to emit
352 // here (branch blocks are statement-free by definition).
353 let _ = cond;
354 } else {
355 if let Some(f) = follow {
356 self.if_follows.push(f);
357 }
358 let save_exp = self.expect_next.get();
359 // follow=None keeps the inherited expectation: the
360 // flow leaving this If's arms continues to whatever
361 // follows the If itself.
362 self.expect_next.set(follow.or(save_exp));
363 let then_stmt = self.conv(*then_r);
364 let else_stmt = self.conv(*else_r);
365 self.expect_next.set(save_exp);
366 if follow.is_some() {
367 self.if_follows.pop();
368 }
369 let if_stmt = Stmt::If {
370 cond,
371 then_stmt: Box::new(then_stmt),
372 else_stmt: if else_stmt.is_empty_block() {
373 None
374 } else {
375 Some(Box::new(else_stmt))
376 },
377 };
378 head.push(if_stmt);
379 }
380 if head.len() == 1 {
381 head.pop().unwrap()
382 } else {
383 Stmt::Block(head)
384 }
385 }
386 Region::Loop {
387 header,
388 body,
389 members,
390 exits,
391 } => {
392 let label = self.next_label();
393 self.loops.push(LoopCtx {
394 header,
395 exits: exits.iter().copied().collect(),
396 label: label.clone(),
397 });
398 let body_stmt = self.conv(*body);
399 let ctx = self.loops.pop().unwrap();
400 let _ = members;
401 let mut st = self.classify_loop(header, body_stmt, ctx);
402 if crate::dbg_flag!("JCDC_DBG_LOOP") {
403 let kind = match &st {
404 Stmt::While { .. } => "While".to_string(),
405 Stmt::DoWhile { .. } => "DoWhile".to_string(),
406 Stmt::For { .. } => "For".to_string(),
407 Stmt::Block(b) => format!(
408 "Block{}[{}]",
409 b.len(),
410 b.iter()
411 .map(|x| match x {
412 Stmt::DoWhile { .. } => "DoWhile",
413 Stmt::While { .. } => "While",
414 Stmt::Break(_) => "Break",
415 Stmt::Return(_) => "Return",
416 _ => "_",
417 })
418 .collect::<Vec<_>>()
419 .join(",")
420 ),
421 Stmt::Labeled { .. } => "Labeled".to_string(),
422 _ => "Other".to_string(),
423 };
424 eprintln!("CLASSIFY-OUT header={} -> {}", header, kind);
425 }
426 // ALWAYS wrap; prune_unused_labels (post-convert) strips
427 // the wrapper when no break/continue ended up using it.
428 // Deciding at region-close missed breaks born in copied
429 // regions AFTER the loop popped (results[..].stmts
430 // clones / tail copies) — orphan `break L5` with no `L5:`
431 // (weixin 未定义的标签 ×687).
432 st = Stmt::Labeled {
433 label,
434 body: Box::new(st),
435 };
436 st
437 }
438 Region::Switch {
439 block,
440 selector,
441 cases,
442 default,
443 follow,
444 } => {
445 self.cur_block = block;
446 let sw_label = self.next_label();
447 self.switches.push(SwitchCtx {
448 follow,
449 label: sw_label.clone(),
450 loops_depth: self.loops.len(),
451 });
452 let mut case_groups = Vec::new();
453 for (vals, r) in cases {
454 let s = self.conv(r);
455 case_groups.push(crate::ir::stmt::CaseGroup {
456 labels: vals,
457 string_labels: vec![],
458 enum_labels: vec![],
459 raw_labels: vec![],
460 guard: None,
461 body: stmt_to_vec(s),
462 });
463 }
464 let default_stmt = default.map(|d| Box::new(self.conv(*d)));
465 self.switches.pop();
466 let mut head = self.block_stmts_no_term(block);
467 let mut sw = Stmt::Switch {
468 selector,
469 cases: case_groups,
470 default: default_stmt,
471 on_string: false,
472 };
473 {
474 sw = Stmt::Labeled {
475 label: sw_label,
476 body: Box::new(sw),
477 };
478 }
479 head.push(sw);
480 if head.len() == 1 {
481 head.pop().unwrap()
482 } else {
483 Stmt::Block(head)
484 }
485 }
486 Region::Try {
487 group_idx,
488 body,
489 catches,
490 } => {
491 let mut body_stmt = self.conv(*body);
492 // Natural exits of the try body / handlers jump to the block
493 // right after the try span; that is structured fallthrough.
494 let gend = self.groups_end(group_idx);
495 let try_follow = gend.and_then(|e| self.cfg.block_at(e));
496 strip_trailing_goto(&mut body_stmt, try_follow);
497 let mut catch_stmts = Vec::new();
498 for (tys, _hblock, r) in catches {
499 let mut s = self.conv(*r);
500 strip_trailing_goto(&mut s, try_follow);
501 catch_stmts.push(Catch {
502 exc: tys,
503 var: u32::MAX, // assigned by the method pipeline (handler store)
504 var_name: None,
505 body: Box::new(s),
506 });
507 }
508 Stmt::Try {
509 body: Box::new(body_stmt),
510 catches: catch_stmts,
511 finally: None,
512 }
513 }
514 Region::Goto { target } => {
515 if crate::dbg_flag!("JCDC_DBG_GOTO") {
516 eprintln!(
517 "conv Goto target={} cur_block={} loops={:?} switches={} if_follows={:?}",
518 target,
519 self.cur_block,
520 self.loops
521 .iter()
522 .map(|l| (l.header, l.exits.len()))
523 .collect::<Vec<_>>(),
524 self.switches.len(),
525 self.if_follows
526 );
527 }
528 // A jump to an enclosing if's follow that TERMINATES
529 // (return/throw) can be inlined: the copy ends this path
530 // exactly like the jump would, without needing a label.
531 // Same for a jump to a LOOP EXIT that heads a pure
532 // terminator chain (stmt-bearing fall-through links
533 // ending in return/throw): resolve_goto's loop-exit arm
534 // would turn it into a bare `break`, silently dropping
535 // the chain's statements between the loop end and the
536 // shared return (jdk26 Bits.reserveMemory phase-1:
537 // `if (interrupted) <goto interrupt-block>; ` rendered
538 // as else-break and the Thread.currentThread()
539 // .interrupt() vanished — interruption lost). The
540 // inlined copy keeps the abrupt ending (no fall-out
541 // duplication); a genuine fall-out exit still breaks.
542 //
543 let inline_terminator = self.if_follows.contains(&target)
544 && matches!(self.results[target].term, Term::Return(_) | Term::Throw(_))
545 && !self.tail_chain_writes_final(target);
546 if inline_terminator {
547 // Copy the WHOLE terminator chain: the target's own
548 // statements plus every fall-through link down to
549 // the final return/throw (a single-block chain is
550 // the original if-follow case).
551 let mut v: Vec<Stmt> = Vec::new();
552 let mut t = target;
553 let mut guard = 0;
554 loop {
555 v.extend(self.results[t].stmts.clone());
556 match &self.results[t].term {
557 Term::Return(e) => {
558 v.push(Stmt::Return(e.clone()));
559 break;
560 }
561 Term::Throw(e) => {
562 v.push(Stmt::Throw(e.clone()));
563 break;
564 }
565 Term::Fallthrough | Term::Goto
566 if self.cfg.blocks[t].succ.len() == 1 && guard < 8 =>
567 {
568 t = self.cfg.blocks[t].succ[0];
569 guard += 1;
570 }
571 _ => break,
572 }
573 }
574 return if v.len() == 1 {
575 v.into_iter().next().unwrap()
576 } else {
577 Stmt::Block(v)
578 };
579 }
580 if let Some(j) = self.resolve_goto(target) {
581 match j {
582 Jump::Break(lbl) => {
583 if let Some(l) = &lbl {
584 self.used_labels.insert(l.clone());
585 }
586 Stmt::Break(lbl)
587 }
588 Jump::Continue(lbl) => {
589 if let Some(l) = &lbl {
590 self.used_labels.insert(l.clone());
591 }
592 Stmt::Continue(lbl)
593 }
594 Jump::ContinueVia(t, lbl) => {
595 if let Some(l) = &lbl {
596 self.used_labels.insert(l.clone());
597 }
598 let mut cv = if self.prev_copy.get() == Some(t) {
599 // Statements already emitted by the
600 // immediately preceding CopyStmts.
601 Vec::new()
602 } else {
603 self.results[t].stmts.clone()
604 };
605 cv.push(Stmt::Continue(lbl));
606 if cv.len() == 1 {
607 cv.into_iter().next().unwrap()
608 } else {
609 Stmt::Block(cv)
610 }
611 }
612 Jump::RawGoto(t) => {
613 if crate::dbg_flag!("JCDC_DBG_GOTO") {
614 eprintln!(
615 "RAWGOTO t={} copied_tails={:?} if_follows={:?} last={}",
616 t, self.copied_tails, self.if_follows, self.goto_is_last
617 );
618 }
619 // A Goto region is always the last part of its
620 // walk, so the jump either falls through to the
621 // enclosing merge or must be inlined.
622 let term_copy =
623 matches!(self.results[t].term, Term::Return(_) | Term::Throw(_))
624 && !self.tail_chain_writes_final(t)
625 && !self.is_retry_loop_header(t);
626 if term_copy {
627 let mut cv = self.results[t].stmts.clone();
628 match &self.results[t].term {
629 Term::Return(e) => cv.push(Stmt::Return(e.clone())),
630 Term::Throw(e) => cv.push(Stmt::Throw(e.clone())),
631 _ => {}
632 }
633 if cv.len() == 1 {
634 cv.into_iter().next().unwrap()
635 } else {
636 Stmt::Block(cv)
637 }
638 } else if self
639 .loops
640 .iter()
641 .any(|l| l.exits.contains(&t) || l.header == t)
642 && (self.goto_is_last || self.if_follows.contains(&t))
643 {
644 // The target is an ENCLOSING LOOP's exit:
645 // inside a loop body, falling out of an if
646 // continues the LOOP — the if-follow
647 // elision would silently drop the jump
648 // (jdk11 ObjectInputStream.readSerialData's
649 // finally-copy retry loop lost its `break`,
650 // the finally's while(true) never completed
651 // normally, and the tail went unreachable —
652 // 无法访问的语句 x2 trees). Materialize the
653 // break (innermost enclosing loop).
654 Stmt::Break(None)
655 } else if !matches!(
656 self.results[t].term,
657 Term::Return(_) | Term::Throw(_)
658 ) && !self.results[t].stmts.is_empty()
659 && !self.copied_tails.contains(&t)
660 && self.prev_copy.get() != Some(t)
661 && self
662 .expect_next
663 .get()
664 .map(|nx| {
665 // The next emission is a copy that
666 // STARTS PAST t (at a successor of t
667 // already in copied_tails): eliding
668 // would silently skip t's own
669 // statements, and no emitted copy
670 // covers them. (sj17 receive:
671 // Goto{16=SET}, expect=Some(17),
672 // 17 copied, 16 not.) If t itself is
673 // in copied_tails, an emitted full
674 // copy already includes t's stmts —
675 // inlining would double-emit (w26
676 // receive: Goto{14}, 14 copied).
677 let mut x = t;
678 for _ in 0..8 {
679 if x == nx {
680 return x != t;
681 }
682 if self.copied_tails.contains(&x) {
683 return false;
684 }
685 match self.cfg.blocks[x].succ.first() {
686 Some(&n) => x = n,
687 None => return false,
688 }
689 }
690 false
691 })
692 .unwrap_or(false)
693 && (self
694 .if_follows
695 .iter()
696 .any(|f| self.cfg.blocks[t].succ.contains(f)))
697 {
698 // Statement-bearing target FIRST: eliding
699 // (goto_is_last / expect / copy-tail) would
700 // silently skip t's own statements when the
701 // next emission is a copy of t's SUCCESSOR
702 // rather than t itself (jdk17
703 // DatagramChannelImpl.receive: Goto{16=
704 // `sender = sourceSocketAddress()`} elided
705 // via reaches_copy_tail(16->17) into the
706 // arm's Basic(17) copy — the n==0&&isOpen
707 // path returned a null sender). The inline
708 // below emits t's statements and then falls
709 // through to the same continuation.
710 let cv = self.results[t].stmts.clone();
711 if cv.len() == 1 {
712 cv.into_iter().next().unwrap()
713 } else {
714 Stmt::Block(cv)
715 }
716 } else if self.goto_is_last
717 || self.expect_next.get() == Some(t)
718 || self.reaches_copy_tail(t)
719 {
720 // Natural fallthrough reaches the same
721 // continuation the jump targeted.
722 Stmt::Block(vec![])
723 } else if !matches!(
724 self.results[t].term,
725 Term::Return(_) | Term::Throw(_)
726 ) && self.prev_copy.get() != Some(t)
727 && (self
728 .if_follows
729 .iter()
730 .any(|f| self.cfg.blocks[t].succ.contains(f)))
731 {
732 // The jump re-enters an already-structured
733 // block whose flow ends at an enclosing
734 // if-follow: inline its statements; the
735 // natural continuation matches the jump's.
736 let cv = self.results[t].stmts.clone();
737 if cv.len() == 1 {
738 cv.into_iter().next().unwrap()
739 } else {
740 Stmt::Block(cv)
741 }
742 } else {
743 Stmt::Goto(t as u32)
744 }
745 }
746 }
747 } else {
748 Stmt::Block(vec![])
749 }
750 }
751 }
752 }
753
754 /// Statements of a block including its terminal (return/throw), but NOT
755 /// the structural terminals (cond/switch/goto — handled by regions).
756 fn block_stmts(&mut self, block: usize) -> Stmt {
757 let mut v = self.block_stmts_no_term(block);
758 match &self.results[block].term {
759 Term::Return(e) => v.push(Stmt::Return(e.clone())),
760 Term::Throw(e) => v.push(Stmt::Throw(e.clone())),
761 Term::Jsr | Term::Ret => v.push(Stmt::Comment("// jsr/ret not supported".into())),
762 _ => {}
763 }
764 if v.len() == 1 {
765 v.pop().unwrap()
766 } else {
767 Stmt::Block(v)
768 }
769 }
770
771 fn block_stmts_no_term(&self, block: usize) -> Vec<Stmt> {
772 // Monitor markers are kept; synchronized reconstruction happens later.
773 self.results[block].stmts.clone()
774 }
775
776 /// Resolve a goto target against the scope stack.
777 fn resolve_goto(&mut self, target: usize) -> Option<Jump> {
778 // continue: innermost loop whose header == target
779 if let Some(i) = (0..self.loops.len())
780 .rev()
781 .find(|&i| self.loops[i].header == target)
782 {
783 let depth = self.loops.len() - 1 - i;
784 return Some(if depth == 0 {
785 Jump::Continue(None)
786 } else {
787 Jump::Continue(Some(self.loops[i].label.clone()))
788 });
789 }
790 // break out of a loop whose exit set contains the target; pick the
791 // OUTERMOST such loop — an exit of nested loops (e.g. `break outer`)
792 // belongs to every enclosing loop's exit set, and breaking only the
793 // innermost would wrongly re-enter the outer loop.
794 if let Some(li) = (0..self.loops.len()).find(|&i| self.loops[i].exits.contains(&target)) {
795 // RESTART-STUB exit: the target chains through statement-free
796 // stubs back into an enclosing-or-self loop HEADER — the jump
797 // re-iterates THAT loop, it does not break out of anything
798 // (jdk11/17/26 ConcurrentLinkedQueue.poll's p==q arm `goto
799 // restartFromHead`: exit 12 is the `goto 0` stub; rendering
800 // break+break fell to the post-loop tail and returned the
801 // STALE item instead of restarting from head). The broad
802 // walk-side continue-stub precedence was reverted once
803 // (Pattern.clazz: switch-case goto stubs must stay
804 // RawGoto-elided so the emitter re-appends case breaks) —
805 // this form is scoped to genuine loop exits with no open
806 // switch on the stack.
807 if self.switches.is_empty() {
808 let mut x = target;
809 let mut guard = 0;
810 let header_hit = loop {
811 if let Some(hi) = self.loops.iter().position(|l| l.header == x) {
812 if hi <= li {
813 break Some(hi);
814 }
815 }
816 if guard >= 8 {
817 break None;
818 }
819 let r = &self.results[x];
820 let stub = r.stmts.is_empty()
821 && r.out_stack.is_empty()
822 && matches!(r.term, Term::Fallthrough | Term::Goto)
823 && self.cfg.blocks[x].succ.len() == 1;
824 if !stub {
825 break None;
826 }
827 x = self.cfg.blocks[x].succ[0];
828 guard += 1;
829 };
830 if let Some(hi) = header_hit {
831 let depth = self.loops.len() - 1 - hi;
832 return Some(if depth == 0 {
833 Jump::Continue(None)
834 } else {
835 Jump::Continue(Some(self.loops[hi].label.clone()))
836 });
837 }
838 }
839 // switches opened after that loop intercept a plain `break`
840 let crosses_switch = !self.switches.is_empty();
841 return Some(if li + 1 == self.loops.len() && !crosses_switch {
842 Jump::Break(None)
843 } else {
844 Jump::Break(Some(self.loops[li].label.clone()))
845 });
846 }
847 if let Some(si) = (0..self.switches.len())
848 .rev()
849 .find(|&i| self.switches[i].follow == Some(target))
850 {
851 return Some(
852 if si + 1 == self.switches.len()
853 && self.loops.len() == self.switches[si].loops_depth
854 {
855 Jump::Break(None)
856 } else {
857 Jump::Break(Some(self.switches[si].label.clone()))
858 },
859 );
860 }
861 // Natural flow to the enclosing if's merge point: no statement.
862 // Only the INNERMOST open follow qualifies — eliding a jump to an
863 // outer follow would silently skip the statements between (e.g. a
864 // shared throw at the end of an else-branch).
865 if self.if_follows.last() == Some(&target) {
866 return None;
867 }
868 // Inside a loop, a jump to an already-structured block that flows
869 // back into the loop is a CONTINUE of the innermost such loop: the
870 // target's statements were emitted earlier in this body, and the
871 // natural continuation after this region is the loop bottom (an
872 // if-follow or a fall-out exit), never the target. Eliding it as
873 // fallthrough (the RawGoto `goto_is_last` arm) silently dropped the
874 // iteration: jdk11/17 InstantPrinterParser.format's second loop
875 // copy emitted `if (i >= fractionalDigits) {}` with no way out --
876 // the digit append + back edge vanished (semantically an infinite
877 // loop; javac: 缺少返回语句 on the method tail).
878 // A target that is a loop EXIT keeps its RawGoto resolution (the
879 // conv arm materializes the break): Pattern.clazz's switch-case
880 // `break` targets sit on the loop-bottom path AND name exits —
881 // continuing there made every switch exit abrupt and the post-
882 // switch tail unreachable (无法访问的语句 x3 trees).
883 let is_any_exit = self.loops.iter().any(|l| l.exits.contains(&target));
884 if !is_any_exit && self.switches.is_empty() {
885 // STUB-TARGET continue: a statement-free confluence stub that
886 // can reach an enclosing header re-iterates that loop (its own
887 // flow was emitted earlier in this body copy; IPP's can_reach
888 // targets t=43/18/96/89/114/21/7 are all stubs).
889 // HEADER-ADJACENT statement-bearing target: the jump re-runs a
890 // shared tail whose statements were NOT emitted on this path —
891 // inline them and continue (jdk11 BigInteger.nextProbablePrime
892 // sieve arms: Goto{result=result.add(TWO)} flowing straight to
893 // the header; a bare Continue skipped the advance and left
894 // while(true) as the method's only completion: 缺少返回语句).
895 // Statement-bearing targets with a BRANCHING or statement
896 // bearing chain to the header keep RawGoto resolution (huc
897 // getInputStream0's clone/getValue tails flow through shared
898 // forward code — continuing there would skip it).
899 let mut via_label: Option<Option<String>> = None;
900 if self.results[target].stmts.is_empty() {
901 if let Some(i) = (0..self.loops.len()).rev().find(|&i| {
902 crate::structure::can_reach_cfg(self.cfg, target, self.loops[i].header, 4096)
903 }) {
904 let depth = self.loops.len() - 1 - i;
905 via_label = Some(if depth == 0 {
906 None
907 } else {
908 Some(self.loops[i].label.clone())
909 });
910 }
911 } else {
912 let mut x = target;
913 for _ in 0..8 {
914 if let Some(hi) = self.loops.iter().position(|l| l.header == x) {
915 let depth = self.loops.len() - 1 - hi;
916 via_label = Some(if depth == 0 {
917 None
918 } else {
919 Some(self.loops[hi].label.clone())
920 });
921 break;
922 }
923 if !self.results[x].stmts.is_empty() && x != target {
924 break;
925 }
926 if self.cfg.blocks[x].succ.len() != 1 {
927 break;
928 }
929 x = self.cfg.blocks[x].succ[0];
930 }
931 }
932 if let Some(lbl) = via_label {
933 return Some(if self.results[target].stmts.is_empty() {
934 Jump::Continue(lbl)
935 } else {
936 Jump::ContinueVia(target, lbl)
937 });
938 }
939 }
940 // Inside a loop, a forward escape that cannot reach back into the
941 // loop is a break of the innermost loop.
942 if !self.loops.is_empty()
943 && !crate::structure::can_reach_cfg(
944 self.cfg,
945 target,
946 self.loops[self.loops.len() - 1].header,
947 4096,
948 )
949 {
950 return Some(Jump::Break(None));
951 }
952 // Unstructured jump.
953 Some(Jump::RawGoto(target))
954 }
955
956 /// True if `a` post-dominates `b` (every path from b exits through a).
957 /// True when a jump to `t` is equivalent to natural fallthrough: `t`
958 /// (or the end of a chain of statement-free blocks starting at `t`) is
959 /// a copied shared tail or an open if-follow that the enclosing flow
960 /// will emit next anyway.
961 /// True when `t` is the head of a javac retry loop: some exception
962 /// handler protecting `t` has no normal preds and flows straight back
963 /// to `t` (`catch (InterruptedException e) { ..; goto head }`). A Goto
964 /// to such a header re-executes the protected body — inlining the
965 /// body's terminator as a "shared tail copy" drops it out of its try
966 /// (jdk26 Future.exceptionNow: the IE catch got `get(); throw ISE`
967 /// unprotected — 未报告的异常错误 InterruptedException).
968 fn is_retry_loop_header(&self, t: usize) -> bool {
969 self.cfg.exc_edges.iter().any(|e| {
970 e.from == t
971 && e.to != t
972 && self.cfg.blocks[e.to].pred.is_empty()
973 && self.cfg.blocks[e.to].succ.len() == 1
974 && self.cfg.blocks[e.to].succ[0] == t
975 })
976 }
977
978 fn reaches_copy_tail(&self, t: usize) -> bool {
979 let mut x = t;
980 for _ in 0..8 {
981 if self.copied_tails.contains(&x) || self.if_follows.contains(&x) {
982 return true;
983 }
984 if !self.results[x].stmts.is_empty() {
985 return false;
986 }
987 match &self.results[x].term {
988 Term::Fallthrough | Term::Goto => match self.cfg.blocks[x].succ.first() {
989 Some(&n) => x = n,
990 None => return false,
991 },
992 _ => return false,
993 }
994 }
995 false
996 }
997
998 #[allow(dead_code)]
999 fn postdominates(&self, a: usize, b: usize, universe: &HashSet<usize>) -> bool {
1000 // BFS from b avoiding a; if no exit block is reachable, a post-dominates.
1001 let mut seen = HashSet::default();
1002 let mut q = std::collections::VecDeque::new();
1003 q.push_back(b);
1004 seen.insert(b);
1005 while let Some(x) = q.pop_front() {
1006 for &s in &self.cfg.blocks[x].succ {
1007 if s == a {
1008 continue;
1009 }
1010 if !universe.contains(&s) {
1011 continue;
1012 }
1013 if seen.insert(s) {
1014 q.push_back(s);
1015 }
1016 }
1017 if self.cfg.blocks[x].succ.is_empty() && x != a && x != b {
1018 // reached an exit without passing through a
1019 return false;
1020 }
1021 }
1022 // also treat blocks leaving the universe as exits
1023 true
1024 }
1025
1026 /// Classify a loop region into while / do-while / infinite and assemble
1027 /// the final statement.
1028 fn classify_loop(&mut self, header: usize, body_stmt: Stmt, ctx: LoopCtx) -> Stmt {
1029 let term = self.results[header].term.clone();
1030 let succs = self.cfg.blocks[header].succ.clone();
1031
1032 match term {
1033 Term::Cond { cond } if succs.len() == 2 => {
1034 let taken = succs[1];
1035 let fall = succs[0];
1036 if taken == header && ctx.exits.contains(&fall) {
1037 // Self-loop: the header block holds both the body and
1038 // the trailing conditional back edge → do-while. The
1039 // fallthrough side is the loop exit. (When the fall
1040 // side is INTERIOR the self-edge is an in-body retry
1041 // jump of a loop with no normal completion at all —
1042 // rotating it into a do-while bottom invents an exit
1043 // path: jdk11/17/26 DSAParameterGenerator.generatePandQ's
1044 // `if (!resultQ.isProbablePrime(..)) goto <Q-gen>`
1045 // self-retry falls through into the P-search interior;
1046 // the fabricated do-while fell out to the method end —
1047 // 缺少返回语句. Those shapes take the interior-diamond
1048 // while(true) arm below.)
1049 // A compound (multi-test) trailing condition folds first:
1050 // `if(c1)continue; .. if(cN)continue; else exit;` becomes
1051 // `do{body}while(c1||..||cN); exit`.
1052 if let Some((stmts, c, exit)) = extract_compound_do_while(&body_stmt) {
1053 // An extracted exit that is the loop's OWN unlabeled
1054 // break must be dropped: the do-while condition false
1055 // already exits, and re-emitting the break OUTSIDE the
1056 // loop is a stray `break;` (compile error). SESE's
1057 // explicit `Goto{header}` -> continue makes self-loop
1058 // bodies hit this shape (`if (c) continue; else break;`).
1059 // return/throw/labeled-break exits stay (real fall-out).
1060 if matches!(exit, Stmt::Break(None)) {
1061 return Stmt::DoWhile {
1062 body: Box::new(Stmt::Block(stmts)),
1063 cond: c,
1064 };
1065 }
1066 return Stmt::Block(vec![
1067 Stmt::DoWhile {
1068 body: Box::new(Stmt::Block(stmts)),
1069 cond: c,
1070 },
1071 exit,
1072 ]);
1073 }
1074 let (stmts, c) = match extract_trailing_do_while(&body_stmt) {
1075 Some(x) => x,
1076 None => (stmt_to_vec(body_stmt), cond.clone()),
1077 };
1078 return Stmt::DoWhile {
1079 body: Box::new(Stmt::Block(stmts)),
1080 cond: c,
1081 };
1082 }
1083 if fall == header && ctx.exits.contains(&taken) {
1084 // Inverted self-loop: `while (!(c)) body` — the taken
1085 // side exits, the fallthrough loops back.
1086 let inner2 = strip_trailing_continue(body_stmt);
1087 return Stmt::While {
1088 cond: negate(cond.clone()),
1089 body: Box::new(inner2),
1090 };
1091 }
1092 let taken_is_exit = ctx.exits.contains(&taken);
1093 if crate::dbg_flag!("JCDC_DBG_LOOP") {
1094 eprintln!(
1095 "CLASSIFY2 header={} taken={} fall={} exits={:?}",
1096 header, taken, fall, ctx.exits
1097 );
1098 }
1099 if !taken_is_exit && !ctx.exits.contains(&fall) {
1100 // Multi-block loop condition. The header's fallthrough
1101 // may be a pure condition-continuation test block whose
1102 // taken side is the loop exit and whose fall side rejoins
1103 // the body (`taken`). javac compiles `while (cH || !cB)`
1104 // exactly this way:
1105 // H: if cH goto body; B: if cB goto exit; body: ..; goto H
1106 // Fold B into the while condition. Without this the body
1107 // walk re-emits H and B as empty `if`s inside a
1108 // `while(true)`, dropping the exit and leaving an infinite
1109 // loop plus an unreachable trailing statement.
1110 if self.results[fall].stmts.is_empty() {
1111 if let Term::Cond { cond: cb } = &self.results[fall].term {
1112 let bs = self.cfg.blocks[fall].succ.clone();
1113 if bs.len() == 2 && ctx.exits.contains(&bs[1]) && bs[0] == taken {
1114 let combined = Expr::Bin {
1115 op: BinOp::LogOr,
1116 l: Box::new(cond.clone()),
1117 r: Box::new(negate(cb.clone())),
1118 ty: None,
1119 };
1120 // The body is the converted region
1121 // remainder, NOT the taken block's raw
1122 // statements: when `taken` is wrapped in
1123 // regions (a try/catch group around the
1124 // body call), the raw-stmt body silently
1125 // drops them (jdk11 SocketChannelImpl
1126 // .implCloseSelectableChannel: the
1127 // wait()-loop's try/catch(Interrupted
1128 // Exception) region vanished — bare
1129 // wait() — 未报告的异常错误). The
1130 // leading guard If is the condition being
1131 // folded here; strip it and keep the rest.
1132 let mut parts = stmt_to_vec(body_stmt);
1133 if matches!(parts.first(), Some(Stmt::If { .. })) {
1134 parts.remove(0);
1135 }
1136 let body = if parts.is_empty() {
1137 Stmt::Block(self.results[taken].stmts.clone())
1138 } else {
1139 let rest = if parts.len() == 1 {
1140 parts.pop().unwrap()
1141 } else {
1142 Stmt::Block(parts)
1143 };
1144 strip_trailing_continue(rest)
1145 };
1146 if crate::dbg_flag!("JCDC_DBG_LOOP") {
1147 eprintln!(
1148 "CLASSIFY-CONDCHAIN header={} B={} body={} exits={:?}",
1149 header, fall, taken, ctx.exits
1150 );
1151 }
1152 return Stmt::While {
1153 cond: combined,
1154 body: Box::new(body),
1155 };
1156 }
1157 }
1158 }
1159 // Neither successor leaves the loop: the header's Cond
1160 // is an interior diamond (e.g. a ternary inside an
1161 // infinite `for(;;)` whose back edge targets the header
1162 // top), not an exit test. Keep it in the body.
1163 return Stmt::While {
1164 cond: Expr::Const(ConstVal::Int(1)),
1165 body: Box::new(body_stmt),
1166 };
1167 }
1168 // The body walk re-emitted the header's own If region; unwrap
1169 // it so the loop reads `while (C) { else-part }`.
1170 let (inner, exit_stmts) = split_leading_if(&body_stmt, &cond);
1171 // A top test the structurer wrapped in a TRY (the header
1172 // block sits inside its handler's protected range — jdk26
1173 // Bits.reserveMemory's backoff retry loop tests
1174 // tryReserveOrClean(..) throws InterruptedException under
1175 // its own catch(IE) retry handler): rotating the test into
1176 // `while (C)` evaluates the call OUTSIDE every handler —
1177 // 未报告的异常错误InterruptedException. split_leading_if
1178 // deliberately cannot reach through the Try (the rotated
1179 // cond would still be unprotected), so keep the test where
1180 // the bytecode has it and stay on while(true). The earlier
1181 // implCloseSelectableChannel guard (raw-stmt bodies losing
1182 // the leading If's statements) does not apply: the If lives
1183 // intact inside the Try.
1184
1185 if crate::dbg_flag!("JCDC_DBG_LOOP") {
1186 eprintln!(
1187 "CLASSIFY header={} taken_is_exit={} exit_stmts={}",
1188 header,
1189 taken_is_exit,
1190 exit_stmts.len()
1191 );
1192 }
1193 let inner = strip_trailing_continue(inner);
1194 let while_cond = if taken_is_exit {
1195 negate(cond.clone())
1196 } else {
1197 cond.clone()
1198 };
1199 let plain_exit = exit_stmts.is_empty()
1200 || matches!(exit_stmts.as_slice(), [Stmt::Break(_)])
1201 || matches!(exit_stmts.as_slice(), [Stmt::Block(b)] if b.is_empty());
1202 if taken_is_exit && plain_exit {
1203 match try_protected_dowhile(inner, &cond) {
1204 Ok(dw) => dw,
1205 Err(inner) => Stmt::While {
1206 cond: while_cond,
1207 body: Box::new(inner),
1208 },
1209 }
1210 } else if taken_is_exit {
1211 // Exit branch runs statements before leaving:
1212 // while (true) { if (C_exit) { stmts; break; } body }
1213 // `cond` IS the exit test here (the taken side exits —
1214 // negate(cond) inverted the guard: jdk17 CHM
1215 // comparableClassFor emitted `if (i < len) return null`
1216 // inside while(true), inverting the loop). The break is
1217 // only appended when the exit statements do not already
1218 // terminate (return null + break = unreachable stmt).
1219 let mut ex = exit_stmts;
1220 let already_term = matches!(
1221 ex.last(),
1222 Some(Stmt::Return(_)) | Some(Stmt::Throw(_)) | Some(Stmt::Break(_))
1223 );
1224 if !already_term {
1225 ex.push(Stmt::Break(None));
1226 }
1227 let guard = Stmt::If {
1228 cond: cond.clone(),
1229 then_stmt: Box::new(Stmt::Block(ex)),
1230 else_stmt: None,
1231 };
1232 let mut v = vec![guard];
1233 v.extend(stmt_to_vec(inner));
1234 Stmt::While {
1235 cond: Expr::Const(ConstVal::Int(1)),
1236 body: Box::new(Stmt::Block(v)),
1237 }
1238 } else {
1239 // Unusual orientation: the fallthrough side exits.
1240 if exit_stmts.is_empty()
1241 || matches!(exit_stmts.as_slice(), [Stmt::Break(_)])
1242 || matches!(exit_stmts.as_slice(), [Stmt::Block(b)] if b.is_empty())
1243 {
1244 // then-side was the exit scaffolding; body is `inner`
1245 match try_protected_dowhile(inner, &cond) {
1246 Ok(dw) => dw,
1247 Err(inner) => Stmt::While {
1248 cond: while_cond,
1249 body: Box::new(inner),
1250 },
1251 }
1252 } else {
1253 // then-side carries the body ending with the back
1254 // edge; fallthrough exits.
1255 let body2 = strip_trailing_continue(stmts_to_stmt(exit_stmts));
1256 Stmt::While {
1257 cond: while_cond,
1258 body: Box::new(body2),
1259 }
1260 }
1261 }
1262 }
1263 Term::Goto | Term::Fallthrough => {
1264 // Possibly do-while: the body ends with a conditional jump
1265 // back to the header (`if (c) continue;` or inverted), or a
1266 // COMPOUND run of such tests ending in the loop exit.
1267 if let Some((stmts, c, exit)) = extract_compound_do_while(&body_stmt) {
1268 // Same guard as the self-loop compound path above: an
1269 // extracted exit that is the loop's OWN unlabeled break
1270 // must be dropped — the do-while condition false already
1271 // exits, and a `break;` re-emitted OUTSIDE the loop is a
1272 // stray (it also makes stmt_terminates treat the sequence
1273 // as terminated, so prune_unreachable drops the real
1274 // tail: jdk26 Resolver.bind `return this` — 缺少返回语句).
1275 // SESE's rotated do-whiles hit this shape: the tail test
1276 // block becomes `if (c) continue; else break;`.
1277 // return/throw/labeled-break exits stay (real fall-out).
1278 if matches!(exit, Stmt::Break(None)) {
1279 return Stmt::DoWhile {
1280 body: Box::new(Stmt::Block(stmts)),
1281 cond: c,
1282 };
1283 }
1284 return Stmt::Block(vec![
1285 Stmt::DoWhile {
1286 body: Box::new(Stmt::Block(stmts)),
1287 cond: c,
1288 },
1289 exit,
1290 ]);
1291 }
1292 if let Some((stmts, c)) = extract_trailing_do_while(&body_stmt) {
1293 return Stmt::DoWhile {
1294 body: Box::new(Stmt::Block(stmts)),
1295 cond: c,
1296 };
1297 }
1298 Stmt::While {
1299 cond: Expr::Const(ConstVal::Int(1)),
1300 body: Box::new(body_stmt),
1301 }
1302 }
1303 _ => Stmt::While {
1304 cond: Expr::Const(ConstVal::Int(1)),
1305 body: Box::new(body_stmt),
1306 },
1307 }
1308 }
1309
1310 /// True if `target` is inside the loop currently being classified
1311 /// (approximated: target can reach the header again).
1312 #[allow(dead_code)]
1313 fn loop_contains(&self, header: usize, target: usize) -> bool {
1314 can_reach(self.cfg, target, header, 8192)
1315 }
1316
1317 #[allow(dead_code)]
1318 fn loop_exit_contains(&self, header: usize, target: usize) -> bool {
1319 // The loop currently being classified is the innermost on the stack
1320 // BEFORE it was popped; ctx.exits was consumed. Recompute cheaply:
1321 // target is an exit if it is not reachable-back-to-header within the
1322 // loop members — approximated by checking the parent scope recorded
1323 // in loops stack is empty here; use cfg: header's own successors that
1324 // leave... For the header itself, an exit is any successor that is
1325 // not dominated by header OR is not in the natural loop. Simple
1326 // approximation: a successor s is "in loop" if s can reach header
1327 // again via normal edges.
1328 can_reach(self.cfg, target, header, 4096).not()
1329 }
1330}
1331
1332#[allow(dead_code)]
1333trait NotExt {
1334 fn not(self) -> bool;
1335}
1336impl NotExt for bool {
1337 fn not(self) -> bool {
1338 !self
1339 }
1340}
1341
1342#[allow(dead_code)]
1343fn can_reach(cfg: &Cfg, from: usize, to: usize, budget: usize) -> bool {
1344 if from == to {
1345 return true;
1346 }
1347 let mut seen = HashSet::default();
1348 let mut q = std::collections::VecDeque::new();
1349 q.push_back(from);
1350 seen.insert(from);
1351 let mut n = 0;
1352 while let Some(b) = q.pop_front() {
1353 n += 1;
1354 if n > budget {
1355 return false;
1356 }
1357 for &s in &cfg.blocks[b].succ {
1358 if s == to {
1359 return true;
1360 }
1361 if seen.insert(s) {
1362 q.push_back(s);
1363 }
1364 }
1365 }
1366 false
1367}
1368
1369/// If the body starts with the loop header's own `If` (same condition
1370/// expression), return (else-branch content, then-branch content).
1371/// Otherwise return (body, []).
1372fn stmts_to_stmt(v: Vec<Stmt>) -> Stmt {
1373 match v.len() {
1374 0 => Stmt::Block(vec![]),
1375 1 => v.into_iter().next().unwrap(),
1376 _ => Stmt::Block(v),
1377 }
1378}
1379
1380/// When the loop's top test lives inside a Try in `inner` (the header
1381/// block sits in its handler's protected range — jdk26
1382/// Bits.reserveMemory's backoff retry loop tests
1383/// `tryReserveOrClean(..) throws InterruptedException` under its own
1384/// catch(IE) handler), the `while (C)` rotation would evaluate C
1385/// OUTSIDE every handler — 未报告的异常错误InterruptedException.
1386/// Rewrite as a do-while instead: inject `break` into the embedded
1387/// If's EMPTY arm (the exit side — the exit blocks live outside the
1388/// loop region as its continuation siblings, so the empty arm is the
1389/// fall-out) and loop unconditionally. The sibling tail then stays
1390/// reachable as the do-while's natural completion. Returns None when
1391/// the test is not try-wrapped (plain rotation applies) or when the
1392/// shape is ambiguous (both If arms materialized).
1393// The Err payload IS the statement being rejected — boxing it would
1394// churn every call site for a cold path.
1395#[allow(clippy::result_large_err)]
1396fn try_protected_dowhile(inner: Stmt, cond: &Expr) -> Result<Stmt, Stmt> {
1397 // The exit side of the embedded test: an Empty region conversion
1398 // (empty block / missing else) or an ALREADY-materialized plain
1399 // `break` (the merged-span shape walks the sleep region as the
1400 // then-arm and breaks on the exit side directly).
1401 fn is_empty(s: &Stmt) -> bool {
1402 match s {
1403 Stmt::Block(v) => v.is_empty() || (v.len() == 1 && is_empty(&v[0])),
1404 Stmt::Break(None) => false,
1405 _ => false,
1406 }
1407 }
1408 fn inject(s: &mut Stmt, cond: &Expr) -> bool {
1409 match s {
1410 Stmt::If {
1411 cond: c,
1412 then_stmt,
1413 else_stmt,
1414 } if c == cond => {
1415 let then_empty = is_empty(then_stmt);
1416 let else_empty = else_stmt.as_ref().map(|e| is_empty(e)).unwrap_or(true);
1417 if then_empty && !else_empty {
1418 **then_stmt = Stmt::Break(None);
1419 true
1420 } else if else_empty && !then_empty {
1421 *else_stmt = Some(Box::new(Stmt::Break(None)));
1422 true
1423 } else {
1424 false
1425 }
1426 }
1427 Stmt::Try { body, .. } | Stmt::TryWithResources { body, .. } => inject(body, cond),
1428 Stmt::Block(v) => v.first_mut().map(|f| inject(f, cond)).unwrap_or(false),
1429 Stmt::Labeled { body, .. } | Stmt::Synchronized { body, .. } => inject(body, cond),
1430 _ => false,
1431 }
1432 }
1433 let mut b = inner;
1434 if inject(&mut b, cond) {
1435 Ok(Stmt::DoWhile {
1436 body: Box::new(b),
1437 cond: Expr::Const(ConstVal::Int(1)),
1438 })
1439 } else {
1440 Err(b)
1441 }
1442}
1443
1444fn split_leading_if(body: &Stmt, cond: &Expr) -> (Stmt, Vec<Stmt>) {
1445 let items = match body {
1446 Stmt::Block(v) => v,
1447 other => {
1448 return match other {
1449 Stmt::If {
1450 cond: c,
1451 then_stmt,
1452 else_stmt,
1453 } if c == cond => (
1454 else_stmt
1455 .as_ref()
1456 .map(|e| (**e).clone())
1457 .unwrap_or(Stmt::Block(vec![])),
1458 stmt_to_vec((**then_stmt).clone()),
1459 ),
1460 _ => (other.clone(), vec![]),
1461 };
1462 }
1463 };
1464 if let Some(Stmt::If {
1465 cond: c,
1466 then_stmt,
1467 else_stmt,
1468 }) = items.first()
1469 {
1470 {
1471 if c == cond {
1472 let inner = if items.len() == 1 {
1473 else_stmt
1474 .as_ref()
1475 .map(|e| (**e).clone())
1476 .unwrap_or(Stmt::Block(vec![]))
1477 } else {
1478 let mut rest = vec![else_stmt
1479 .as_ref()
1480 .map(|e| (**e).clone())
1481 .unwrap_or(Stmt::Block(vec![]))];
1482 rest.extend(items[1..].iter().cloned());
1483 Stmt::Block(rest)
1484 };
1485 return (inner, stmt_to_vec((**then_stmt).clone()));
1486 }
1487 }
1488 }
1489 (body.clone(), vec![])
1490}
1491
1492/// Remove a trailing `continue;` (loop back-edge) from a statement list.
1493fn strip_trailing_continue(s: Stmt) -> Stmt {
1494 match s {
1495 Stmt::Block(mut v) => {
1496 while matches!(v.last(), Some(Stmt::Continue(None))) {
1497 v.pop();
1498 }
1499 if v.len() == 1 && matches!(v[0], Stmt::Block(_)) {
1500 let inner = match v.pop().unwrap() {
1501 Stmt::Block(inner) => inner,
1502 _ => unreachable!(),
1503 };
1504 return strip_trailing_continue(Stmt::Block(inner));
1505 }
1506 Stmt::Block(v)
1507 }
1508 Stmt::Continue(None) => Stmt::Block(vec![]),
1509 other => other,
1510 }
1511}
1512
1513pub fn negate(e: Expr) -> Expr {
1514 match e {
1515 Expr::Un { op: UnOp::Not, e } => *e,
1516 // De Morgan for the short-circuit operators: !(A && B) =
1517 // !A || !B, !(A || B) = !A && !B — recursing through negate
1518 // keeps comparison operands cleanly inverted. An op-only swap
1519 // (the historical invert() LogAnd<->LogOr mapping) silently
1520 // changed the condition's meaning: Arrays.equals' folded
1521 // `a == null || a2 == null` inverted to `a == null && a2 ==
1522 // null`, NPE-ing the a2==null path.
1523 Expr::Bin {
1524 op: op @ (crate::ir::expr::BinOp::LogAnd | crate::ir::expr::BinOp::LogOr),
1525 l,
1526 r,
1527 ty,
1528 } => {
1529 let swapped = if matches!(op, crate::ir::expr::BinOp::LogAnd) {
1530 crate::ir::expr::BinOp::LogOr
1531 } else {
1532 crate::ir::expr::BinOp::LogAnd
1533 };
1534 Expr::Bin {
1535 op: swapped,
1536 l: Box::new(negate(*l)),
1537 r: Box::new(negate(*r)),
1538 ty,
1539 }
1540 }
1541 Expr::Bin { op, l, r, ty } => {
1542 if let Some(inv) = op.invert() {
1543 Expr::Bin { op: inv, l, r, ty }
1544 } else {
1545 Expr::Un {
1546 op: UnOp::Not,
1547 e: Box::new(Expr::Bin { op, l, r, ty }),
1548 }
1549 }
1550 }
1551 other => Expr::Un {
1552 op: UnOp::Not,
1553 e: Box::new(other),
1554 },
1555 }
1556}
1557
1558/// True for a bare `continue;` (or a block wrapping just one).
1559fn is_continue_stmt(s: &Stmt) -> bool {
1560 matches!(s, Stmt::Continue(None))
1561 || matches!(s, Stmt::Block(v) if v.len() == 1 && matches!(v[0], Stmt::Continue(None)))
1562}
1563
1564/// Detect a COMPOUND trailing do-while condition: the body ends with a run of
1565/// `if (c1) continue;` ... `if (cN) continue; else <exit>;`. javac emits this
1566/// for `do { body } while (c1 || ... || cN);` followed by the loop exit when
1567/// the condition is a short-circuit `||` whose tests each jump back to the
1568/// body head (e.g. `Random.internalNextInt`: `while (r < origin || r >=
1569/// bound)`). Fold the run into a single do-while whose condition is the `||`
1570/// of the tests, returning the body statements, that condition, and the exit
1571/// action (`<exit>`) to emit right after the loop.
1572fn extract_compound_do_while(body: &Stmt) -> Option<(Vec<Stmt>, Expr, Stmt)> {
1573 // Flatten nested straight-line blocks: the loop body may group the first
1574 // condition test(s) inside a nested Block (the self-loop header's region)
1575 // while later tests are siblings. Splicing pure sequence blocks is safe.
1576 fn flatten_seq(s: &Stmt) -> Vec<Stmt> {
1577 match s {
1578 Stmt::Block(v) => {
1579 let mut out = Vec::new();
1580 for x in v {
1581 out.extend(flatten_seq(x));
1582 }
1583 out
1584 }
1585 other => vec![other.clone()],
1586 }
1587 }
1588 let mut stmts = flatten_seq(body);
1589 // Unnest the rendered if/else-if CHAIN spine: javac's bottom-tested
1590 // `if (c1) continue; if (c2) continue; ... else exit;` disjunct run
1591 // converts to ONE nested If whose else arms hold the remaining
1592 // tests — opaque to the backwards scan below, which would fold only
1593 // c1 and push the whole c2..cN chain out of the loop as the "exit"
1594 // (jdk26 ML_DSA.signInternal: `do { expandMask.. } while
1595 // (vectorNormBound(z,..));` with the c2/hint chain — and its
1596 // continue/break — stranded after the loop, continue 在 loop 外部
1597 // ×2). Splitting each continue-then If back into siblings restores
1598 // the flat run; semantics are identical (the then arm is a bare
1599 // continue with no fallthrough, and the LAST else is preserved as
1600 // the final statement's else = the loop's exit route).
1601 {
1602 let mut flat: Vec<Stmt> = Vec::new();
1603 for st in stmts.into_iter() {
1604 let mut cur = st;
1605 loop {
1606 match cur {
1607 Stmt::If {
1608 cond,
1609 then_stmt,
1610 else_stmt: Some(e),
1611 } if is_continue_stmt(&then_stmt) => {
1612 flat.push(Stmt::If {
1613 cond,
1614 then_stmt,
1615 else_stmt: None,
1616 });
1617 cur = *e;
1618 }
1619 other => {
1620 flat.push(other);
1621 break;
1622 }
1623 }
1624 }
1625 }
1626 stmts = flat;
1627 }
1628 let n = stmts.len();
1629 if n < 2 {
1630 return None;
1631 }
1632 // Last statement: `if (c_last) continue; else <exit>` — the exit is the
1633 // loop's fall-out (a return/throw/break), NOT another continue.
1634 let (c_last, exit) = match &stmts[n - 1] {
1635 Stmt::If {
1636 cond,
1637 then_stmt,
1638 else_stmt: Some(e),
1639 } if is_continue_stmt(then_stmt) && !is_continue_stmt(e) => (cond.clone(), (**e).clone()),
1640 _ => return None,
1641 };
1642 // Walk backwards over preceding `if (ci) continue;` (no else) tests.
1643 let mut conds = vec![c_last];
1644 let mut i = n - 1;
1645 while i >= 1 {
1646 match &stmts[i - 1] {
1647 Stmt::If {
1648 cond,
1649 then_stmt,
1650 else_stmt: None,
1651 } if is_continue_stmt(then_stmt) => {
1652 conds.push(cond.clone());
1653 i -= 1;
1654 }
1655 _ => break,
1656 }
1657 }
1658 let body_stmts: Vec<Stmt> = stmts[..i].to_vec();
1659 // cond = c1 || c2 || ... || c_last (conds currently reversed).
1660 let mut it = conds.into_iter().rev();
1661 let mut cond = it.next().unwrap();
1662 for c in it {
1663 cond = Expr::Bin {
1664 op: BinOp::LogOr,
1665 l: Box::new(c),
1666 r: Box::new(cond),
1667 ty: None,
1668 };
1669 }
1670 Some((body_stmts, cond, exit))
1671}
1672
1673/// Detect a trailing do-while condition at the end of a loop body:
1674/// `if (c) continue;` → cond c, or `if (c) {} else continue;` → cond !c.
1675fn extract_trailing_do_while(body: &Stmt) -> Option<(Vec<Stmt>, Expr)> {
1676 let mut stmts = match body {
1677 Stmt::Block(v) => v.clone(),
1678 other => vec![other.clone()],
1679 };
1680 if stmts.is_empty() {
1681 return None;
1682 }
1683 let n = stmts.len() - 1;
1684 if let Stmt::If {
1685 cond,
1686 then_stmt,
1687 else_stmt,
1688 } = &stmts[n]
1689 {
1690 let then_is_cont = |s: &Stmt| {
1691 matches!(s, Stmt::Continue(None))
1692 || matches!(s, Stmt::Block(v) if v.len() == 1 && matches!(v[0], Stmt::Continue(None)))
1693 };
1694 if then_is_cont(then_stmt) && else_stmt.is_none() {
1695 let c = cond.clone();
1696 stmts.pop();
1697 return Some((stmts, c));
1698 }
1699 if else_stmt.as_ref().map(|e| then_is_cont(e)).unwrap_or(false)
1700 && (matches!(&**then_stmt, Stmt::Block(v) if v.is_empty()))
1701 {
1702 let c = negate(cond.clone());
1703 stmts.pop();
1704 return Some((stmts, c));
1705 }
1706 }
1707 None
1708}
1709
1710/// If the body ends with `if (c) continue;` (Continue(None), no else),
1711/// strip it and return (body without trailing if, c).
1712#[allow(dead_code)]
1713fn extract_trailing_continue_if(body: &Stmt) -> Option<(Vec<Stmt>, Expr)> {
1714 let mut stmts = match body {
1715 Stmt::Block(v) => v.clone(),
1716 other => vec![other.clone()],
1717 };
1718 if stmts.is_empty() {
1719 return None;
1720 }
1721 let n = stmts.len() - 1;
1722 // Direct trailing `if (c) continue;`.
1723 let is_direct = match &stmts[n] {
1724 Stmt::If {
1725 then_stmt,
1726 else_stmt: None,
1727 ..
1728 } => {
1729 matches!(&**then_stmt, Stmt::Continue(None))
1730 || matches!(&**then_stmt, Stmt::Block(tb) if tb.len() == 1 && matches!(tb[0], Stmt::Continue(None)))
1731 }
1732 _ => false,
1733 };
1734 if is_direct {
1735 if let Stmt::If { cond, .. } = stmts.pop().unwrap() {
1736 return Some((stmts, cond));
1737 }
1738 }
1739 // Descend into a trailing block.
1740 if matches!(stmts.last(), Some(Stmt::Block(_))) {
1741 let last = stmts.pop().unwrap();
1742 if let Some((inner, c)) = extract_trailing_continue_if(&last) {
1743 if !inner.is_empty() {
1744 stmts.push(Stmt::Block(inner));
1745 }
1746 return Some((stmts, c));
1747 } else {
1748 stmts.push(last);
1749 }
1750 }
1751 None
1752}
1753
1754/// Separate the first Basic block's statements from the rest of a body.
1755/// (Bodies built by `walk` start with the header's statements.)
1756#[allow(dead_code)]
1757fn split_first_block(body: Stmt) -> (Stmt, Option<usize>) {
1758 // The body is whatever the walk produced; we keep it intact — header
1759 // statements were already woven in by conv(Basic). Return as-is.
1760 (body, None)
1761}
1762
1763fn stmt_to_vec(s: Stmt) -> Vec<Stmt> {
1764 match s {
1765 Stmt::Block(v) => v,
1766 other => vec![other],
1767 }
1768}
1769
1770/// Strip `Labeled` wrappers no Break/Continue ended up referencing.
1771/// Wrappers are attached unconditionally during conv (a break born in a
1772/// copied/follow region lands after its loop's region-close, so the
1773/// at-close used_labels check orphaned it); after the full conversion
1774/// used_labels is complete and the unused wrappers come off. An unused
1775/// wrapper's body replaces it in-place (a Block body stays a nested
1776/// block — downstream cleanup flattens).
1777fn prune_unused_labels(st: &mut Stmt, used: &HashSet<String>) {
1778 loop {
1779 let take = matches!(st, Stmt::Labeled { label, .. } if !used.contains(label));
1780 if !take {
1781 break;
1782 }
1783 let inner = match std::mem::replace(st, Stmt::Block(Vec::new())) {
1784 Stmt::Labeled { body, .. } => *body,
1785 _ => unreachable!(),
1786 };
1787 *st = inner;
1788 }
1789 match st {
1790 Stmt::Block(v) => v.iter_mut().for_each(|x| prune_unused_labels(x, used)),
1791 Stmt::Labeled { body, .. } => prune_unused_labels(body, used),
1792 Stmt::If { then_stmt, else_stmt, .. } => {
1793 prune_unused_labels(then_stmt, used);
1794 if let Some(e) = else_stmt {
1795 prune_unused_labels(e, used);
1796 }
1797 }
1798 Stmt::While { body, .. }
1799 | Stmt::DoWhile { body, .. }
1800 | Stmt::ForEach { body, .. }
1801 | Stmt::Synchronized { body, .. } => prune_unused_labels(body, used),
1802 Stmt::For { init, body, .. } => {
1803 init.iter_mut().for_each(|x| prune_unused_labels(x, used));
1804 prune_unused_labels(body, used);
1805 }
1806 Stmt::Switch { cases, default, .. } => {
1807 for c in cases.iter_mut() {
1808 c.body.iter_mut().for_each(|x| prune_unused_labels(x, used));
1809 }
1810 if let Some(d) = default {
1811 prune_unused_labels(d, used);
1812 }
1813 }
1814 Stmt::Try { body, catches, finally }
1815 | Stmt::TryWithResources { body, catches, finally, .. } => {
1816 prune_unused_labels(body, used);
1817 for c in catches.iter_mut() {
1818 prune_unused_labels(&mut c.body, used);
1819 }
1820 if let Some(f) = finally {
1821 prune_unused_labels(f, used);
1822 }
1823 }
1824 _ => {}
1825 }
1826}