1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
//! Byte-neutral responsibility split of the former monolith; see the parent module.
use super::*;
/// The two `structured_plan` self-checks, factored out so [`structured_reject_reason`] runs them too.
/// Returns the reject-reason breadcrumb (a stable class label) when a self-check fires, else `None`
/// (the plan is admissible). `ordered` is the structured block order, `header_merge` the
/// header→declared-merge map, `loop_merges` the forest loop-merge map.
pub(in crate::native) fn plan_self_check_reason(
ordered: &[BodyBlock],
header_merge: &HashMap<String, String>,
loop_merges: &HashMap<String, LoopMergeInfo>,
) -> Option<&'static str> {
// Self-check 1: reject straddling loop merges. A loop nested inside an enclosing construct
// (selection/switch/outer loop with header CH and merge CM) must keep its merge block INSIDE that
// construct. The loop is strictly inside the construct when CH dominates the loop header but CM does
// not (the header sits between CH and CM). If the loop's own merge ML is then dominated by CM — it
// lands at/after the construct's merge — the construct boundaries invert: CM branches back into the
// loop's merge, and the structured emitter produces "branches to / exits the selection construct,
// but not via the header" rejects (a previously observed module shape). The kept repair path structures
// these correctly, so reject and fall back rather than emit invalid SPIR-V.
let plan_forest = analyze(ordered);
for l in &plan_forest.loops {
let Some(info) = loop_merges.get(&l.header) else {
continue;
};
let ml = info.merge.as_str();
for (ch, cm) in header_merge {
if ch == &l.header {
continue;
}
let inside =
plan_forest.dominates(ch, &l.header) && !plan_forest.dominates(cm, &l.header);
if inside && plan_forest.dominates(cm, ml) {
// Diagnostic admission (M-B1, default-off): a straddling loop merge is normally an
// honest reject (the enclosing construct's boundaries invert). But for the
// enclosing-guard early-return shape (`05/b00a8a8d`: top-level `if(!c) return` guards
// whose false arm is the OpReturn block that also serves as the loop merge), forcing
// admission lets the downstream synth run and exposes the NEXT blocker (a byte-view
// pointer-phi), which the CFG straddle reject otherwise masks. Flag-on emits invalid
// SPIR-V for genuine straddles, so this is a single-case probe knob, never a fix.
if crate::env_vars::straddle_admit() {
continue;
}
return Some("selection:straddle-loop-merge");
}
}
}
// Self-check 2: reject cross-arm shared-convergence selections/switches. A structured selection or
// switch's arm target (other than its own merge, or a structured break/continue to an enclosing
// loop) MUST be dominated by the header — i.e. private to that arm. When an arm jumps to a block
// reached from OUTSIDE the construct too, the shared block is not dominated by any one header and
// lands after that header's merge in emission order, so the header "exits the selection ... but not
// via a structured exit". Structured SPIR-V needs the shared block CLONED per level, which the kept
// repair path does; reject and fall back. Two shapes hit this:
// - conditionals: a short-circuit `a || b || c` ladder funnels every condition's taken-arm into
// one shared block (a previously observed module shape).
// - switches: a `switch` case/default target is a SIBLING arm of an enclosing selection (banked
// a previously observed module shape, a previously observed module shape), so the switch block exits its enclosing
// selection through a non-merge edge.
// `block_successors` yields the arm set for both conditional and switch terminators, so one check
// covers both rather than only conditionals.
let plan_loop_headers: HashSet<&str> = plan_forest
.loops
.iter()
.map(|l| l.header.as_str())
.collect();
// A jump from header `b`'s arm to a loop's merge/continue is a legal structured break/continue ONLY
// when that loop ENCLOSES `b` (SPIR-V permits a break/continue to an enclosing construct, not to an
// arbitrary sibling construct). The earlier formulation excluded a jump to ANY loop's merge/continue
// — a non-contextual whitelist that admits a sibling-arm cross-jump to a non-enclosing loop's merge,
// which then emits "branches to / exits the selection construct, but not via a structured exit"
// (e.g. `00/a28d5623`: selection header `%94`'s arm branches to `%272`, the merge of a loop living
// in the OTHER top-level arm). Enclosure is tested by natural-loop membership: `l.body` contains `b`.
let is_enclosing_break = |b: &str, a: &str| -> bool {
plan_forest.loops.iter().any(|l| {
l.body.iter().any(|n| n == b)
&& loop_merges
.get(&l.header)
.is_some_and(|i| i.merge == a || i.continue_target == a)
})
};
for b in ordered {
if plan_loop_headers.contains(b.name.as_str()) {
continue;
}
let Some(m) = header_merge.get(&b.name) else {
continue;
};
// A header must dominate its own declared merge (SPIR-V structured-control rule). When the
// merge-assignment picked a block shared with an ENCLOSING construct's arm — so an outer branch
// reaches it directly without passing through this header — the header does not dominate it and
// the selection/switch "exits the selection ... but not via a structured exit" (banked
// `e848bc87`/`72cbab44`). The repair path re-nests these; reject and fall back.
if !plan_forest.dominates(&b.name, m) {
return Some("selection:merge-not-dominated");
}
for a in block_successors(b) {
if &a == m || is_enclosing_break(&b.name, &a) {
continue;
}
if !plan_forest.dominates(&b.name, &a) {
if crate::env_vars::spi_why() {
eprintln!(
"[spi-why] cross-arm-shared header={} arm={} merge={}",
b.name, a, m
);
}
return Some("selection:cross-arm-shared");
}
}
}
// Self-check 3 (Keystone-2): reject a DEFINITIVE cross-arm edge
// that self-check 2 misses. Self-check 2 only inspects a selection header's DIRECT arm successors;
// the 32-row ADMIT structured-exit family escapes via an INTERNAL block deeper in an arm branching to
// a sibling arm of an ANCESTOR selection (e.g. `04/ecdfc78d`: block %94 in %79's else-arm subtree
// branches to %102, %79's then-arm). Detect it as an edge B->S where B is DEFINITIVELY in one arm
// (`dominates(t0, B)`) and S DEFINITIVELY in the sibling arm (`dominates(t1, S)`) of some 2-arm
// conditional selection header H. FP-free: a block dominated by neither arm target (an irreducible/
// straddle reconvergence — the dead-#6 ambiguity) is skipped, so a spirv-val-legal selection is never
// rejected. Computed edge-wise via idom walk (O(edges * dom-depth), NOT O(headers * blocks)): for a
// NON-forward edge B->S, walk B's idom chain; at each selection-header ancestor H whose arm target
// taken by B is `child`, the OTHER arm target `t1` making `dominates(t1, S)` true is the sibling arm.
if ordered.len() <= CROSS_ARM_EDGE_MAX_BLOCKS {
// header -> its two conditional branch targets. ONLY blocks with an assigned selection merge
// (`header_merge`) are real OpSelectionMerge constructs; a conditional without one emits no
// merge instruction, so its arms are not structured arms and a cross-arm edge on it is not a
// structured-exit violation (matching self-check 2, which also keys on `header_merge`). Loops
// and switches are excluded (a break/continue is a legal exit, not a cross-arm jump).
let targets: HashMap<&str, (String, String)> = ordered
.iter()
.filter(|h| !plan_loop_headers.contains(h.name.as_str()))
.filter_map(|h| {
let m = header_merge.get(&h.name)?;
let (t0, t1) = conditional_branch_targets(h)?;
// Skip an if with an EMPTY arm (an arm target == the merge): the only exits are the real
// arm and the merge, so there is no sibling arm to cross into and a branch to the merge
// is a legal exit, not a cross-arm jump (matches the O(H*B) `&t == m` skip).
if &t0 == m || &t1 == m || t0 == t1 {
return None;
}
Some((h.name.as_str(), (t0, t1)))
})
.collect();
for b in ordered {
for s in block_successors(b) {
// Forward edge (S in B's own subtree) is always a legal in-arm edge.
if plan_forest.dominates(&b.name, &s) {
continue;
}
// Walk B's dominator chain; `child` is the arm target of the header `cur` that B entered.
let mut child: &str = &b.name;
while let Some(cur) = plan_forest.idom(child) {
if let Some((x, y)) = targets.get(cur) {
let sibling = if child == x {
Some(y)
} else if child == y {
Some(x)
} else {
None
};
if let Some(t1) = sibling {
if plan_forest.dominates(t1, &s) {
if crate::env_vars::spi_why() {
eprintln!(
"[spi-why] cross-arm-edge header={} sibling={} block={} -> {}",
cur, t1, b.name, s
);
}
return Some("selection:cross-arm-edge");
}
}
}
child = cur;
}
}
}
}
None
}
/// Whether a CFG target is a supported void LLVM return block. The terminal-exit attempt clones this
/// block per selection, so return values remain an explicit unsupported format rather than guessed SSA.
pub(in crate::native) fn block_ends_in_void_return(blocks: &[BodyBlock], name: &str) -> bool {
let Some(block) = blocks.iter().find(|block| block.name == name) else {
return false;
};
// Carrier: a `ret void` terminator lowers to `TirTerminator::Ret(None)` (the structured "returns
// void"), the sole substrate. A block whose lines did not lower (`typed: None`) has no terminator.
block
.typed
.as_ref()
.is_some_and(|t| matches!(t.terminator, crate::native::tir::TirTerminator::Ret(None)))
}
/// DIAGNOSTIC: classify why `structured_plan` rejects (returns `None`) a function, or `None` if it
/// would be admitted. Mirrors [`structured_plan`]'s gates exactly so the breadcrumb is faithful —
/// including the two plan self-checks via the shared [`plan_self_check_reason`]. Used to break down the
/// frontier `cfg` bucket by the restructure class it needs — directs which gate to extend next. Not
/// used in emission.
pub(in crate::native) fn structured_reject_reason(blocks: &[BodyBlock]) -> Option<String> {
// Mirror `structured_plan`'s two attempts so the diagnostic never drifts from the emission gate: a
// function the base path admits has no reason; otherwise classify the graph the pre-pass actually
// hands to emission (the privatized one), so a function rescued by trivial cross-arm privatization
// reports ADMIT, not its pre-privatization cross-arm class.
let switch_private = super::clone_crossarm::privatize_switch_case_continuations(blocks);
let deep_shared = super::clone_crossarm::privatize_deep_shared_continuations(&switch_private);
if deep_shared.len() != blocks.len() && structured_plan(&deep_shared).is_some() {
return None;
}
let force_converge = crate::env_vars::converge_inloop();
if structured_plan_inner(blocks, force_converge, false).is_some() {
return None;
}
let privatized = super::clone_crossarm::privatize_trivial_cross_arm(blocks);
if privatized.len() != blocks.len()
&& structured_plan_inner4(&privatized, force_converge, false, false, false).is_some()
{
return None;
}
// Mirror `structured_plan`'s third (region-clone) attempt so the diagnostic never drifts: classify
// the graph the region pre-pass actually hands emission, so a function rescued by the merge-
// preserving dominated-region clone reports ADMIT, not its pre-clone cross-arm class.
let region = super::clone_crossarm::privatize_region_cross_arm(blocks);
if region.len() != blocks.len()
&& structured_plan_inner4(®ion, force_converge, false, false, false).is_some()
{
return None;
}
// Mirror `structured_plan`'s fourth (reject-triggered in-loop convergence) attempt: a function it
// rescues reports ADMIT, so `--structured-why` reflects the emission gate, not the base-reject class.
if structured_plan_inner4(blocks, true, false, false, false).is_some() {
return None;
}
// Mirror `structured_plan`'s fifth (converge + break-aware selection merges) attempt
// (switch-bearing functions excluded to match the emission gate).
if !switch_gate_excludes(blocks)
&& structured_plan_inner4(blocks, true, true, false, false).is_some()
{
return None;
}
// Mirror `structured_plan`'s sixth (straddle-restructure) attempt, so a function it
// rescues reports ADMIT and `--structured-why` reflects the emission gate.
if !switch_gate_excludes(blocks) {
if let Some(destraddled) = restructure_straddle_loop_merges(blocks) {
if structured_plan_inner4(&destraddled, force_converge, false, false, false).is_some()
|| structured_plan_inner4(&destraddled, true, false, false, false).is_some()
|| structured_plan_inner4(&destraddled, true, true, false, false).is_some()
{
return None;
}
}
}
// Mirror `structured_plan`'s attempt 6b (M3 straddle-under-converge/break-aware, then
// the region-clone chained on the destraddled graph).
if !switch_gate_excludes(blocks) {
if let Some(destraddled) = restructure_straddle_loop_merges_with(blocks, true, true) {
if structured_plan_inner4(&destraddled, true, false, false, false).is_some()
|| structured_plan_inner4(&destraddled, true, true, false, false).is_some()
{
return None;
}
let region2 = super::clone_crossarm::privatize_region_cross_arm(&destraddled);
if region2.len() != destraddled.len()
&& (structured_plan_inner4(®ion2, true, false, false, false).is_some()
|| structured_plan_inner4(®ion2, true, true, false, false).is_some())
{
return None;
}
}
}
// Mirror `structured_plan`'s seventh (region+converge) attempt.
if !switch_gate_excludes(blocks)
&& region.len() != blocks.len()
&& (structured_plan_inner4(®ion, true, false, false, false).is_some()
|| structured_plan_inner4(®ion, true, true, false, false).is_some())
{
return None;
}
// Mirror `structured_plan`'s eighth (multi-exit shared-exit region clone) attempt.
if !switch_gate_excludes(blocks)
&& (structured_plan_inner4(blocks, force_converge, false, true, false).is_some()
|| structured_plan_inner4(blocks, true, false, true, false).is_some()
|| structured_plan_inner4(blocks, true, true, true, false).is_some())
{
return None;
}
// Mirror the final loop-exit-convergence tier, including its mandatory lowering of a switch that
// directly breaks the enclosing loop. The raw switch form must not be re-tried after a lowered
// graph declines: that would make the diagnostic claim ADMIT for a plan spirv-val rejects.
if blocks.len() <= LOOP_EXIT_SELECTION_MAX_BLOCKS {
let lowered_switches = super::blocks::lower_loop_exit_switches(blocks);
let admits = if blocks_changed(blocks, &lowered_switches) {
structured_plan_inner5(&lowered_switches, true, false, false, false, true).is_some()
} else {
structured_plan_inner5(blocks, true, false, false, false, true).is_some()
};
if admits {
return None;
}
}
if blocks.len() <= TERMINAL_EXIT_SELECTION_MAX_BLOCKS
&& [(false, false), (true, false), (true, true)]
.into_iter()
.any(|(converge, break_aware)| {
structured_plan_inner6(blocks, converge, break_aware, false, false, false, true)
.is_some()
})
{
return None;
}
// Mirror the final reject-only divergent-exit normalization. It is intentionally after every
// ordinary ladder attempt, matching `structured_plan`: an admitted function never reaches it.
if structured_plan_divergent_exit(blocks).is_some() {
return None;
}
if region.len() != blocks.len() {
return reject_reason_inner(®ion);
}
reject_reason_inner(&privatized)
}
/// Diagnostic-only reject classifier for [`structured_plan_construct_tree`]. This asks the
/// construct-tree planner first; if it declines, it reports the ordinary structural residue left on
/// the same candidate graph.
pub(in crate::native) fn construct_tree_reject_reason(blocks: &[BodyBlock]) -> Option<String> {
if structured_plan_construct_tree(blocks).is_some() {
None
} else {
reject_reason_inner(blocks)
}
}
/// Read-only diagnostic for the first planner gate that makes a construct-tree candidate decline.
/// This mirrors `structured_plan_construct_tree`'s loop/selection completeness checks, but prints one
/// compact breadcrumb instead of the full `METAL2VULKAN_SPI_WHY` skeleton.
pub(in crate::native) fn construct_tree_gate_witness_lines(blocks: &[BodyBlock]) -> Vec<String> {
let mut out = Vec::new();
if structured_plan_construct_tree(blocks).is_some() {
out.push(format!("gate=ADMIT blocks={}", blocks.len()));
return out;
}
let (lblocks, loop_merges) = forest_loop_merges(blocks, false, false);
let lforest = analyze(&lblocks);
for loop_info in &lforest.loops {
if !loop_merges.contains_key(&loop_info.header) {
out.push(format!(
"gate=loop-uncovered blocks={} header={} loop_body_blocks={}",
blocks.len(),
loop_info.header,
loop_info.body.len(),
));
return out;
}
}
let (sblocks, mut branch, mut branch_by_header, switch) =
unique_selection_merges_with_construct_tree_ownership(
&lblocks,
&loop_merges,
false,
false,
&HashMap::new(),
);
let forest = analyze(&sblocks);
let loop_headers: HashSet<&str> = forest.loops.iter().map(|l| l.header.as_str()).collect();
let names: HashSet<&str> = sblocks.iter().map(|block| block.name.as_str()).collect();
let natural_merges = selection_merges(&lblocks, &lforest);
let mut header_merge: HashMap<String, String> = HashMap::new();
for (header, info) in &loop_merges {
header_merge.insert(header.clone(), info.merge.clone());
}
for block in &sblocks {
let is_switch = is_switch_block(block);
if loop_headers.contains(block.name.as_str()) {
if is_switch {
out.push(format!(
"gate=loop-header-switch blocks={} header={}",
blocks.len(),
block.name,
));
return out;
}
continue;
}
if is_switch {
match switch.get(&block.name) {
Some(merge) => {
header_merge.insert(block.name.clone(), merge.clone());
}
None => {
let successors = block_successors(block);
let mut successor_sample =
successors.iter().take(8).cloned().collect::<Vec<_>>();
if successors.len() > successor_sample.len() {
successor_sample.push("…".to_string());
}
let mut successor_roles = successors
.iter()
.filter_map(|successor| {
sblocks
.iter()
.find(|candidate| &candidate.name == successor)
.map(|candidate| {
format!("{}:{}", candidate.name, block_role_label(candidate))
})
})
.collect::<Vec<_>>();
successor_roles.sort();
let mut successor_chains = successors
.iter()
.filter_map(|successor| {
single_successor_chain(&sblocks, successor, 6)
.map(|chain| format!("{successor}->{}", chain.join("->")))
})
.collect::<Vec<_>>();
successor_chains.sort();
out.push(format!(
"gate=switch-no-merge blocks={} header={} successors=[{}] successor_roles=[{}] successor_chains=[{}]",
blocks.len(),
block.name,
successor_sample.join(","),
successor_roles.join(","),
successor_chains.join(","),
));
return out;
}
}
continue;
}
let successors = block_successors(block);
let distinct: HashSet<&str> = successors
.iter()
.map(String::as_str)
.filter(|target| names.contains(target))
.collect();
if distinct.len() < 2 {
continue;
}
let Some((t, f)) = conditional_branch_targets(block) else {
out.push(format!(
"gate=no-cond-targets blocks={} header={}",
blocks.len(),
block.name,
));
return out;
};
if bare_loop_exit_branch_with_passthroughs(
&sblocks,
&forest,
&loop_merges,
&block.name,
&t,
&f,
) {
branch.remove(&(t.clone(), f.clone()));
branch_by_header.remove(&block.name);
continue;
}
if let Some(merge) = branch_by_header
.get(&block.name)
.or_else(|| branch.get(&(t.clone(), f.clone())))
{
header_merge.insert(block.name.clone(), merge.clone());
continue;
}
if let Some(merge) = loop_break_continue_merge(&forest, &loop_merges, &block.name, &t, &f) {
header_merge.insert(block.name.clone(), merge);
continue;
}
let natural = natural_merges
.get(&block.name)
.map(String::as_str)
.unwrap_or("-");
let has_phi = natural != "-" && block_has_phi(&lblocks, natural);
let mut dom_preds = lblocks
.iter()
.filter(|predecessor| {
natural != "-"
&& lforest.dominates(&block.name, &predecessor.name)
&& block_successors(predecessor)
.iter()
.any(|successor| successor == natural)
})
.map(|predecessor| predecessor.name.clone())
.collect::<Vec<_>>();
dom_preds.sort();
let mut dom_pred_sample = dom_preds.iter().take(8).cloned().collect::<Vec<_>>();
if dom_preds.len() > dom_pred_sample.len() {
dom_pred_sample.push("…".to_string());
}
let mut current_dom_preds = sblocks
.iter()
.filter(|predecessor| {
natural != "-"
&& forest.dominates(&block.name, &predecessor.name)
&& block_successors(predecessor)
.iter()
.any(|successor| successor == natural)
})
.map(|predecessor| predecessor.name.clone())
.collect::<Vec<_>>();
current_dom_preds.sort();
let mut current_dom_pred_sample = current_dom_preds
.iter()
.take(8)
.cloned()
.collect::<Vec<_>>();
if current_dom_preds.len() > current_dom_pred_sample.len() {
current_dom_pred_sample.push("…".to_string());
}
let mut original_pred_current_chains = dom_preds
.iter()
.filter_map(|pred| {
single_successor_chain(&sblocks, pred, 8)
.map(|chain| format!("{pred}->{}", chain.join("->")))
})
.collect::<Vec<_>>();
original_pred_current_chains.sort();
let mut original_pred_current_chain_sample = original_pred_current_chains
.iter()
.take(8)
.cloned()
.collect::<Vec<_>>();
if original_pred_current_chains.len() > original_pred_current_chain_sample.len() {
original_pred_current_chain_sample.push("…".to_string());
}
let reverse_present = branch.contains_key(&(f.clone(), t.clone()));
out.push(format!(
"gate=branch-no-merge blocks={} sblocks={} header={} arms=({},{}) natural={} natural_phi={} dom_pred_count={} dom_preds=[{}] current_dom_pred_count={} current_dom_preds=[{}] original_pred_current_chains=[{}] branch_reverse_present={}",
blocks.len(),
sblocks.len(),
block.name,
t,
f,
natural,
has_phi as u8,
dom_preds.len(),
dom_pred_sample.join(","),
current_dom_preds.len(),
current_dom_pred_sample.join(","),
original_pred_current_chain_sample.join(","),
reverse_present,
));
return out;
}
let order = structured_order(&sblocks, &forest, |header| {
header_merge.get(header).cloned()
});
let rank: HashMap<&str, usize> = order
.iter()
.enumerate()
.map(|(index, name)| (name.as_str(), index))
.collect();
let mut ordered = sblocks.clone();
ordered.sort_by_key(|block| rank.get(block.name.as_str()).copied().unwrap_or(usize::MAX));
if let Some(reason) = plan_self_check_reason(&ordered, &header_merge, &loop_merges) {
if reason == "selection:merge-not-dominated" {
let ordered_loop_headers: HashSet<&str> = forest
.loops
.iter()
.map(|loop_info| loop_info.header.as_str())
.collect();
if let Some((header, merge)) = ordered.iter().find_map(|block| {
if ordered_loop_headers.contains(block.name.as_str()) {
return None;
}
let merge = header_merge.get(&block.name)?;
(!forest.dominates(&block.name, merge)).then_some((&block.name, merge))
}) {
let reachable = crate::native::cfg::graph::Cfg::from_blocks(&sblocks)
.map(|cfg| cfg.reachable_from(&cfg.entry))
.unwrap_or_default();
let header_idom = forest.idom(header).unwrap_or("-");
let merge_idom = forest.idom(merge).unwrap_or("-");
let source_natural = natural_merges
.get(header)
.map(String::as_str)
.unwrap_or("-");
let final_arms = sblocks
.iter()
.find(|block| block.name == *header)
.and_then(conditional_branch_targets)
.map(|(t, f)| format!("({t},{f})"))
.unwrap_or_else(|| "(-,-)".to_string());
let mut preds = sblocks
.iter()
.filter(|candidate| {
block_successors(candidate)
.iter()
.any(|target| target == merge)
})
.map(|candidate| candidate.name.clone())
.collect::<Vec<_>>();
preds.sort();
let mut pred_sample = preds.iter().take(8).cloned().collect::<Vec<_>>();
if preds.len() > pred_sample.len() {
pred_sample.push("…".to_string());
}
let mut pred_roles = sblocks
.iter()
.filter(|candidate| preds.iter().any(|pred| pred == &candidate.name))
.map(|candidate| format!("{}:{}", candidate.name, block_role_label(candidate)))
.collect::<Vec<_>>();
pred_roles.sort();
let mut pred_role_sample = pred_roles.iter().take(8).cloned().collect::<Vec<_>>();
if pred_roles.len() > pred_role_sample.len() {
pred_role_sample.push("…".to_string());
}
let mut pred_sources = preds
.iter()
.map(|pred| {
let mut sources = sblocks
.iter()
.filter(|candidate| {
block_successors(candidate)
.iter()
.any(|target| target == pred)
})
.map(|candidate| {
format!("{}:{}", candidate.name, block_role_label(candidate))
})
.collect::<Vec<_>>();
sources.sort();
format!("{pred}<-[{}]", sources.join("|"))
})
.collect::<Vec<_>>();
pred_sources.sort();
let mut pred_source_sample =
pred_sources.iter().take(8).cloned().collect::<Vec<_>>();
if pred_sources.len() > pred_source_sample.len() {
pred_source_sample.push("…".to_string());
}
out.push(format!(
"gate=self-check blocks={} reason={reason} header={} merge={} arms={} source_natural={} header_reachable={} merge_reachable={} header_idom={} merge_idom={} merge_pred_count={} merge_preds=[{}] merge_pred_roles=[{}] merge_pred_sources=[{}]",
blocks.len(),
header,
merge,
final_arms,
source_natural,
reachable.contains(header) as u8,
reachable.contains(merge) as u8,
header_idom,
merge_idom,
preds.len(),
pred_sample.join(","),
pred_role_sample.join(","),
pred_source_sample.join(","),
));
} else {
out.push(format!(
"gate=self-check blocks={} reason={reason}",
blocks.len()
));
}
} else {
out.push(format!(
"gate=self-check blocks={} reason={reason}",
blocks.len()
));
}
} else {
out.push(format!(
"gate=unknown blocks={} sblocks={} header_merges={}",
blocks.len(),
sblocks.len(),
header_merge.len(),
));
}
out
}
/// Read-only diagnostic for `selection:cond-other` rows. It reports the structural witness that the
/// base classifier uses: a conditional whose synthesized selection merge is missing, whose natural
/// merge is non-phi, and whose header-dominated predecessor(s) still target that natural merge. The
/// output deliberately includes nearby loop-exiting switches so the next construct-tree derivation can
/// pick a bounded switch/loop region instead of retrying whole-function transforms.
pub(in crate::native) fn cond_other_witness_lines(blocks: &[BodyBlock]) -> Vec<String> {
let mut out = Vec::new();
append_cond_other_witness_lines("source", blocks, &mut out);
let switch_private = super::clone_crossarm::privatize_switch_case_continuations(blocks);
let deep_shared = super::clone_crossarm::privatize_deep_shared_continuations(&switch_private);
if blocks_changed(blocks, &deep_shared) {
append_cond_other_witness_lines("deep-shared", &deep_shared, &mut out);
}
let privatized = super::clone_crossarm::privatize_trivial_cross_arm(blocks);
if blocks_changed(blocks, &privatized) {
append_cond_other_witness_lines("trivial", &privatized, &mut out);
}
let region = super::clone_crossarm::privatize_region_cross_arm(blocks);
if blocks_changed(blocks, ®ion) {
append_cond_other_witness_lines("region", ®ion, &mut out);
}
out.sort();
out.dedup();
out
}
/// Read-only diagnostic for the `selection:cond-phi-shared/*` reject family. It mirrors the
/// classifier's phi-carrying missing-selection-merge branch and records the header/natural-merge
/// facts needed to decide whether the existing phi-aware merge split should have fired or whether a
/// real ownership collision remains.
pub(in crate::native) fn cond_phi_shared_witness_lines(blocks: &[BodyBlock]) -> Vec<String> {
let mut out = Vec::new();
append_cond_phi_shared_witness_lines("source", blocks, &mut out);
out.sort();
out.dedup();
out
}
fn append_cond_other_witness_lines(graph: &str, blocks: &[BodyBlock], out: &mut Vec<String>) {
let (lblocks, loop_merges) = forest_loop_merges(blocks, false, false);
let lforest = analyze(&lblocks);
let (sblocks, branch, _switch) = unique_selection_merges(&lblocks, &loop_merges, false);
let forest = analyze(&sblocks);
let loop_headers: HashSet<&str> = forest.loops.iter().map(|l| l.header.as_str()).collect();
let names: HashSet<&str> = sblocks.iter().map(|block| block.name.as_str()).collect();
let natural_merges = selection_merges(&lblocks, &lforest);
for block in &sblocks {
if loop_headers.contains(block.name.as_str()) || is_switch_block(block) {
continue;
}
let succs = block_successors(block);
let distinct: HashSet<&str> = succs
.iter()
.map(String::as_str)
.filter(|target| names.contains(target))
.collect();
if distinct.len() < 2 {
continue;
}
let Some((t, f)) = conditional_branch_targets(block) else {
continue;
};
let looped_arms = lblocks
.iter()
.find(|candidate| candidate.name == block.name)
.and_then(conditional_branch_targets)
.map(|(lt, lf)| format!("({lt},{lf})"))
.unwrap_or_else(|| "(-,-)".to_string());
if branch.contains_key(&(t.clone(), f.clone())) {
continue;
}
let Some(natural) = natural_merges.get(&block.name) else {
continue;
};
if block_has_phi(&lblocks, natural) {
continue;
}
let mut dom_preds = lblocks
.iter()
.filter(|predecessor| {
lforest.dominates(&block.name, &predecessor.name)
&& block_successors(predecessor)
.iter()
.any(|successor| successor == natural)
})
.map(|predecessor| predecessor.name.clone())
.collect::<Vec<_>>();
if dom_preds.is_empty() {
continue;
}
dom_preds.sort();
let enclosing_loop = lforest
.loops
.iter()
.filter(|loop_info| loop_info.body.iter().any(|node| node == &block.name))
.min_by_key(|loop_info| loop_info.body.len());
let (loop_header, loop_merge, loop_continue, loop_body_count, exit_switches, arm_roles) =
if let Some(loop_info) = enclosing_loop {
let body: HashSet<&str> = loop_info.body.iter().map(String::as_str).collect();
let info = loop_merges.get(&loop_info.header);
let mut switches = lblocks
.iter()
.filter(|candidate| {
candidate.name != loop_info.header
&& body.contains(candidate.name.as_str())
&& is_switch_block(candidate)
})
.filter_map(|candidate| {
let mut exits = block_successors(candidate)
.into_iter()
.filter(|successor| !body.contains(successor.as_str()))
.collect::<Vec<_>>();
if exits.is_empty() {
return None;
}
exits.sort();
Some(format!("{}=>{}", candidate.name, exits.join("|")))
})
.collect::<Vec<_>>();
switches.sort();
(
loop_info.header.as_str(),
info.map(|info| info.merge.as_str()).unwrap_or("-"),
info.map(|info| info.continue_target.as_str())
.unwrap_or("-"),
loop_info.body.len(),
switches,
info.map(|info| {
format!(
"({},{})",
cond_other_target_role(&sblocks, &t, info),
cond_other_target_role(&sblocks, &f, info)
)
})
.unwrap_or_else(|| "(-,-)".to_string()),
)
} else {
("-", "-", "-", 0, Vec::new(), "(-,-)".to_string())
};
let mut dom_pred_sample = dom_preds.iter().take(8).cloned().collect::<Vec<_>>();
if dom_preds.len() > dom_pred_sample.len() {
dom_pred_sample.push("…".to_string());
}
let mut switch_sample = exit_switches.iter().take(8).cloned().collect::<Vec<_>>();
if exit_switches.len() > switch_sample.len() {
switch_sample.push("…".to_string());
}
out.push(format!(
"graph={graph} blocks={} header={} looped_arms={} arms=({},{}) arm_roles={} natural={} dom_pred_count={} dom_preds=[{}] loop={} loop_merge={} loop_continue={} loop_body_blocks={} exit_switch_count={} exit_switches=[{}]",
blocks.len(),
block.name,
looped_arms,
t,
f,
arm_roles,
natural,
dom_preds.len(),
dom_pred_sample.join(","),
loop_header,
loop_merge,
loop_continue,
loop_body_count,
exit_switches.len(),
switch_sample.join(","),
));
}
}
fn append_cond_phi_shared_witness_lines(graph: &str, blocks: &[BodyBlock], out: &mut Vec<String>) {
let (lblocks, loop_merges) = forest_loop_merges(blocks, false, false);
let lforest = analyze(&lblocks);
let (sblocks, branch, _switch) = unique_selection_merges(&lblocks, &loop_merges, false);
let forest = analyze(&sblocks);
let loop_headers: HashSet<&str> = forest.loops.iter().map(|l| l.header.as_str()).collect();
let names: HashSet<&str> = sblocks.iter().map(|block| block.name.as_str()).collect();
let natural_merges = selection_merges(&lblocks, &lforest);
for block in &sblocks {
if loop_headers.contains(block.name.as_str()) || is_switch_block(block) {
continue;
}
let succs = block_successors(block);
let distinct: HashSet<&str> = succs
.iter()
.map(String::as_str)
.filter(|target| names.contains(target))
.collect();
if distinct.len() < 2 {
continue;
}
let Some((t, f)) = conditional_branch_targets(block) else {
continue;
};
if branch.contains_key(&(t.clone(), f.clone())) {
continue;
}
let Some(natural) = natural_merges.get(&block.name) else {
continue;
};
if !block_has_phi(&lblocks, natural) {
continue;
}
let mut dom_preds = lblocks
.iter()
.filter(|predecessor| {
lforest.dominates(&block.name, &predecessor.name)
&& block_successors(predecessor)
.iter()
.any(|successor| successor == natural)
})
.map(|predecessor| predecessor.name.clone())
.collect::<Vec<_>>();
dom_preds.sort();
let loop_role = loop_merges.iter().find_map(|(header, info)| {
if info.merge.as_str() == natural.as_str() {
Some((header.as_str(), "merge"))
} else if info.continue_target.as_str() == natural.as_str() {
Some((header.as_str(), "continue"))
} else {
None
}
});
let sibling_claims = natural_merges
.values()
.filter(|merge| merge.as_str() == natural.as_str())
.count();
let class = if dom_preds.is_empty() {
"selection:cond-phi-shared/own-arm".to_string()
} else if let Some((loop_header, role)) = loop_role {
let in_loop = lforest
.loops
.iter()
.find(|loop_info| loop_info.header.as_str() == loop_header)
.map(|loop_info| loop_info.body.iter().any(|name| name == &block.name))
.unwrap_or(false);
let site = if in_loop { "inloop" } else { "outer" };
format!("selection:cond-phi-shared/loop-role/{role}-{site}")
} else if sibling_claims > 1 {
"selection:cond-phi-shared/sibling".to_string()
} else {
"selection:cond-phi-shared/uncollided".to_string()
};
let mut dom_pred_sample = dom_preds.iter().take(8).cloned().collect::<Vec<_>>();
if dom_preds.len() > dom_pred_sample.len() {
dom_pred_sample.push("…".to_string());
}
let (phi_count, phi_sample) = phi_summary(&lblocks, natural);
let (loop_role_header, loop_role_kind) = loop_role.unwrap_or(("-", "-"));
out.push(format!(
"graph={graph} blocks={} class={class} header={} arms=({},{}) natural={} natural_phi_count={} natural_phi_sample=[{}] dom_pred_count={} dom_preds=[{}] sibling_claims={} loop_role_header={} loop_role_kind={}",
blocks.len(),
block.name,
t,
f,
natural,
phi_count,
phi_sample.join(","),
dom_preds.len(),
dom_pred_sample.join(","),
sibling_claims,
loop_role_header,
loop_role_kind,
));
}
}
fn phi_summary(blocks: &[BodyBlock], name: &str) -> (usize, Vec<String>) {
let Some(block) = blocks.iter().find(|block| block.name == name) else {
return (0, Vec::new());
};
let Some(carrier) = &block.typed else {
return (0, Vec::new());
};
let phis = carrier
.insts
.iter()
.filter(|inst| inst.is_phi())
.collect::<Vec<_>>();
let mut sample = phis
.iter()
.take(8)
.map(|inst| {
inst.result
.clone()
.unwrap_or_else(|| "<no-result>".to_string())
})
.collect::<Vec<_>>();
if phis.len() > sample.len() {
sample.push("…".to_string());
}
(phis.len(), sample)
}
fn single_successor_chain(blocks: &[BodyBlock], start: &str, limit: usize) -> Option<Vec<String>> {
let mut out = Vec::new();
let mut seen = HashSet::new();
let mut current = start.to_string();
for _ in 0..limit {
let block = blocks.iter().find(|block| block.name == current)?;
let successors = block_successors(block);
if successors.len() != 1 {
if !successors.is_empty() {
out.push(format!("{{{}}}", successors.join("|")));
}
return Some(out);
}
let next = successors[0].clone();
out.push(next.clone());
if !seen.insert(next.clone()) {
out.push("cycle".to_string());
return Some(out);
}
current = next;
}
out.push("…".to_string());
Some(out)
}
fn block_role_label(block: &BodyBlock) -> &'static str {
match block.role {
BlockRole::Normal => "ordinary",
BlockRole::LMerge => "lmerge",
BlockRole::TerminalExitReturn => "terminal-exit-return",
BlockRole::SwitchBypass => "switch-bypass",
BlockRole::ConstructTreeRoute => "construct-tree-route",
}
}
fn cond_other_target_role(blocks: &[BodyBlock], target: &str, loop_info: &LoopMergeInfo) -> String {
if target == loop_info.merge {
return "loop-merge".to_string();
}
if target == loop_info.continue_target {
return "loop-continue".to_string();
}
let Some(block) = blocks.iter().find(|block| block.name == target) else {
return "unknown".to_string();
};
let role = block_role_label(block);
if block.role != BlockRole::LMerge {
return role.to_string();
}
let mut successors = block_successors(block);
successors.sort();
successors.dedup();
if successors.len() != 1 {
return format!("lmerge->{}", successors.join("|"));
}
let successor = &successors[0];
if successor == &loop_info.merge {
"lmerge->loop-merge".to_string()
} else if successor == &loop_info.continue_target {
"lmerge->loop-continue".to_string()
} else {
format!("lmerge->{successor}")
}
}
/// The base reject classifier, mirroring [`structured_plan_inner`]'s gates. [`structured_reject_reason`]
/// runs it on the privatized graph after confirming the base path rejects.
pub(in crate::native) fn reject_reason_inner(blocks: &[BodyBlock]) -> Option<String> {
let (lblocks, loop_merges) = forest_loop_merges(blocks, false, false);
let lforest = analyze(&lblocks);
// Loop gate: aggregate the restructure class of the first uncovered loop.
let plans = lforest.structured_plan();
for l in &lforest.loops {
if !loop_merges.contains_key(&l.header) {
let kinds = plans
.iter()
.find(|p| p.header == l.header)
.map(|p| {
if p.restructure.is_empty() {
"loop-uncovered".to_string()
} else {
let mut k: Vec<String> =
p.restructure.iter().map(|r| format!("{r:?}")).collect();
k.sort();
let mut reason = format!("loop:{}", k.join("+"));
// DIAGNOSTIC suffix for the multi-exit relooper work: the synth handles only
// k==2 non-phi exits, so the sub-case (exit count + any phi-carrying exit)
// directs which extension moves the cfg head. Pure measurement — not used in
// emission.
if p.restructure.contains(&Restructure::MultipleExits) {
let mut exits = l.exits.clone();
exits.sort();
exits.dedup();
let phi = exits.iter().any(|e| block_has_phi(&lblocks, e));
reason.push_str(&format!("[k={},phi={}]", exits.len(), phi as u8));
}
reason
}
})
.unwrap_or_else(|| "loop-uncovered".to_string());
return Some(kinds);
}
}
let (sblocks, branch, switch) = unique_selection_merges(&lblocks, &loop_merges, false);
let forest = analyze(&sblocks);
let loop_headers: HashSet<&str> = forest.loops.iter().map(|l| l.header.as_str()).collect();
let names: HashSet<&str> = sblocks.iter().map(|b| b.name.as_str()).collect();
for b in &sblocks {
let is_switch = is_switch_block(b);
if loop_headers.contains(b.name.as_str()) {
if is_switch {
return Some("loop:loop-header-switch".to_string());
}
continue;
}
if is_switch {
if !switch.contains_key(&b.name) {
return Some("selection:switch-no-merge".to_string());
}
continue;
}
let succs = block_successors(b);
let distinct: HashSet<&str> = succs
.iter()
.map(String::as_str)
.filter(|t| names.contains(t))
.collect();
if distinct.len() < 2 {
continue;
}
let Some((t, f)) = conditional_branch_targets(b) else {
return Some("selection:no-targets".to_string());
};
if !branch.contains_key(&(t, f)) {
// Sub-classify so the metric-mover targets the right surgery. Recompute the natural merge
// and the collision/synth decision unique_selection_merges made for this header.
let nat_forest = analyze(&lblocks);
let sel = selection_merges(&lblocks, &nat_forest);
let Some(natural) = sel.get(&b.name) else {
return Some("selection:cond-no-natural".to_string());
};
if block_has_phi(&lblocks, natural) {
// Sub-classify the phi-carrying unhandled merge so the next R2 increment targets the
// dominant sub-shape. `/loop-role` (the bulk) is the hard case: `natural` is BOTH a
// loop's merge/continue AND this selection's post-dominator — a loop-merge ⇄
// selection-merge collision that needs the loop given a distinct synthesized merge
// before the selection can claim `natural`. `/own-arm` = the header's own arm IS
// `natural` (no dominated pass-through site). `/sibling` = two sibling selections share
// `natural`. `/uncollided` = phi merge that should already synth (a synth gap, not a
// collision).
let has_dom_pred = lblocks.iter().any(|p| {
nat_forest.dominates(&b.name, &p.name)
&& block_successors(p).iter().any(|s| s == natural)
});
// Which loop (if any) already owns `natural` in the FINAL loop-merge map, and in what
// role. This is the `loop-role` collision — sub-classified below so the next surgery
// targets the dominant shape (merge-collision vs continue-collision, and whether the
// colliding selection sits inside that loop's body or outside it). Pure diagnostic.
let loop_role = loop_merges.iter().find_map(|(h, i)| {
if i.merge.as_str() == natural.as_str() {
Some((h.as_str(), "merge"))
} else if i.continue_target.as_str() == natural.as_str() {
Some((h.as_str(), "continue"))
} else {
None
}
});
let sibling_claims = sel
.values()
.filter(|m| m.as_str() == natural.as_str())
.count();
if !has_dom_pred {
return Some("selection:cond-phi-shared/own-arm".to_string());
}
if let Some((loop_h, role)) = loop_role {
// Is the selection header inside the colliding loop's body? An in-loop selection
// sharing the loop's merge/continue is a structured break/continue that needs the
// loop given a distinct merge FIRST; an outer selection sharing an inner loop's
// block is the `merge_collides_with_outer_selection` shape (already handled for the
// single-exit/merge case — a residual here means the split declined).
let in_loop = nat_forest
.loops
.iter()
.find(|l| l.header.as_str() == loop_h)
.map(|l| l.body.iter().any(|n| n.as_str() == b.name.as_str()))
.unwrap_or(false);
let site = if in_loop { "inloop" } else { "outer" };
return Some(format!("selection:cond-phi-shared/loop-role/{role}-{site}"));
}
if sibling_claims > 1 {
return Some("selection:cond-phi-shared/sibling".to_string());
}
return Some("selection:cond-phi-shared/uncollided".to_string());
}
// synth returns None when no header-dominated predecessor targets `natural` — i.e. the
// header's own arm IS `natural`, which is dominated by an enclosing header (shared arm).
let has_dom_pred = lblocks.iter().any(|p| {
nat_forest.dominates(&b.name, &p.name)
&& block_successors(p).iter().any(|s| s == natural)
});
if !has_dom_pred {
return Some("selection:cond-shared-arm".to_string());
}
return Some("selection:cond-other".to_string());
}
}
// All merge-synthesis gates passed (every header has a unique merge) — `structured_plan` would now
// reach its two plan self-checks. Rebuild the same header→merge map + structured order and run them
// via the shared helper, so a function rejected ONLY by a self-check is reported here too (else it
// mis-reports as ADMIT while emission falls back to the repair path).
let mut header_merge: HashMap<String, String> = HashMap::new();
for (h, info) in &loop_merges {
header_merge.insert(h.clone(), info.merge.clone());
}
for b in &sblocks {
if loop_headers.contains(b.name.as_str()) {
continue;
}
let is_switch = is_switch_block(b);
if is_switch {
if let Some(m) = switch.get(&b.name) {
header_merge.insert(b.name.clone(), m.clone());
}
continue;
}
let succs = block_successors(b);
let distinct: HashSet<&str> = succs
.iter()
.map(String::as_str)
.filter(|t| names.contains(t))
.collect();
if distinct.len() < 2 {
continue;
}
if let Some((t, f)) = conditional_branch_targets(b) {
if let Some(m) = branch.get(&(t, f)) {
header_merge.insert(b.name.clone(), m.clone());
}
}
}
let order = structured_order(&sblocks, &forest, |h| header_merge.get(h).cloned());
let rank: HashMap<&str, usize> = order
.iter()
.enumerate()
.map(|(i, n)| (n.as_str(), i))
.collect();
let mut ordered = sblocks.clone();
ordered.sort_by_key(|b| rank.get(b.name.as_str()).copied().unwrap_or(usize::MAX));
plan_self_check_reason(&ordered, &header_merge, &loop_merges).map(str::to_string)
}
#[cfg(test)]
mod tests {
use super::*;
fn bb(name: &str, role: BlockRole, lines: &[&str]) -> BodyBlock {
let lines = lines
.iter()
.map(|line| line.to_string())
.collect::<Vec<_>>();
BodyBlock {
name: name.to_string(),
role,
typed: crate::native::tir::lower_block_carrier(name, &lines, &HashMap::new()),
}
}
#[test]
fn cond_other_target_role_reports_synthetic_loop_routes() {
let blocks = vec![
bb("%lm", BlockRole::LMerge, &["br label %merge"]),
bb("%cont", BlockRole::Normal, &["br label %head"]),
bb("%merge", BlockRole::Normal, &["ret void"]),
];
let loop_info = LoopMergeInfo {
merge: "%merge".to_string(),
continue_target: "%cont".to_string(),
};
assert_eq!(
cond_other_target_role(&blocks, "%lm", &loop_info),
"lmerge->loop-merge"
);
assert_eq!(
cond_other_target_role(&blocks, "%cont", &loop_info),
"loop-continue"
);
}
}