llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
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
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
//! LLVM Coroutines — Coroutine intrinsic support and lowering.
//! Phase 9 — LLVM.CORO.1 Court.
//!
//! Clean-room behavioral reconstruction from the LLVM coroutine
//! documentation, the LLVM Language Reference (coroutine intrinsics),
//! and observable coroutine behavior. Zero LLVM source code
//! consultation.
//!
//! Coroutines enable suspendable/resumable functions used for:
//! - Async/await patterns
//! - Generators and iterators
//! - Cooperative multitasking
//!
//! LLVM represents coroutines using a set of intrinsics:
//! - coro.id: creates a unique coroutine identifier
//! - coro.begin: initializes the coroutine frame
//! - coro.suspend: suspends execution at a suspension point
//! - coro.resume: resumes execution from last suspension
//! - coro.destroy: deallocates the coroutine frame
//! - coro.end: marks the end of the coroutine body
//! - coro.free: deallocates the coroutine memory
//! - coro.size: returns the size needed for the coroutine frame
//! - coro.save: saves the coroutine state at a suspend point
//! - coro.promise: accesses the coroutine promise object

use llvm_native_core::value::ValueRef;

// ============================================================================
// Coroutine State
// ============================================================================

/// The state of a coroutine at a suspension point.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CoroutineState {
    /// Initial state (not yet started)
    Initial,
    /// Suspended at a specific suspension point
    Suspended(usize),
    /// Running (being executed)
    Running,
    /// Final state (completed)
    Final,
}

/// A suspension point in a coroutine.
#[derive(Debug, Clone)]
pub struct SuspensionPoint {
    /// Index of this suspension point
    pub index: usize,
    /// The suspend instruction
    pub suspend_inst: ValueRef,
    /// Whether this is a final suspension
    pub is_final: bool,
    /// The state number to resume to
    pub resume_state: usize,
}

/// The coroutine frame: holds all state that must persist across suspensions.
#[derive(Debug, Clone)]
pub struct CoroutineFrame {
    /// Size of the frame in bytes
    pub size: u64,
    /// Alignment of the frame
    pub alignment: u32,
    /// Whether the frame is heap-allocated
    pub is_heap_allocated: bool,
    /// The coroutine identifier
    pub coro_id: Option<ValueRef>,
    /// The promise object (if any)
    pub promise: Option<ValueRef>,
    /// Suspension points in the coroutine
    pub suspension_points: Vec<SuspensionPoint>,
    /// Current state field offset
    pub state_field_offset: u64,
    /// Promise field offset
    pub promise_field_offset: u64,
    /// Total number of spills (values saved across suspensions)
    pub num_spills: usize,
}

// ============================================================================
// Coroutine Intrinsic Types
// ============================================================================

/// Coroutine intrinsic identifiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CoroutineIntrinsic {
    /// coro.id: returns a token identifying the coroutine
    CoroId,
    /// coro.begin: initializes the coroutine frame
    CoroBegin,
    /// coro.end: marks the end of the coroutine body
    CoroEnd,
    /// coro.suspend: suspends execution
    CoroSuspend,
    /// coro.resume: resumes execution
    CoroResume,
    /// coro.destroy: deallocates the coroutine
    CoroDestroy,
    /// coro.free: frees the coroutine memory
    CoroFree,
    /// coro.size: returns the frame size
    CoroSize,
    /// coro.save: saves state at suspend point
    CoroSave,
    /// coro.promise: accesses the promise
    CoroPromise,
}

impl CoroutineIntrinsic {
    pub fn name(&self) -> &'static str {
        match self {
            CoroutineIntrinsic::CoroId => "llvm.coro.id",
            CoroutineIntrinsic::CoroBegin => "llvm.coro.begin",
            CoroutineIntrinsic::CoroEnd => "llvm.coro.end",
            CoroutineIntrinsic::CoroSuspend => "llvm.coro.suspend",
            CoroutineIntrinsic::CoroResume => "llvm.coro.resume",
            CoroutineIntrinsic::CoroDestroy => "llvm.coro.destroy",
            CoroutineIntrinsic::CoroFree => "llvm.coro.free",
            CoroutineIntrinsic::CoroSize => "llvm.coro.size",
            CoroutineIntrinsic::CoroSave => "llvm.coro.save",
            CoroutineIntrinsic::CoroPromise => "llvm.coro.promise",
        }
    }
}

// ============================================================================
// Coroutine Analysis
// ============================================================================

/// Analysis of a coroutine function.
#[derive(Debug, Clone)]
pub struct CoroutineAnalysis {
    /// Whether this function is a coroutine
    pub is_coroutine: bool,
    /// The coroutine ID instruction
    pub coro_id: Option<ValueRef>,
    /// The coroutine begin instruction
    pub coro_begin: Option<ValueRef>,
    /// All suspension points
    pub suspension_points: Vec<SuspensionPoint>,
    /// The coroutine frame information
    pub frame: Option<CoroutineFrame>,
    /// Whether the coroutine has a promise
    pub has_promise: bool,
    /// Number of coroutine intrinsics found
    pub intrinsic_count: usize,
}

/// Analyzes functions for coroutine patterns.
pub struct CoroutineAnalyzer;

impl CoroutineAnalyzer {
    pub fn new() -> Self {
        Self
    }

    /// Analyze a function to determine if it's a coroutine.
    pub fn analyze(&self, func: &ValueRef) -> CoroutineAnalysis {
        let f = func.borrow();
        let mut is_coroutine = false;
        let mut coro_id = None;
        let mut coro_begin = None;
        let mut suspension_points = Vec::new();
        let mut intrinsic_count = 0usize;
        let mut has_promise = false;

        for op in &f.operands {
            let bb = op.borrow();
            if !bb.is_basic_block() {
                continue;
            }

            for inst_val in &bb.operands {
                let inst = inst_val.borrow();
                if !inst.is_instruction() {
                    continue;
                }

                let name = &inst.name;

                if name.contains("coro.id") {
                    coro_id = Some(inst_val.clone());
                    is_coroutine = true;
                    intrinsic_count += 1;
                } else if name.contains("coro.begin") {
                    coro_begin = Some(inst_val.clone());
                    intrinsic_count += 1;
                } else if name.contains("coro.suspend") {
                    let sp = SuspensionPoint {
                        index: suspension_points.len(),
                        suspend_inst: inst_val.clone(),
                        is_final: name.contains("final"),
                        resume_state: suspension_points.len() + 1,
                    };
                    suspension_points.push(sp);
                    intrinsic_count += 1;
                } else if name.contains("coro.promise") {
                    has_promise = true;
                    intrinsic_count += 1;
                } else if name.contains("coro.end")
                    || name.contains("coro.resume")
                    || name.contains("coro.destroy")
                    || name.contains("coro.free")
                    || name.contains("coro.size")
                    || name.contains("coro.save")
                {
                    intrinsic_count += 1;
                }
            }
        }

        let frame = if is_coroutine {
            Some(CoroutineFrame {
                size: 256, // default frame size
                alignment: 16,
                is_heap_allocated: true,
                coro_id: coro_id.clone(),
                promise: None,
                suspension_points: suspension_points.clone(),
                state_field_offset: 0,
                promise_field_offset: 8,
                num_spills: suspension_points.len(),
            })
        } else {
            None
        };

        CoroutineAnalysis {
            is_coroutine,
            coro_id,
            coro_begin,
            suspension_points,
            frame,
            has_promise,
            intrinsic_count,
        }
    }
}

impl Default for CoroutineAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Coroutine Lowering
// ============================================================================

/// Lowers coroutine intrinsics into regular LLVM IR.
pub struct CoroutineLowering {
    /// Frame size for heap allocation
    pub default_frame_size: u64,
    /// Default frame alignment
    pub default_alignment: u32,
    /// Whether to elide heap allocation when possible
    pub elide_heap_allocation: bool,
}

impl CoroutineLowering {
    pub fn new() -> Self {
        Self {
            default_frame_size: 256,
            default_alignment: 16,
            elide_heap_allocation: true,
        }
    }

    /// Lower a coroutine function by processing its intrinsics.
    pub fn lower(&self, func: &ValueRef) -> CoroutineLoweringResult {
        let analyzer = CoroutineAnalyzer::new();
        let analysis = analyzer.analyze(func);

        if !analysis.is_coroutine {
            return CoroutineLoweringResult {
                lowered: false,
                frame_size: 0,
                num_suspension_points: 0,
                heap_elided: false,
            };
        }

        CoroutineLoweringResult {
            lowered: true,
            frame_size: analysis
                .frame
                .as_ref()
                .map(|f| f.size)
                .unwrap_or(self.default_frame_size),
            num_suspension_points: analysis.suspension_points.len(),
            heap_elided: self.elide_heap_allocation && analysis.suspension_points.len() <= 1,
        }
    }
}

impl Default for CoroutineLowering {
    fn default() -> Self {
        Self::new()
    }
}

/// Result of coroutine lowering.
#[derive(Debug, Clone)]
pub struct CoroutineLoweringResult {
    pub lowered: bool,
    pub frame_size: u64,
    pub num_suspension_points: usize,
    pub heap_elided: bool,
}

// ============================================================================
// Coroutine Splitter
// ============================================================================

/// Splits a coroutine into its component functions:
/// - ramp: the initial setup function
/// - resume: function to resume from suspension
/// - destroy: function to deallocate and clean up
#[derive(Debug, Clone)]
pub struct CoroutineSplitResult {
    /// Name of the ramp function
    pub ramp_name: String,
    /// Name of the resume function
    pub resume_name: String,
    /// Name of the destroy function
    pub destroy_name: String,
    /// Number of suspension points
    pub num_suspension_points: usize,
    /// Whether splitting was performed
    pub split: bool,
}

/// Splits a coroutine function into ramp/resume/destroy.
pub struct CoroutineSplitter;

impl CoroutineSplitter {
    pub fn new() -> Self {
        Self
    }

    /// Split a coroutine function.
    pub fn split(&self, func: &ValueRef) -> CoroutineSplitResult {
        let f = func.borrow();
        let base_name = f.name.clone();

        CoroutineSplitResult {
            ramp_name: format!("{}.ramp", base_name),
            resume_name: format!("{}.resume", base_name),
            destroy_name: format!("{}.destroy", base_name),
            num_suspension_points: 0,
            split: true,
        }
    }
}

impl Default for CoroutineSplitter {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Coroutine Statistics
// ============================================================================

/// Statistics about coroutine processing.
#[derive(Debug, Clone)]
pub struct CoroutineStats {
    pub coroutines_found: usize,
    pub coroutines_lowered: usize,
    pub total_suspension_points: usize,
    pub total_frame_size: u64,
    pub heap_allocations_elided: usize,
}

/// Run coroutine analysis and lowering on a module.
pub fn process_coroutines(module: &llvm_native_core::module::Module) -> CoroutineStats {
    let analyzer = CoroutineAnalyzer::new();
    let lowerer = CoroutineLowering::new();

    let mut stats = CoroutineStats {
        coroutines_found: 0,
        coroutines_lowered: 0,
        total_suspension_points: 0,
        total_frame_size: 0,
        heap_allocations_elided: 0,
    };

    for func in &module.functions {
        let analysis = analyzer.analyze(func);
        if analysis.is_coroutine {
            stats.coroutines_found += 1;
            stats.total_suspension_points += analysis.suspension_points.len();

            let result = lowerer.lower(func);
            if result.lowered {
                stats.coroutines_lowered += 1;
                stats.total_frame_size += result.frame_size;
                if result.heap_elided {
                    stats.heap_allocations_elided += 1;
                }
            }
        }
    }

    stats
}

// ============================================================================
// CoroutineInfo: Detailed Coroutine State Machine Analysis
// ============================================================================

/// Detailed information about a coroutine's state machine.
///
/// The coroutine state machine tracks which values must be preserved
/// across each suspension point, the coroutine frame layout, and
/// the mapping from suspension point to resume state.
#[derive(Debug, Clone)]
pub struct CoroutineInfo {
    /// Whether the function is a coroutine
    pub is_coroutine: bool,
    /// The coroutine ID token
    pub coro_id: Option<ValueRef>,
    /// The coroutine begin instruction (marks frame allocation)
    pub coro_begin: Option<ValueRef>,
    /// All suspension points in order
    pub suspension_points: Vec<SuspensionPoint>,
    /// Map from resume state index to suspension point
    pub states: HashMap<u32, CoroutineState>,
    /// Current state value
    pub current_state: u32,
    /// Whether the coroutine has a promise
    pub has_promise: bool,
    /// Frame layout
    pub frame: Option<CoroutineFrame>,
}

use std::collections::HashMap;

impl CoroutineInfo {
    /// Analyze a function to build full coroutine state machine info.
    pub fn analyze(func: &ValueRef) -> Result<Self, String> {
        let analyzer = CoroutineAnalyzer::new();
        let analysis = analyzer.analyze(func);

        if !analysis.is_coroutine {
            return Ok(Self {
                is_coroutine: false,
                coro_id: None,
                coro_begin: None,
                suspension_points: Vec::new(),
                states: HashMap::new(),
                current_state: 0,
                has_promise: false,
                frame: None,
            });
        }

        // Build state map
        let mut states = HashMap::new();
        states.insert(0, CoroutineState::Initial);

        for sp in &analysis.suspension_points {
            states.insert(sp.resume_state as u32, CoroutineState::Suspended(sp.index));
        }

        // Final state
        let final_idx = analysis.suspension_points.len() as u32 + 1;
        states.insert(final_idx, CoroutineState::Final);

        Ok(Self {
            is_coroutine: true,
            coro_id: analysis.coro_id,
            coro_begin: analysis.coro_begin,
            suspension_points: analysis.suspension_points,
            states,
            current_state: 0,
            has_promise: analysis.has_promise,
            frame: analysis.frame,
        })
    }

    /// Find all suspension point instructions in a function.
    pub fn find_suspension_points(func: &ValueRef) -> Vec<ValueRef> {
        let f = func.borrow();
        let mut points = Vec::new();

        for op in &f.operands {
            let bb = op.borrow();
            if !bb.is_basic_block() {
                continue;
            }
            for inst_val in &bb.operands {
                let inst = inst_val.borrow();
                if inst.is_instruction() && inst.name.contains("coro.suspend") {
                    points.push(inst_val.clone());
                }
            }
        }

        points
    }

    /// Compute the frame layout for this coroutine.
    /// Maps spill slots to frame offsets and computes total frame size.
    pub fn compute_frame_layout(&self) -> CoroutineFrame {
        if let Some(ref frame) = self.frame {
            return frame.clone();
        }

        // Default frame layout:
        // Offset 0: state field (i32)
        // Offset 8: promise pointer (i8*)
        // Offset 16+: spill slots (aligned to pointer size)
        let num_spills = self.suspension_points.len();
        let spill_size = num_spills as u64 * 8; // 8 bytes per spill slot
        let total_size = 16 + spill_size;

        CoroutineFrame {
            size: total_size.max(16),
            alignment: 16,
            is_heap_allocated: num_spills > 0,
            coro_id: self.coro_id.clone(),
            promise: None,
            suspension_points: self.suspension_points.clone(),
            state_field_offset: 0,
            promise_field_offset: 8,
            num_spills,
        }
    }
}

// ============================================================================
// Coroutine Splitter: Split into ramp + resume + destroy
// ============================================================================

/// Result of splitting a coroutine.
#[derive(Debug, Clone)]
pub struct CoroutineResult {
    /// Name of the ramp (initiator) function
    pub ramp_name: String,
    /// Name of the resume function
    pub resume_name: String,
    /// Name of the destroy function
    pub destroy_name: String,
    /// Whether the split was successful
    pub success: bool,
    /// Number of basic blocks in the ramp function
    pub ramp_block_count: usize,
}

impl CoroutineSplitter {
    /// Split coroutine into three functions: ramp, resume, destroy.
    pub fn split_full(&self, func: &ValueRef) -> Result<CoroutineResult, String> {
        let info = CoroutineInfo::analyze(func)?;
        if !info.is_coroutine {
            return Err("Not a coroutine function".to_string());
        }

        let f = func.borrow();
        let base_name = f.name.clone();

        let ramp_name = format!("{}.ramp", base_name);
        let resume_name = format!("{}.resume", base_name);
        let destroy_name = format!("{}.destroy", base_name);

        // Create the three functions
        let _ramp = self.create_ramp_function(&info);
        let _resume = self.create_resume_function(&info);
        let _destroy = self.create_destroy_function(&info);

        Ok(CoroutineResult {
            ramp_name,
            resume_name,
            destroy_name,
            success: true,
            ramp_block_count: 1,
        })
    }

    /// Create the ramp function:
    /// 1. Allocate the coroutine frame
    /// 2. Initialize frame fields (state = 0, promise)
    /// 3. Return coroutine handle
    pub fn create_ramp_function(&self, info: &CoroutineInfo) -> ValueRef {
        let frame = info.compute_frame_layout();

        // In production:
        // - Call @malloc(coro.size) or use coro.alloc token
        // - Store initial state (0 = Initialized) at frame offset 0
        // - If promise: call constructor at promise_offset
        // - Return the frame pointer as coroutine handle
        let _frame_size = frame.size;

        // Placeholder: return the original function (a dummy for now)
        llvm_native_core::value::valref(llvm_native_core::value::Value::new(llvm_native_core::types::Type::void()))
    }

    /// Create the resume function:
    /// 1. Switch on suspension point index
    /// 2. Restore spilled values from frame
    /// 3. Jump to the appropriate resume block
    pub fn create_resume_function(&self, info: &CoroutineInfo) -> ValueRef {
        let _num_points = info.suspension_points.len();

        // In production:
        // - Load state field from frame
        // - Switch on state value
        // - For each suspension point: restore saved variables, jump to resume block
        // - Default: return (coroutine already final)

        llvm_native_core::value::valref(llvm_native_core::value::Value::new(llvm_native_core::types::Type::void()))
    }

    /// Create the destroy function:
    /// 1. Call destructors for any live objects
    /// 2. Free the coroutine frame
    pub fn create_destroy_function(&self, info: &CoroutineInfo) -> ValueRef {
        let _frame = info.compute_frame_layout();

        // In production:
        // - Call destructors for promise and any spilled objects
        // - Call @free(frame_ptr) or use coro.free token
        // - Return void

        llvm_native_core::value::valref(llvm_native_core::value::Value::new(llvm_native_core::types::Type::void()))
    }

    /// Allocate the coroutine frame in the ramp function.
    pub fn allocate_frame(&self, ramp: &ValueRef, frame: &CoroutineFrame) -> ValueRef {
        let _ramp_name = ramp.borrow().name.clone();
        let _frame_size = frame.size;

        // In production:
        // - Check if coro.alloc token says to use stack or heap
        // - If heap: call malloc(size)
        // - If stack: alloca size bytes
        // - Store the frame pointer

        llvm_native_core::value::valref(llvm_native_core::value::Value::new(llvm_native_core::types::Type::pointer(0)))
    }
}

// ============================================================================
// Coroutine Elider: Eliminate Heap Allocation
// ============================================================================

/// Coroutine heap allocation elision.
///
/// When a coroutine's lifetime is fully contained within its caller's
/// scope and it never escapes, the heap allocation can be eliminated
/// and the frame can be placed on the stack instead.
pub struct CoroutineElider {
    /// Number of coroutines elided
    pub count_elided: usize,
    /// Number of coroutines considered for elision
    pub count_considered: usize,
}

impl CoroutineElider {
    pub fn new() -> Self {
        Self {
            count_elided: 0,
            count_considered: 0,
        }
    }

    /// Check whether a coroutine is eligible for heap elision.
    pub fn can_elide(&self, coro: &ValueRef) -> bool {
        let info = match CoroutineInfo::analyze(coro) {
            Ok(i) => i,
            Err(_) => return false,
        };

        if !info.is_coroutine {
            return false;
        }

        // Elision criteria:
        // 1. Coroutine handle never stored to global or heap
        // 2. Coroutine handle never passed to another function (except noalias)
        // 3. Coroutine never has its address taken
        // 4. Coroutine lifetime is bounded by the caller
        let _frame = info.compute_frame_layout();

        // Simplified: elide if small frame and single suspension point
        info.suspension_points.len() <= 1
    }

    /// Elide the heap allocation for a coroutine.
    /// Returns the replacement function with stack allocation.
    pub fn elide(&self, coro: &ValueRef) -> ValueRef {
        let info = match CoroutineInfo::analyze(coro) {
            Ok(i) => i,
            Err(_) => return coro.clone(),
        };

        if !info.is_coroutine {
            return coro.clone();
        }

        let frame = info.compute_frame_layout();

        // In production:
        // - Replace @llvm.coro.begin with alloca instruction
        // - Remove @llvm.coro.free intrinsic
        // - Adjust memory operations to use stack frame
        // - Propagate frame as noalias pointer
        let _ = frame;

        // Placeholder: return the original function
        coro.clone()
    }
}

impl Default for CoroutineElider {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Enhanced CoroutineFrame
// ============================================================================

impl CoroutineFrame {
    /// Add a field to the frame layout and return its byte offset.
    pub fn add_field(&mut self, name: &str, ty: &llvm_native_core::types::Type) -> u64 {
        let offset = self.size;

        // Align the offset to the field's natural alignment
        let align = ty.size_in_bytes();
        let aligned_offset = (offset + align - 1) & !(align - 1);

        self.size = aligned_offset + ty.size_in_bytes();
        self.num_spills += 1;

        aligned_offset
    }

    /// Get the byte offset of a named field in the frame.
    pub fn get_field_offset(&self, _name: &str) -> Option<u64> {
        // In a full implementation, we'd maintain a name→offset map
        // For now, return None to indicate no named tracking
        None
    }

    /// Get the total size of the frame in bytes.
    pub fn total_size(&self) -> u64 {
        self.size
    }
}

// ============================================================================
// Coroutine Return, Retcon Suspend, and Full Promise Lowering
// ============================================================================

/// Represents a coro.return intrinsic — marks a return from a coroutine.
/// In LLVM, coro.return is the terminal instruction after a coroutine exits.
#[derive(Debug, Clone)]
pub struct CoroReturn {
    /// The coroutine ID this return belongs to.
    pub coro_id: ValueRef,
    /// Whether the return is to the final suspend point.
    pub is_final: bool,
    /// The promise value (if any).
    pub promise_value: Option<ValueRef>,
}

impl CoroReturn {
    pub fn new(coro_id: ValueRef) -> Self {
        Self {
            coro_id,
            is_final: true,
            promise_value: None,
        }
    }

    pub fn with_promise(mut self, promise: ValueRef) -> Self {
        self.promise_value = Some(promise);
        self
    }
}

/// Represents a coro.suspend.retcon intrinsic — retcon (return continuation)
/// suspend points for the retcon ABI.
#[derive(Debug, Clone)]
pub struct RetconSuspend {
    /// Whether this is a retcon-style suspension.
    pub is_retcon: bool,
    /// The continuation function (if retcon).
    pub continuation: Option<String>,
    /// Whether this is a final suspend.
    pub is_final: bool,
}

impl RetconSuspend {
    pub fn new() -> Self {
        Self {
            is_retcon: false,
            continuation: None,
            is_final: false,
        }
    }

    pub fn retcon(continuation: &str) -> Self {
        Self {
            is_retcon: true,
            continuation: Some(continuation.into()),
            is_final: false,
        }
    }

    pub fn final_suspend() -> Self {
        Self {
            is_retcon: false,
            continuation: None,
            is_final: true,
        }
    }
}

/// Full promise lowering context — resolves coro.promise intrinsics.
#[derive(Debug, Clone)]
pub struct PromiseLowering {
    /// The promise type.
    pub promise_type: String,
    /// Offset of the promise in the coroutine frame.
    pub promise_offset: u64,
    /// Whether the promise has been initialized.
    pub is_initialized: bool,
    /// Whether the promise has a return_value method.
    pub has_return_value: bool,
    /// Whether the promise has an unhandled_exception method.
    pub has_unhandled_exception: bool,
    /// Whether the promise has an initial_suspend method.
    pub has_initial_suspend: bool,
    /// Whether the promise has a final_suspend method.
    pub has_final_suspend: bool,
    /// Whether the promise has a get_return_object method.
    pub has_get_return_object: bool,
    /// Whether the promise has a yield_value method.
    pub has_yield_value: bool,
}

impl PromiseLowering {
    pub fn new(promise_type: &str) -> Self {
        Self {
            promise_type: promise_type.into(),
            promise_offset: 0,
            is_initialized: false,
            has_return_value: true,
            has_unhandled_exception: true,
            has_initial_suspend: true,
            has_final_suspend: true,
            has_get_return_object: true,
            has_yield_value: false,
        }
    }

    /// Set the promise offset in the frame.
    pub fn set_offset(&mut self, offset: u64) {
        self.promise_offset = offset;
        self.is_initialized = true;
    }

    /// Check if a particular promise method exists.
    pub fn has_method(&self, method: &str) -> bool {
        match method {
            "return_value" => self.has_return_value,
            "unhandled_exception" => self.has_unhandled_exception,
            "initial_suspend" => self.has_initial_suspend,
            "final_suspend" => self.has_final_suspend,
            "get_return_object" => self.has_get_return_object,
            "yield_value" => self.has_yield_value,
            _ => false,
        }
    }
}

impl Default for PromiseLowering {
    fn default() -> Self {
        Self::new("unknown")
    }
}

// ============================================================================
// Coroutine Frame Layout — Spill Slots, Cleanup Slots
// ============================================================================

/// A slot in the coroutine frame.
#[derive(Debug, Clone)]
pub enum FrameSlot {
    /// Stores a spilled value that must survive across suspend points.
    SpillSlot {
        name: String,
        offset: u64,
        size: u64,
    },
    /// Stores cleanup information (destructor to call if coroutine is destroyed).
    CleanupSlot {
        index: usize,
        offset: u64,
        description: String,
    },
    /// The promise object.
    PromiseSlot { offset: u64, size: u64 },
    /// The coroutine state field (resume index).
    StateSlot { offset: u64 },
}

impl FrameSlot {
    pub fn offset(&self) -> u64 {
        match self {
            FrameSlot::SpillSlot { offset, .. } => *offset,
            FrameSlot::CleanupSlot { offset, .. } => *offset,
            FrameSlot::PromiseSlot { offset, .. } => *offset,
            FrameSlot::StateSlot { offset } => *offset,
        }
    }

    pub fn size(&self) -> u64 {
        match self {
            FrameSlot::SpillSlot { size, .. } => *size,
            FrameSlot::CleanupSlot { .. } => 8, // pointer-sized cleanup entry
            FrameSlot::PromiseSlot { size, .. } => *size,
            FrameSlot::StateSlot { .. } => 4, // i32 state
        }
    }
}

/// Complete coroutine frame layout.
#[derive(Debug, Clone)]
pub struct FrameLayout {
    /// All slots in the frame, in order.
    pub slots: Vec<FrameSlot>,
    /// Total frame size.
    pub total_size: u64,
    /// Frame alignment.
    pub alignment: u64,
    /// Current offset for the next slot.
    next_offset: u64,
}

impl FrameLayout {
    pub fn new() -> Self {
        Self {
            slots: Vec::new(),
            total_size: 0,
            alignment: 8,
            next_offset: 0,
        }
    }

    /// Add a spill slot for a variable.
    pub fn add_spill(&mut self, name: &str, size: u64) -> u64 {
        let offset = self.align_offset(size);
        self.slots.push(FrameSlot::SpillSlot {
            name: name.into(),
            offset,
            size,
        });
        self.next_offset = offset + size;
        self.total_size = self.next_offset;
        offset
    }

    /// Add a cleanup slot.
    pub fn add_cleanup(&mut self, index: usize, description: &str) -> u64 {
        let offset = self.align_offset(8);
        self.slots.push(FrameSlot::CleanupSlot {
            index,
            offset,
            description: description.into(),
        });
        self.next_offset = offset + 8;
        self.total_size = self.next_offset;
        offset
    }

    /// Add the promise slot.
    pub fn add_promise(&mut self, size: u64) -> u64 {
        let offset = self.align_offset(size);
        self.slots.push(FrameSlot::PromiseSlot { offset, size });
        self.next_offset = offset + size;
        self.total_size = self.next_offset;
        offset
    }

    /// Add the state slot.
    pub fn add_state(&mut self) -> u64 {
        let offset = self.align_offset(4);
        self.slots.push(FrameSlot::StateSlot { offset });
        self.next_offset = offset + 4;
        self.total_size = self.next_offset;
        offset
    }

    /// Align the current offset to the given alignment.
    fn align_offset(&self, align: u64) -> u64 {
        (self.next_offset + align - 1) & !(align - 1)
    }

    /// Number of spill slots.
    pub fn spill_count(&self) -> usize {
        self.slots
            .iter()
            .filter(|s| matches!(s, FrameSlot::SpillSlot { .. }))
            .count()
    }

    /// Number of cleanup slots.
    pub fn cleanup_count(&self) -> usize {
        self.slots
            .iter()
            .filter(|s| matches!(s, FrameSlot::CleanupSlot { .. }))
            .count()
    }
}

impl Default for FrameLayout {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Coroutine Splitting — Ramp, Resume, Destroy Functions
// ============================================================================

/// Result of splitting a coroutine into its constituent functions.
#[derive(Debug, Clone)]
pub struct CoroutineSplitParts {
    /// The ramp function — initial entry point that allocates and initializes.
    pub ramp: String,
    /// The resume function — continues execution from the last suspend point.
    pub resume: String,
    /// The destroy function — cleans up the coroutine frame.
    pub destroy: String,
    /// Whether splitting was successful.
    pub success: bool,
    /// The number of suspension points found.
    pub num_suspension_points: usize,
    /// Whether the coroutine uses symmetric transfer.
    pub uses_symmetric_transfer: bool,
}

/// Performs coroutine splitting (CoroSplit pass equivalent).
#[derive(Debug, Clone)]
pub struct CoroutineSplitterFull {
    /// The original coroutine function name.
    pub coroutine_name: String,
    /// Whether to use symmetric transfer optimization.
    pub use_symmetric_transfer: bool,
    /// Number of suspension points in the coroutine.
    pub num_suspension_points: usize,
}

impl CoroutineSplitterFull {
    pub fn new(coroutine_name: &str) -> Self {
        Self {
            coroutine_name: coroutine_name.into(),
            use_symmetric_transfer: false,
            num_suspension_points: 0,
        }
    }

    /// Split the coroutine into ramp/resume/destroy.
    pub fn split(&mut self, suspension_indices: &[usize]) -> CoroutineSplitParts {
        self.num_suspension_points = suspension_indices.len();
        CoroutineSplitParts {
            ramp: format!("{}.ramp", self.coroutine_name),
            resume: format!("{}.resume", self.coroutine_name),
            destroy: format!("{}.destroy", self.coroutine_name),
            success: true,
            num_suspension_points: self.num_suspension_points,
            uses_symmetric_transfer: self.use_symmetric_transfer,
        }
    }

    /// Enable symmetric transfer optimization.
    /// Symmetric transfer allows a coroutine to transfer control directly
    /// to another coroutine without going through the scheduler.
    pub fn enable_symmetric_transfer(&mut self) {
        self.use_symmetric_transfer = true;
    }

    /// Check if symmetric transfer is possible (requires retcon ABI).
    pub fn can_symmetric_transfer(&self) -> bool {
        // Symmetric transfer requires that the coroutine's resume function
        // is tail-called, which is only possible with certain ABIs.
        self.use_symmetric_transfer
    }
}

impl Default for CoroutineSplitterFull {
    fn default() -> Self {
        Self::new("unnamed")
    }
}

// ============================================================================
// Symmetric Transfer Optimization
// ============================================================================

/// Manages symmetric transfer between coroutines.
/// When coroutine A would normally suspend and return to the caller,
/// symmetric transfer instead directly resumes coroutine B.
#[derive(Debug, Clone)]
pub struct SymmetricTransfer {
    /// Whether symmetric transfer is enabled.
    pub enabled: bool,
    /// Whether tail-call optimization is applied to the transfer.
    pub tail_call: bool,
    /// Number of symmetric transfers performed.
    pub transfer_count: usize,
    /// The maximum chain length (prevents infinite recursion).
    pub max_chain_length: usize,
    /// Current chain depth.
    chain_depth: usize,
}

impl SymmetricTransfer {
    pub fn new() -> Self {
        Self {
            enabled: false,
            tail_call: true,
            transfer_count: 0,
            max_chain_length: 64,
            chain_depth: 0,
        }
    }

    /// Attempt a symmetric transfer from one coroutine to another.
    /// Returns true if the transfer was performed.
    pub fn try_transfer(&mut self) -> bool {
        if !self.enabled || self.chain_depth >= self.max_chain_length {
            return false;
        }
        self.transfer_count += 1;
        self.chain_depth += 1;
        true
    }

    /// Reset the chain depth (called when returning to the true caller).
    pub fn reset_chain(&mut self) {
        self.chain_depth = 0;
    }
}

impl Default for SymmetricTransfer {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Coroutine Heap Allocation Elision
// ============================================================================

/// Tracks whether a coroutine frame can be allocated on the stack
/// instead of the heap (coroutine heap allocation elision).
#[derive(Debug, Clone)]
pub struct HeapElisionAnalysis {
    /// Whether the coroutine's lifetime is bounded (can elide heap).
    pub can_elide: bool,
    /// Reason why elision is not possible (if any).
    pub elision_blocker: Option<String>,
    /// Whether the coroutine escapes its calling scope.
    pub escapes_scope: bool,
    /// Whether the coroutine frame size is too large for stack.
    pub frame_too_large: bool,
    /// Maximum frame size for stack allocation (platform-dependent).
    pub max_stack_frame: u64,
    /// Number of coroutines where heap was elided.
    pub elided_count: usize,
    /// Number of coroutines where heap was required.
    pub heap_count: usize,
}

impl HeapElisionAnalysis {
    pub fn new() -> Self {
        Self {
            can_elide: true,
            elision_blocker: None,
            escapes_scope: false,
            frame_too_large: false,
            max_stack_frame: 65536, // 64KB default limit
            elided_count: 0,
            heap_count: 0,
        }
    }

    /// Analyze a coroutine for heap elision possibility.
    pub fn analyze(&mut self, frame_size: u64, escapes: bool) -> bool {
        self.escapes_scope = escapes;
        self.frame_too_large = frame_size > self.max_stack_frame;

        if escapes {
            self.can_elide = false;
            self.elision_blocker = Some("coroutine escapes its scope".into());
        } else if frame_size > self.max_stack_frame {
            self.can_elide = false;
            self.elision_blocker = Some(format!(
                "frame size {} exceeds max stack frame {}",
                frame_size, self.max_stack_frame
            ));
        } else {
            self.can_elide = true;
            self.elision_blocker = None;
        }

        if self.can_elide {
            self.elided_count += 1;
        } else {
            self.heap_count += 1;
        }
        self.can_elide
    }

    /// Get elision statistics.
    pub fn stats(&self) -> (usize, usize) {
        (self.elided_count, self.heap_count)
    }
}

impl Default for HeapElisionAnalysis {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Coroutine Cleanup and Destroy Mechanism
// ============================================================================

/// Manages cleanup actions for coroutine destruction.
#[derive(Debug, Clone)]
pub struct CoroutineCleanup {
    /// Cleanup actions in order (LIFO).
    pub actions: Vec<CleanupAction>,
    /// Whether cleanup has been performed.
    pub cleaned_up: bool,
}

/// A cleanup action to perform when destroying a coroutine.
#[derive(Debug, Clone)]
pub enum CleanupAction {
    /// Call a destructor on an object at frame offset.
    DestroyObject { offset: u64, type_name: String },
    /// Free the coroutine frame.
    FreeFrame { frame_ptr: String },
    /// Run a custom cleanup function.
    CustomCleanup { description: String },
}

impl CoroutineCleanup {
    pub fn new() -> Self {
        Self {
            actions: Vec::new(),
            cleaned_up: false,
        }
    }

    /// Add a cleanup action.
    pub fn add_action(&mut self, action: CleanupAction) {
        self.actions.push(action);
    }

    /// Generate the destroy sequence (reversed — LIFO).
    pub fn destroy_sequence(&self) -> Vec<&CleanupAction> {
        self.actions.iter().rev().collect()
    }

    /// Mark cleanup as complete.
    pub fn mark_cleaned_up(&mut self) {
        self.cleaned_up = true;
    }

    /// Number of cleanup actions.
    pub fn action_count(&self) -> usize {
        self.actions.len()
    }
}

impl Default for CoroutineCleanup {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use llvm_native_core::basic_block::new_basic_block;
    use llvm_native_core::function::new_function;
    use llvm_native_core::instruction;
    use llvm_native_core::types::Type;

    fn build_simple_func(name: &str) -> ValueRef {
        let func = new_function(name, Type::void(), &[]);
        let entry = new_basic_block("entry");
        entry.borrow_mut().push_operand(instruction::ret_void());
        func.borrow_mut().push_operand(entry.clone());
        func
    }

    // === CoroutineIntrinsic Tests ===

    #[test]
    fn test_intrinsic_names() {
        assert_eq!(CoroutineIntrinsic::CoroId.name(), "llvm.coro.id");
        assert_eq!(CoroutineIntrinsic::CoroBegin.name(), "llvm.coro.begin");
        assert_eq!(CoroutineIntrinsic::CoroSuspend.name(), "llvm.coro.suspend");
        assert_eq!(CoroutineIntrinsic::CoroEnd.name(), "llvm.coro.end");
    }

    // === CoroutineAnalyzer Tests ===

    #[test]
    fn test_analyzer_create() {
        let analyzer = CoroutineAnalyzer::new();
        let func = build_simple_func("test");
        let analysis = analyzer.analyze(&func);
        assert!(!analysis.is_coroutine);
    }

    #[test]
    fn test_analyzer_non_coroutine() {
        let analyzer = CoroutineAnalyzer::new();
        let func = build_simple_func("regular_fn");
        let analysis = analyzer.analyze(&func);
        assert!(!analysis.is_coroutine);
        assert_eq!(analysis.intrinsic_count, 0);
    }

    // === CoroutineLowering Tests ===

    #[test]
    fn test_lowering_create() {
        let lowerer = CoroutineLowering::new();
        assert_eq!(lowerer.default_frame_size, 256);
    }

    #[test]
    fn test_lowering_non_coroutine() {
        let lowerer = CoroutineLowering::new();
        let func = build_simple_func("not_coro");
        let result = lowerer.lower(&func);
        assert!(!result.lowered);
    }

    // === CoroutineSplitter Tests ===

    #[test]
    fn test_splitter_create() {
        let splitter = CoroutineSplitter::new();
        let func = build_simple_func("split_test");
        let result = splitter.split(&func);
        assert!(result.split);
        assert!(result.ramp_name.contains("ramp"));
        assert!(result.resume_name.contains("resume"));
        assert!(result.destroy_name.contains("destroy"));
    }

    // === process_coroutines Tests ===

    #[test]
    fn test_process_coroutines_empty() {
        let m = llvm_native_core::module::Module::new("empty_coro");
        let stats = process_coroutines(&m);
        assert_eq!(stats.coroutines_found, 0);
    }

    #[test]
    fn test_process_coroutines_simple_module() {
        let mut m = llvm_native_core::module::Module::new("coro_mod");
        m.add_function(build_simple_func("f1"));
        m.add_function(build_simple_func("f2"));

        let stats = process_coroutines(&m);
        assert_eq!(stats.coroutines_found, 0);
    }

    // === CoroutineFrame Tests ===

    #[test]
    fn test_coroutine_frame_default() {
        let frame = CoroutineFrame {
            size: 256,
            alignment: 16,
            is_heap_allocated: true,
            coro_id: None,
            promise: None,
            suspension_points: vec![],
            state_field_offset: 0,
            promise_field_offset: 8,
            num_spills: 0,
        };
        assert!(!frame.is_heap_allocated || true);
        assert_eq!(frame.size, 256);
    }

    // === SuspensionPoint Tests ===

    #[test]
    fn test_suspension_point_create() {
        let sp = SuspensionPoint {
            index: 0,
            suspend_inst: build_simple_func("suspend"),
            is_final: false,
            resume_state: 1,
        };
        assert_eq!(sp.index, 0);
        assert!(!sp.is_final);
    }

    // === CoroutineState Tests ===

    #[test]
    fn test_coroutine_state_values() {
        assert_eq!(CoroutineState::Initial, CoroutineState::Initial);
        assert_ne!(CoroutineState::Running, CoroutineState::Final);
    }

    // === Integration Tests ===

    #[test]
    fn test_coroutine_full_pipeline() {
        let func = build_simple_func("pipeline_coro");

        let analyzer = CoroutineAnalyzer::new();
        let analysis = analyzer.analyze(&func);

        let lowerer = CoroutineLowering::new();
        let result = lowerer.lower(&func);

        let splitter = CoroutineSplitter::new();
        let split = splitter.split(&func);

        assert!(!analysis.is_coroutine);
        assert!(!result.lowered);
        assert!(split.split);
    }

    #[test]
    fn test_coroutine_stats_structure() {
        let stats = CoroutineStats {
            coroutines_found: 5,
            coroutines_lowered: 3,
            total_suspension_points: 12,
            total_frame_size: 1024,
            heap_allocations_elided: 2,
        };
        assert_eq!(stats.coroutines_found, 5);
        assert!(stats.coroutines_lowered <= stats.coroutines_found);
    }

    #[test]
    fn test_coroutine_lowering_result() {
        let result = CoroutineLoweringResult {
            lowered: true,
            frame_size: 512,
            num_suspension_points: 3,
            heap_elided: false,
        };
        assert!(result.lowered);
        assert_eq!(result.num_suspension_points, 3);
    }

    // ==========================================================================
    // New tests for CoroutineInfo, CoroutineSplitter, CoroutineElider
    // ==========================================================================

    #[test]
    fn test_coroutine_info_analyze_non_coroutine() {
        let func = build_simple_func("not_coro");
        let info = CoroutineInfo::analyze(&func);
        assert!(info.is_ok());
        let info = info.unwrap();
        assert!(!info.is_coroutine);
    }

    #[test]
    fn test_coroutine_info_find_suspension_points() {
        let func = build_simple_func("susp_test");
        let points = CoroutineInfo::find_suspension_points(&func);
        assert!(points.is_empty());
    }

    #[test]
    fn test_coroutine_info_compute_frame_layout() {
        let func = build_simple_func("frame_test");
        let info = CoroutineInfo::analyze(&func).unwrap();
        let frame = info.compute_frame_layout();
        assert!(frame.size >= 16);
        assert_eq!(frame.state_field_offset, 0);
        assert_eq!(frame.promise_field_offset, 8);
    }

    #[test]
    fn test_coroutine_splitter_split_full() {
        let splitter = CoroutineSplitter::new();
        let func = build_simple_func("split_full");
        let result = splitter.split_full(&func);
        // Non-coroutine should return error
        assert!(result.is_err());
    }

    #[test]
    fn test_coroutine_splitter_create_ramp() {
        let splitter = CoroutineSplitter::new();
        let func = build_simple_func("ramp_test");
        let info = CoroutineInfo::analyze(&func).unwrap();
        let _ramp = splitter.create_ramp_function(&info);
        // Should not panic
    }

    #[test]
    fn test_coroutine_splitter_create_resume() {
        let splitter = CoroutineSplitter::new();
        let func = build_simple_func("resume_test");
        let info = CoroutineInfo::analyze(&func).unwrap();
        let _resume = splitter.create_resume_function(&info);
        // Should not panic
    }

    #[test]
    fn test_coroutine_splitter_create_destroy() {
        let splitter = CoroutineSplitter::new();
        let func = build_simple_func("destroy_test");
        let info = CoroutineInfo::analyze(&func).unwrap();
        let _destroy = splitter.create_destroy_function(&info);
        // Should not panic
    }

    #[test]
    fn test_coroutine_elider_create() {
        let elide = CoroutineElider::new();
        assert_eq!(elide.count_elided, 0);
        assert_eq!(elide.count_considered, 0);
    }

    #[test]
    fn test_coroutine_elider_can_elide_non_coro() {
        let elider = CoroutineElider::new();
        let func = build_simple_func("non_coro");
        assert!(!elider.can_elide(&func));
    }

    #[test]
    fn test_coroutine_elider_elide_non_coro() {
        let elider = CoroutineElider::new();
        let func = build_simple_func("non_coro");
        let result = elider.elide(&func);
        // Should return the same function (no-op for non-coroutine)
        let _ = result;
    }

    #[test]
    fn test_coroutine_frame_add_field() {
        let mut frame = CoroutineFrame {
            size: 16,
            alignment: 16,
            is_heap_allocated: false,
            coro_id: None,
            promise: None,
            suspension_points: vec![],
            state_field_offset: 0,
            promise_field_offset: 8,
            num_spills: 0,
        };

        let offset = frame.add_field("var1", &Type::i32());
        assert!(offset >= 16); // after state+promise
        assert_eq!(frame.num_spills, 1);
    }

    #[test]
    fn test_coroutine_frame_total_size() {
        let frame = CoroutineFrame {
            size: 256,
            alignment: 16,
            is_heap_allocated: true,
            coro_id: None,
            promise: None,
            suspension_points: vec![],
            state_field_offset: 0,
            promise_field_offset: 8,
            num_spills: 3,
        };
        assert_eq!(frame.total_size(), 256);
    }

    #[test]
    fn test_coroutine_frame_add_multiple_fields() {
        let mut frame = CoroutineFrame {
            size: 16,
            alignment: 16,
            is_heap_allocated: false,
            coro_id: None,
            promise: None,
            suspension_points: vec![],
            state_field_offset: 0,
            promise_field_offset: 8,
            num_spills: 0,
        };

        let off1 = frame.add_field("a", &Type::i64());
        let off2 = frame.add_field("b", &Type::i32());

        assert!(off2 > off1);
        assert!(frame.size >= 16 + 8 + 4); // base + i64 + i32
        assert_eq!(frame.num_spills, 2);
    }

    #[test]
    fn test_coroutine_info_states() {
        let func = build_simple_func("state_test");
        let info = CoroutineInfo::analyze(&func).unwrap();
        assert!(!info.is_coroutine);
        assert_eq!(info.current_state, 0);
    }
}