llvm-native-core 0.1.2

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
//! Clang Optimizer Integration
//!
//! Implements the optimization pipeline construction from command-line flags,
//! modeling the LLVM pass pipeline builder. Supports all standard optimization
//! levels (-O0 through -Oz) and optimization flags.
//!
//! Features:
//! - Pass pipeline construction per optimization level
//! - Size optimization levels (Os, Oz)
//! - Fast-math flags (-ffast-math)
//! - Frame pointer control (-fno-omit-frame-pointer)
//! - Vectorization control (-fvectorize/-fno-vectorize)
//! - Inline control (-finline-functions/-fno-inline-functions)
//! - LTO pipeline construction (-flto/-flto=thin)
//! - Optimization remark emission
//! - PassBuilder for building pipelines from flags

use std::collections::BTreeMap;
use std::fmt;

// ── Optimization Level ────────────────────────────────────────────────────

/// Optimization level for the compiler pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ClangOptLevel {
    /// No optimization, fastest compilation.
    O0,
    /// Basic optimizations (mem2reg, instcombine, simplifycfg, dce, licm).
    O1,
    /// Moderate optimizations (+gvn, earlycse, loop-rotate, loop-unroll, slp-vectorize).
    O2,
    /// Aggressive optimizations (+loop-vectorize, aggressive-instcombine, argpromotion).
    O3,
    /// Optimize for size (favor smaller code).
    Os,
    /// Optimize aggressively for size.
    Oz,
}

impl ClangOptLevel {
    /// Parse from a string like "O0", "O2", "Os", etc.
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_uppercase().as_str() {
            "O0" | "0" => Some(Self::O0),
            "O1" | "1" => Some(Self::O1),
            "O2" | "2" => Some(Self::O2),
            "O3" | "3" => Some(Self::O3),
            "OS" => Some(Self::Os),
            "OZ" => Some(Self::Oz),
            _ => None,
        }
    }

    /// Convert to a command-line flag.
    pub fn to_flag(&self) -> String {
        match self {
            Self::O0 => "-O0".into(),
            Self::O1 => "-O1".into(),
            Self::O2 => "-O2".into(),
            Self::O3 => "-O3".into(),
            Self::Os => "-Os".into(),
            Self::Oz => "-Oz".into(),
        }
    }

    /// Whether this level performs any optimization.
    pub fn is_optimizing(&self) -> bool {
        !matches!(self, Self::O0)
    }

    /// Whether this level targets size over speed.
    pub fn is_size_optimized(&self) -> bool {
        matches!(self, Self::Os | Self::Oz)
    }

    /// Whether this level is aggressive (O3 or Oz).
    pub fn is_aggressive(&self) -> bool {
        matches!(self, Self::O3 | Self::Oz)
    }

    /// Get a human-readable description.
    pub fn description(&self) -> &'static str {
        match self {
            Self::O0 => "No optimization, fast compile",
            Self::O1 => "Basic optimizations (mem2reg, instcombine, simplifycfg, dce, licm)",
            Self::O2 => "Moderate optimizations (+gvn, earlycse, loop-rotate, loop-unroll, slp-vectorize)",
            Self::O3 => "Aggressive optimizations (+loop-vectorize, aggressive-instcombine, argpromotion)",
            Self::Os => "Optimize for size (favor smaller code)",
            Self::Oz => "Aggressive size optimization (minsize, no unrolling, no vectorization)",
        }
    }

    /// Default inline threshold for this level.
    pub fn inline_threshold(&self) -> u32 {
        match self {
            Self::O0 => 0,
            Self::O1 => 75,
            Self::O2 => 225,
            Self::O3 => 275,
            Self::Os => 75,
            Self::Oz => 25,
        }
    }
}

impl fmt::Display for ClangOptLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::O0 => write!(f, "O0"),
            Self::O1 => write!(f, "O1"),
            Self::O2 => write!(f, "O2"),
            Self::O3 => write!(f, "O3"),
            Self::Os => write!(f, "Os"),
            Self::Oz => write!(f, "Oz"),
        }
    }
}

// ── Optimization Pipeline Passes ──────────────────────────────────────────

/// Names of standard LLVM optimization passes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PassName {
    // Scalar passes
    PromoteMemoryToRegister,
    InstructionCombining,
    SimplifyCFG,
    DeadCodeElimination,
    GlobalValueNumbering,
    EarlyCSE,
    LoopInvariantCodeMotion,
    LoopRotate,
    LoopUnroll,
    LoopUnswitch,
    LoopIdiom,
    LoopDeletion,
    LoopSimplify,
    LoopDistribute,
    // Vectorization
    SLPVectorize,
    LoopVectorize,
    // Aggressive passes
    AggressiveInstCombine,
    ArgumentPromotion,
    IPSCCP,
    CalledValuePropagation,
    GlobalOptimizer,
    GlobalDCE,
    // Inline
    Inline,
    AlwaysInliner,
    // Cleanup passes
    CFGSimplification,
    Reassociate,
    SCCP,
    JumpThreading,
    CorrelatedValuePropagation,
    TailCallElimination,
    MemCpyOptimization,
    DeadStoreElimination,
    // IPO passes
    FunctionAttrs,
    StripDeadPrototypes,
    GlobalMerge,
    MergeFunctions,
    // LTO
    LTOGlobalDCE,
    LTOInternalize,
    LTOArgumentPromotion,
    LTODeadArgumentElimination,
}

impl PassName {
    /// Human-readable pass name.
    pub fn name(&self) -> &'static str {
        match self {
            Self::PromoteMemoryToRegister => "mem2reg",
            Self::InstructionCombining => "instcombine",
            Self::SimplifyCFG => "simplifycfg",
            Self::DeadCodeElimination => "dce",
            Self::GlobalValueNumbering => "gvn",
            Self::EarlyCSE => "early-cse",
            Self::LoopInvariantCodeMotion => "licm",
            Self::LoopRotate => "loop-rotate",
            Self::LoopUnroll => "loop-unroll",
            Self::LoopUnswitch => "loop-unswitch",
            Self::LoopIdiom => "loop-idiom",
            Self::LoopDeletion => "loop-deletion",
            Self::LoopSimplify => "loop-simplify",
            Self::LoopDistribute => "loop-distribute",
            Self::SLPVectorize => "slp-vectorizer",
            Self::LoopVectorize => "loop-vectorize",
            Self::AggressiveInstCombine => "aggressive-instcombine",
            Self::ArgumentPromotion => "argpromotion",
            Self::IPSCCP => "ipsccp",
            Self::CalledValuePropagation => "called-value-propagation",
            Self::GlobalOptimizer => "globalopt",
            Self::GlobalDCE => "globaldce",
            Self::Inline => "inline",
            Self::AlwaysInliner => "always-inline",
            Self::CFGSimplification => "simplifycfg",
            Self::Reassociate => "reassociate",
            Self::SCCP => "sccp",
            Self::JumpThreading => "jump-threading",
            Self::CorrelatedValuePropagation => "correlated-propagation",
            Self::TailCallElimination => "tailcallelim",
            Self::MemCpyOptimization => "memcpyopt",
            Self::DeadStoreElimination => "dse",
            Self::FunctionAttrs => "functionattrs",
            Self::StripDeadPrototypes => "strip-dead-prototypes",
            Self::GlobalMerge => "global-merge",
            Self::MergeFunctions => "mergefunc",
            Self::LTOGlobalDCE => "globaldce",
            Self::LTOInternalize => "internalize",
            Self::LTOArgumentPromotion => "argpromotion",
            Self::LTODeadArgumentElimination => "deadargelim",
        }
    }
}

// ── Pipeline Construction ─────────────────────────────────────────────────

/// Configuration for building an optimization pipeline.
#[derive(Debug, Clone)]
pub struct OptimizationPipelineConfig {
    /// Base optimization level.
    pub opt_level: ClangOptLevel,
    /// Whether to enable fast-math optimizations.
    pub fast_math: bool,
    /// Whether to omit the frame pointer.
    pub omit_frame_pointer: bool,
    /// Whether to enable automatic vectorization.
    pub vectorize: bool,
    /// Whether to enable SLP vectorization.
    pub slp_vectorize: bool,
    /// Whether to enable function inlining.
    pub inline_functions: bool,
    /// Inline threshold (0 = use default for opt level).
    pub inline_threshold: u32,
    /// Whether to enable LTO.
    pub lto: bool,
    /// Whether to use ThinLTO.
    pub thin_lto: bool,
    /// Whether to strip debug info.
    pub strip_debug: bool,
    /// Whether to enable profile-guided optimization.
    pub pgo: bool,
    /// Custom passes to add to the pipeline.
    pub custom_passes: Vec<PassName>,
    /// Passes to exclude from the pipeline.
    pub excluded_passes: Vec<PassName>,
    /// Whether to emit optimization remarks.
    pub emit_remarks: bool,
    /// Remark output format.
    pub remark_format: RemarkFormat,
    /// Target CPU for tuning.
    pub target_cpu: Option<String>,
    /// Whether to disable all optimizations (overrides opt_level).
    pub disable_optimizations: bool,
    /// Whether to enable sanitizers (may disable some optimizations).
    pub sanitize: bool,
}

impl Default for OptimizationPipelineConfig {
    fn default() -> Self {
        Self {
            opt_level: ClangOptLevel::O2,
            fast_math: false,
            omit_frame_pointer: true,
            vectorize: true,
            slp_vectorize: true,
            inline_functions: true,
            inline_threshold: 0,
            lto: false,
            thin_lto: false,
            strip_debug: false,
            pgo: false,
            custom_passes: Vec::new(),
            excluded_passes: Vec::new(),
            emit_remarks: false,
            remark_format: RemarkFormat::YAML,
            target_cpu: None,
            disable_optimizations: false,
            sanitize: false,
        }
    }
}

impl OptimizationPipelineConfig {
    /// Create config for a specific opt level.
    pub fn for_level(level: ClangOptLevel) -> Self {
        let mut config = Self::default();
        config.opt_level = level;
        match level {
            ClangOptLevel::O0 => {
                config.vectorize = false;
                config.slp_vectorize = false;
                config.inline_functions = false;
            }
            ClangOptLevel::Os | ClangOptLevel::Oz => {
                config.vectorize = false;
                config.slp_vectorize = false;
                config.inline_functions = true;
            }
            _ => {}
        }
        config
    }

    /// Enable fast-math.
    pub fn with_fast_math(mut self) -> Self {
        self.fast_math = true;
        self
    }

    /// Disable frame pointer omission.
    pub fn with_frame_pointer(mut self) -> Self {
        self.omit_frame_pointer = false;
        self
    }

    /// Enable/disable vectorization.
    pub fn with_vectorize(mut self, enabled: bool) -> Self {
        self.vectorize = enabled;
        self
    }

    /// Enable LTO.
    pub fn with_lto(mut self, thin: bool) -> Self {
        self.lto = true;
        self.thin_lto = thin;
        self
    }

    /// Enable remarks.
    pub fn with_remarks(mut self, format: RemarkFormat) -> Self {
        self.emit_remarks = true;
        self.remark_format = format;
        self
    }

    /// Add a custom pass.
    pub fn add_pass(mut self, pass: PassName) -> Self {
        self.custom_passes.push(pass);
        self
    }

    /// Exclude a pass.
    pub fn exclude_pass(mut self, pass: PassName) -> Self {
        self.excluded_passes.push(pass);
        self
    }
}

// ── Pass Pipeline ─────────────────────────────────────────────────────────

/// A single entry in an optimization pipeline.
#[derive(Debug, Clone)]
pub struct PipelinePass {
    /// The pass name.
    pub name: PassName,
    /// Whether this pass is enabled.
    pub enabled: bool,
    /// Custom parameters for the pass.
    pub params: BTreeMap<String, String>,
}

impl PipelinePass {
    /// Create a new enabled pass.
    pub fn new(name: PassName) -> Self {
        Self {
            name,
            enabled: true,
            params: BTreeMap::new(),
        }
    }

    /// Create a disabled pass.
    pub fn disabled(name: PassName) -> Self {
        Self {
            name,
            enabled: false,
            params: BTreeMap::new(),
        }
    }

    /// Add a parameter.
    pub fn with_param(mut self, key: &str, value: &str) -> Self {
        self.params.insert(key.to_string(), value.to_string());
        self
    }
}

/// An ordered sequence of optimization passes for a specific optimization level.
#[derive(Debug, Clone)]
pub struct PassPipeline {
    /// Optimization level this pipeline targets.
    pub opt_level: ClangOptLevel,
    /// Ordered list of passes.
    pub passes: Vec<PipelinePass>,
    /// Pipeline description.
    pub description: String,
}

impl PassPipeline {
    /// Create an empty pipeline.
    pub fn new(opt_level: ClangOptLevel) -> Self {
        Self {
            opt_level,
            passes: Vec::new(),
            description: String::new(),
        }
    }

    /// Add a pass to the pipeline.
    pub fn add_pass(&mut self, pass: PipelinePass) {
        self.passes.push(pass);
    }

    /// Get the number of enabled passes.
    pub fn enabled_pass_count(&self) -> usize {
        self.passes.iter().filter(|p| p.enabled).count()
    }

    /// List all enabled pass names.
    pub fn enabled_pass_names(&self) -> Vec<String> {
        self.passes
            .iter()
            .filter(|p| p.enabled)
            .map(|p| p.name.name().to_string())
            .collect()
    }
}

// ── Pipeline Builder ──────────────────────────────────────────────────────

/// Builds the optimization pipeline for a given optimization level.
pub fn build_optimization_pipeline(level: ClangOptLevel) -> PassPipeline {
    let mut pipeline = PassPipeline::new(level);
    pipeline.description = level.description().to_string();

    let passes = match level {
        ClangOptLevel::O0 => o0_passes(),
        ClangOptLevel::O1 => o1_passes(),
        ClangOptLevel::O2 => o2_passes(),
        ClangOptLevel::O3 => o3_passes(),
        ClangOptLevel::Os => os_passes(),
        ClangOptLevel::Oz => oz_passes(),
    };

    for pass in passes {
        pipeline.add_pass(pass);
    }

    pipeline
}

/// Build the O0 pipeline (no optimization).
fn o0_passes() -> Vec<PipelinePass> {
    vec![
        PipelinePass::new(PassName::AlwaysInliner),
        PipelinePass::disabled(PassName::PromoteMemoryToRegister),
        PipelinePass::disabled(PassName::InstructionCombining),
        PipelinePass::disabled(PassName::SimplifyCFG),
    ]
}

/// Build the O1 pipeline (basic optimizations).
fn o1_passes() -> Vec<PipelinePass> {
    vec![
        PipelinePass::new(PassName::PromoteMemoryToRegister),
        PipelinePass::new(PassName::InstructionCombining),
        PipelinePass::new(PassName::SimplifyCFG),
        PipelinePass::new(PassName::DeadCodeElimination),
        PipelinePass::new(PassName::LoopInvariantCodeMotion),
        PipelinePass::new(PassName::SCCP),
        PipelinePass::new(PassName::Reassociate),
        PipelinePass::new(PassName::CFGSimplification),
        PipelinePass::new(PassName::TailCallElimination),
        PipelinePass::new(PassName::MemCpyOptimization),
        PipelinePass::new(PassName::DeadStoreElimination),
        PipelinePass::new(PassName::FunctionAttrs),
    ]
}

/// Build the O2 pipeline (moderate optimizations).
fn o2_passes() -> Vec<PipelinePass> {
    vec![
        PipelinePass::new(PassName::PromoteMemoryToRegister),
        PipelinePass::new(PassName::InstructionCombining),
        PipelinePass::new(PassName::SimplifyCFG),
        PipelinePass::new(PassName::DeadCodeElimination),
        PipelinePass::new(PassName::GlobalValueNumbering),
        PipelinePass::new(PassName::EarlyCSE),
        PipelinePass::new(PassName::LoopRotate),
        PipelinePass::new(PassName::LoopInvariantCodeMotion),
        PipelinePass::new(PassName::LoopUnroll).with_param("threshold", "150"),
        PipelinePass::new(PassName::SLPVectorize),
        PipelinePass::new(PassName::SCCP),
        PipelinePass::new(PassName::Reassociate),
        PipelinePass::new(PassName::JumpThreading),
        PipelinePass::new(PassName::CorrelatedValuePropagation),
        PipelinePass::new(PassName::CFGSimplification),
        PipelinePass::new(PassName::TailCallElimination),
        PipelinePass::new(PassName::MemCpyOptimization),
        PipelinePass::new(PassName::DeadStoreElimination),
        PipelinePass::new(PassName::FunctionAttrs),
        PipelinePass::new(PassName::GlobalDCE),
    ]
}

/// Build the O3 pipeline (aggressive optimizations).
fn o3_passes() -> Vec<PipelinePass> {
    vec![
        PipelinePass::new(PassName::PromoteMemoryToRegister),
        PipelinePass::new(PassName::InstructionCombining),
        PipelinePass::new(PassName::SimplifyCFG),
        PipelinePass::new(PassName::DeadCodeElimination),
        PipelinePass::new(PassName::GlobalValueNumbering),
        PipelinePass::new(PassName::EarlyCSE),
        PipelinePass::new(PassName::LoopRotate),
        PipelinePass::new(PassName::LoopInvariantCodeMotion),
        PipelinePass::new(PassName::LoopUnroll).with_param("threshold", "300"),
        PipelinePass::new(PassName::LoopVectorize),
        PipelinePass::new(PassName::SLPVectorize),
        PipelinePass::new(PassName::AggressiveInstCombine),
        PipelinePass::new(PassName::ArgumentPromotion),
        PipelinePass::new(PassName::IPSCCP),
        PipelinePass::new(PassName::CalledValuePropagation),
        PipelinePass::new(PassName::GlobalOptimizer),
        PipelinePass::new(PassName::SCCP),
        PipelinePass::new(PassName::Reassociate),
        PipelinePass::new(PassName::JumpThreading),
        PipelinePass::new(PassName::CorrelatedValuePropagation),
        PipelinePass::new(PassName::CFGSimplification),
        PipelinePass::new(PassName::TailCallElimination),
        PipelinePass::new(PassName::MemCpyOptimization),
        PipelinePass::new(PassName::DeadStoreElimination),
        PipelinePass::new(PassName::FunctionAttrs),
        PipelinePass::new(PassName::GlobalDCE),
        PipelinePass::new(PassName::MergeFunctions),
    ]
}

/// Build the Os pipeline (size optimization).
fn os_passes() -> Vec<PipelinePass> {
    vec![
        PipelinePass::new(PassName::PromoteMemoryToRegister),
        PipelinePass::new(PassName::InstructionCombining),
        PipelinePass::new(PassName::SimplifyCFG),
        PipelinePass::new(PassName::DeadCodeElimination),
        PipelinePass::new(PassName::GlobalValueNumbering),
        PipelinePass::new(PassName::EarlyCSE),
        PipelinePass::new(PassName::LoopRotate),
        PipelinePass::new(PassName::LoopInvariantCodeMotion),
        // No LoopUnroll for size
        PipelinePass::new(PassName::SCCP),
        PipelinePass::new(PassName::Reassociate),
        PipelinePass::new(PassName::JumpThreading),
        PipelinePass::new(PassName::CFGSimplification),
        PipelinePass::new(PassName::TailCallElimination),
        PipelinePass::new(PassName::MemCpyOptimization),
        PipelinePass::new(PassName::DeadStoreElimination),
        PipelinePass::new(PassName::FunctionAttrs),
        PipelinePass::new(PassName::GlobalDCE),
        PipelinePass::new(PassName::MergeFunctions),
    ]
}

/// Build the Oz pipeline (aggressive size optimization).
fn oz_passes() -> Vec<PipelinePass> {
    vec![
        PipelinePass::new(PassName::PromoteMemoryToRegister),
        PipelinePass::new(PassName::InstructionCombining),
        PipelinePass::new(PassName::SimplifyCFG),
        PipelinePass::new(PassName::DeadCodeElimination),
        PipelinePass::new(PassName::GlobalValueNumbering),
        PipelinePass::new(PassName::EarlyCSE),
        PipelinePass::new(PassName::LoopRotate),
        PipelinePass::new(PassName::LoopInvariantCodeMotion),
        // No LoopUnroll, No LoopVectorize, No SLPVectorize
        PipelinePass::new(PassName::SCCP),
        PipelinePass::new(PassName::Reassociate),
        PipelinePass::new(PassName::JumpThreading),
        PipelinePass::new(PassName::CFGSimplification),
        PipelinePass::new(PassName::TailCallElimination),
        PipelinePass::new(PassName::MemCpyOptimization),
        PipelinePass::new(PassName::DeadStoreElimination),
        PipelinePass::new(PassName::FunctionAttrs),
        PipelinePass::new(PassName::GlobalDCE),
        PipelinePass::new(PassName::MergeFunctions),
    ]
}

/// Build the LTO pipeline (for link-time optimization).
pub fn build_lto_pipeline(thin: bool) -> PassPipeline {
    let mut pipeline = PassPipeline::new(ClangOptLevel::O2);
    pipeline.description = if thin {
        "ThinLTO pipeline"
    } else {
        "Full LTO pipeline"
    }
    .to_string();

    let passes = vec![
        PipelinePass::new(PassName::LTOGlobalDCE),
        PipelinePass::new(PassName::LTOInternalize),
        PipelinePass::new(PassName::LTOArgumentPromotion),
        PipelinePass::new(PassName::LTODeadArgumentElimination),
    ];

    for pass in passes {
        pipeline.add_pass(pass);
    }

    pipeline
}

// ── Optimization Flags ────────────────────────────────────────────────────

/// All recognized optimization flags and their pipeline effects.
#[derive(Debug, Clone)]
pub struct OptimizationFlags {
    /// Fast math mode.
    pub fast_math: bool,
    /// Disable frame pointer elimination.
    pub no_omit_frame_pointer: bool,
    /// Enable auto-vectorization.
    pub vectorize: bool,
    /// Disable auto-vectorization.
    pub no_vectorize: bool,
    /// Enable SLP vectorization.
    pub slp_vectorize: bool,
    /// Disable SLP vectorization.
    pub no_slp_vectorize: bool,
    /// Enable function inlining.
    pub inline_functions: bool,
    /// Disable function inlining.
    pub no_inline_functions: bool,
    /// Enable LTO.
    pub lto: bool,
    /// Enable ThinLTO.
    pub thin_lto: bool,
    /// Disable all optimizations.
    pub opt_disable: bool,
    /// Custom inline threshold.
    pub inline_threshold: Option<u32>,
    /// Strip debug info.
    pub strip_debug: bool,
    /// Sanitize mode.
    pub sanitize_address: bool,
    pub sanitize_memory: bool,
    pub sanitize_undefined: bool,
    pub sanitize_thread: bool,
}

impl Default for OptimizationFlags {
    fn default() -> Self {
        Self {
            fast_math: false,
            no_omit_frame_pointer: false,
            vectorize: true,
            no_vectorize: false,
            slp_vectorize: true,
            no_slp_vectorize: false,
            inline_functions: true,
            no_inline_functions: false,
            lto: false,
            thin_lto: false,
            opt_disable: false,
            inline_threshold: None,
            strip_debug: false,
            sanitize_address: false,
            sanitize_memory: false,
            sanitize_undefined: false,
            sanitize_thread: false,
        }
    }
}

impl OptimizationFlags {
    /// Create flags from a list of command-line arguments.
    pub fn from_args(args: &[String]) -> Self {
        let mut flags = Self::default();
        for arg in args {
            match arg.as_str() {
                "-ffast-math" => flags.fast_math = true,
                "-fno-omit-frame-pointer" => flags.no_omit_frame_pointer = true,
                "-fomit-frame-pointer" => flags.no_omit_frame_pointer = false,
                "-fvectorize" => {
                    flags.vectorize = true;
                    flags.no_vectorize = false;
                }
                "-fno-vectorize" => {
                    flags.no_vectorize = true;
                    flags.vectorize = false;
                }
                "-fslp-vectorize" => {
                    flags.slp_vectorize = true;
                    flags.no_slp_vectorize = false;
                }
                "-fno-slp-vectorize" => {
                    flags.no_slp_vectorize = true;
                    flags.slp_vectorize = false;
                }
                "-finline-functions" => flags.inline_functions = true,
                "-fno-inline-functions" => {
                    flags.inline_functions = false;
                    flags.no_inline_functions = true;
                }
                "-flto" => {
                    flags.lto = true;
                    flags.thin_lto = false;
                }
                "-flto=thin" => {
                    flags.thin_lto = true;
                    flags.lto = true;
                }
                "-fno-lto" => {
                    flags.lto = false;
                    flags.thin_lto = false;
                }
                "-g0" | "-g0" => flags.strip_debug = true,
                "-fsanitize=address" => flags.sanitize_address = true,
                "-fsanitize=memory" => flags.sanitize_memory = true,
                "-fsanitize=undefined" => flags.sanitize_undefined = true,
                "-fsanitize=thread" => flags.sanitize_thread = true,
                _ => {
                    if arg.starts_with("-mllvm -inline-threshold=") {
                        if let Some(val) = arg.split('=').nth(1) {
                            flags.inline_threshold = val.parse().ok();
                        }
                    }
                }
            }
        }
        flags
    }

    /// Merge flags into the pipeline config.
    pub fn apply_to_config(&self, config: &mut OptimizationPipelineConfig) {
        config.fast_math = self.fast_math;
        config.omit_frame_pointer = !self.no_omit_frame_pointer;
        if self.no_vectorize {
            config.vectorize = false;
        } else if self.vectorize {
            config.vectorize = true;
        }
        if self.no_slp_vectorize {
            config.slp_vectorize = false;
        } else if self.slp_vectorize {
            config.slp_vectorize = true;
        }
        if self.no_inline_functions {
            config.inline_functions = false;
        }
        if self.lto {
            config.lto = true;
            config.thin_lto = self.thin_lto;
        }
        if let Some(threshold) = self.inline_threshold {
            config.inline_threshold = threshold;
        }
    }
}

// ── Optimization Remark Emitter ───────────────────────────────────────────

/// Remark format options.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemarkFormat {
    /// YAML-structured remarks.
    YAML,
    /// JSON-structured remarks.
    JSON,
    /// Bitstream remarks.
    Bitstream,
}

/// Kinds of optimization remarks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemarkKind {
    /// A missed optimization opportunity.
    Missed,
    /// Analysis information.
    Analysis,
    /// A successfully applied optimization.
    Passed,
    /// Other remark.
    Other,
}

impl RemarkKind {
    /// Parse from the LLVM -pass-remarks-* flag.
    pub fn from_flag(flag: &str) -> Option<Self> {
        match flag {
            "missed" => Some(Self::Missed),
            "analysis" => Some(Self::Analysis),
            "passed" => Some(Self::Passed),
            "all" => Some(Self::Other),
            _ => None,
        }
    }

    /// Convert to the flag suffix.
    pub fn to_flag_suffix(&self) -> &'static str {
        match self {
            Self::Missed => "missed",
            Self::Analysis => "analysis",
            Self::Passed => "passed",
            Self::Other => "all",
        }
    }
}

/// A single optimization remark.
#[derive(Debug, Clone)]
pub struct OptimizationRemark {
    /// The kind of remark.
    pub kind: RemarkKind,
    /// The pass that generated the remark.
    pub pass_name: String,
    /// The function where the remark occurred.
    pub function: String,
    /// Source location (if available).
    pub location: Option<(String, u32, u32)>,
    /// The remark message.
    pub message: String,
    /// Extra arguments (key-value pairs).
    pub args: BTreeMap<String, String>,
}

impl OptimizationRemark {
    /// Create a new remark.
    pub fn new(kind: RemarkKind, pass_name: &str, function: &str, message: &str) -> Self {
        Self {
            kind,
            pass_name: pass_name.to_string(),
            function: function.to_string(),
            location: None,
            message: message.to_string(),
            args: BTreeMap::new(),
        }
    }

    /// Set the source location.
    pub fn with_location(mut self, file: &str, line: u32, column: u32) -> Self {
        self.location = Some((file.to_string(), line, column));
        self
    }

    /// Add an argument.
    pub fn with_arg(mut self, key: &str, value: &str) -> Self {
        self.args.insert(key.to_string(), value.to_string());
        self
    }

    /// Format as YAML.
    pub fn to_yaml(&self) -> String {
        let mut yaml = String::new();
        yaml.push_str("--- !");
        yaml.push_str(match self.kind {
            RemarkKind::Missed => "Missed",
            RemarkKind::Analysis => "Analysis",
            RemarkKind::Passed => "Passed",
            RemarkKind::Other => "Other",
        });
        yaml.push('\n');
        yaml.push_str(&format!("Pass:            {}\n", self.pass_name));
        yaml.push_str(&format!("Name:            {}\n", self.message));
        yaml.push_str(&format!("Function:        {}\n", self.function));
        if let Some((ref file, line, col)) = self.location {
            yaml.push_str(&format!("DebugLoc:        {{ File: {}, Line: {}, Column: {} }}\n", file, line, col));
        }
        for (k, v) in &self.args {
            yaml.push_str(&format!("  {}: {}\n", k, v));
        }
        yaml
    }

    /// Format as a single-line summary.
    pub fn summary(&self) -> String {
        let kind_str = match self.kind {
            RemarkKind::Missed => "missed",
            RemarkKind::Analysis => "analysis",
            RemarkKind::Passed => "passed",
            RemarkKind::Other => "other",
        };
        if let Some((ref file, line, col)) = self.location {
            format!("{}:{}:{}: {}: {} in {}", file, line, col, kind_str, self.message, self.function)
        } else {
            format!("{}: {} in {}", kind_str, self.message, self.function)
        }
    }
}

/// Emitter for optimization remarks.
#[derive(Debug, Clone)]
pub struct OptimizationRemarkEmitter {
    /// Whether the emitter is enabled.
    pub enabled: bool,
    /// The output format.
    pub format: RemarkFormat,
    /// Collected remarks.
    pub remarks: Vec<OptimizationRemark>,
    /// Filter: only emit remarks for these pass names (empty = all).
    pub pass_filter: Vec<String>,
}

impl OptimizationRemarkEmitter {
    /// Create a new remark emitter.
    pub fn new() -> Self {
        Self {
            enabled: false,
            format: RemarkFormat::YAML,
            remarks: Vec::new(),
            pass_filter: Vec::new(),
        }
    }

    /// Enable the emitter.
    pub fn enable(&mut self) {
        self.enabled = true;
    }

    /// Set the output format.
    pub fn with_format(mut self, format: RemarkFormat) -> Self {
        self.format = format;
        self
    }

    /// Add a pass filter.
    pub fn filter_pass(mut self, pass: &str) -> Self {
        self.pass_filter.push(pass.to_string());
        self
    }

    /// Emit a remark (if enabled).
    pub fn emit(&mut self, remark: OptimizationRemark) {
        if !self.enabled {
            return;
        }
        if !self.pass_filter.is_empty()
            && !self.pass_filter.contains(&remark.pass_name)
        {
            return;
        }
        self.remarks.push(remark);
    }

    /// Emit a missed-optimization remark.
    pub fn missed(
        &mut self,
        pass_name: &str,
        function: &str,
        message: &str,
    ) {
        self.emit(OptimizationRemark::new(
            RemarkKind::Missed,
            pass_name,
            function,
            message,
        ));
    }

    /// Emit an analysis remark.
    pub fn analysis(
        &mut self,
        pass_name: &str,
        function: &str,
        message: &str,
    ) {
        self.emit(OptimizationRemark::new(
            RemarkKind::Analysis,
            pass_name,
            function,
            message,
        ));
    }

    /// Emit a passed-optimization remark.
    pub fn passed(
        &mut self,
        pass_name: &str,
        function: &str,
        message: &str,
    ) {
        self.emit(OptimizationRemark::new(
            RemarkKind::Passed,
            pass_name,
            function,
            message,
        ));
    }

    /// Get the number of remarks collected.
    pub fn remark_count(&self) -> usize {
        self.remarks.len()
    }

    /// Clear all collected remarks.
    pub fn clear(&mut self) {
        self.remarks.clear();
    }

    /// Format all remarks in the output format.
    pub fn format_all(&self) -> String {
        let mut output = String::new();
        for remark in &self.remarks {
            match self.format {
                RemarkFormat::YAML => {
                    output.push_str(&remark.to_yaml());
                    output.push('\n');
                }
                RemarkFormat::JSON => {
                    output.push_str(&format!(
                        r#"{{"kind":"{}","pass":"{}","fn":"{}","msg":"{}"}}"#,
                        match remark.kind {
                            RemarkKind::Missed => "missed",
                            RemarkKind::Analysis => "analysis",
                            RemarkKind::Passed => "passed",
                            RemarkKind::Other => "other",
                        },
                        remark.pass_name,
                        remark.function,
                        remark.message
                    ));
                    output.push('\n');
                }
                RemarkFormat::Bitstream => {
                    output.push_str(&format!(
                        "[bitstream] {}:{}",
                        remark.pass_name, remark.message
                    ));
                    output.push('\n');
                }
            }
        }
        output
    }
}

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

// ── PassBuilder ───────────────────────────────────────────────────────────

/// Builds complete optimization pipelines from flags.
#[derive(Debug, Clone)]
pub struct PassBuilder {
    /// The optimization configuration.
    pub config: OptimizationPipelineConfig,
    /// The remark emitter.
    pub remarks: OptimizationRemarkEmitter,
}

impl PassBuilder {
    /// Create a new pass builder.
    pub fn new(config: OptimizationPipelineConfig) -> Self {
        Self {
            config,
            remarks: OptimizationRemarkEmitter::new(),
        }
    }

    /// Create a pass builder from command-line arguments.
    pub fn from_args(args: &[String], opt_level: ClangOptLevel) -> Self {
        let config = OptimizationPipelineConfig::for_level(opt_level);
        let flags = OptimizationFlags::from_args(args);
        let mut config = config;
        flags.apply_to_config(&mut config);
        Self::new(config)
    }

    /// Build the full optimization pipeline.
    pub fn build_pipeline(&self) -> PassPipeline {
        if self.config.disable_optimizations {
            return build_optimization_pipeline(ClangOptLevel::O0);
        }
        let mut pipeline = build_optimization_pipeline(self.config.opt_level);

        // Apply customizations
        if !self.config.vectorize {
            // Remove vectorization passes
            pipeline.passes.retain(|p| {
                !matches!(p.name, PassName::LoopVectorize | PassName::SLPVectorize)
            });
        }
        if !self.config.slp_vectorize {
            pipeline.passes.retain(|p| p.name != PassName::SLPVectorize);
        }
        if !self.config.inline_functions {
            pipeline.passes.retain(|p| p.name != PassName::Inline);
        }

        // Add custom passes
        for pass_name in &self.config.custom_passes {
            if !self.config.excluded_passes.contains(pass_name) {
                pipeline.add_pass(PipelinePass::new(*pass_name));
            }
        }

        // Remove excluded passes
        pipeline
            .passes
            .retain(|p| !self.config.excluded_passes.contains(&p.name));

        pipeline
    }

    /// Build the LTO pipeline if needed.
    pub fn build_lto_pipeline(&self) -> Option<PassPipeline> {
        if self.config.lto {
            Some(build_lto_pipeline(self.config.thin_lto))
        } else {
            None
        }
    }

    /// Enable optimization remarks.
    pub fn enable_remarks(&mut self, format: RemarkFormat) {
        self.config.emit_remarks = true;
        self.config.remark_format = format;
        self.remarks = OptimizationRemarkEmitter::new().with_format(format);
        self.remarks.enable();
    }

    /// Get the inline threshold based on config.
    pub fn get_inline_threshold(&self) -> u32 {
        if self.config.inline_threshold > 0 {
            self.config.inline_threshold
        } else {
            self.config.opt_level.inline_threshold()
        }
    }

    /// Check if a specific pass is in the pipeline.
    pub fn has_pass(&self, pass: PassName) -> bool {
        let pipeline = self.build_pipeline();
        pipeline.passes.iter().any(|p| p.name == pass && p.enabled)
    }
}

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

// ── Optimization Summary ─────────────────────────────────────────────────

/// Summary of the optimization pipeline that will be applied.
#[derive(Debug, Clone)]
pub struct OptimizationSummary {
    /// The optimization level.
    pub opt_level: ClangOptLevel,
    /// Number of passes in the pipeline.
    pub pass_count: usize,
    /// Number of enabled passes.
    pub enabled_passes: usize,
    /// Whether fast-math is enabled.
    pub fast_math: bool,
    /// Whether vectorization is enabled.
    pub vectorization: bool,
    /// Whether LTO is enabled.
    pub lto: bool,
    /// Whether LTO is thin.
    pub thin_lto: bool,
    /// Whether frame pointer is omitted.
    pub omit_frame_pointer: bool,
    /// The inline threshold.
    pub inline_threshold: u32,
    /// List of enabled pass names.
    pub pass_names: Vec<String>,
}

impl OptimizationSummary {
    /// Create a summary from a pass builder.
    pub fn from_builder(builder: &PassBuilder) -> Self {
        let pipeline = builder.build_pipeline();
        Self {
            opt_level: builder.config.opt_level,
            pass_count: pipeline.passes.len(),
            enabled_passes: pipeline.enabled_pass_count(),
            fast_math: builder.config.fast_math,
            vectorization: builder.config.vectorize,
            lto: builder.config.lto,
            thin_lto: builder.config.thin_lto,
            omit_frame_pointer: builder.config.omit_frame_pointer,
            inline_threshold: builder.get_inline_threshold(),
            pass_names: pipeline.enabled_pass_names(),
        }
    }

    /// Format as a human-readable string.
    pub fn format(&self) -> String {
        let mut s = String::new();
        s.push_str(&format!("Optimization Level: {}\n", self.opt_level));
        s.push_str(&format!(
            "Passes: {} total, {} enabled\n",
            self.pass_count, self.enabled_passes
        ));
        s.push_str(&format!("Fast Math: {}\n", self.fast_math));
        s.push_str(&format!("Vectorization: {}\n", self.vectorization));
        s.push_str(&format!(
            "LTO: {} ({})\n",
            self.lto,
            if self.thin_lto { "thin" } else { "full" }
        ));
        s.push_str(&format!(
            "Omit Frame Pointer: {}\n",
            self.omit_frame_pointer
        ));
        s.push_str(&format!("Inline Threshold: {}\n", self.inline_threshold));
        if !self.pass_names.is_empty() {
            s.push_str("Enabled passes:\n");
            for name in &self.pass_names {
                s.push_str(&format!("  - {}\n", name));
            }
        }
        s
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── ClangOptLevel tests ────────────────────────────────────────────

    #[test]
    fn test_opt_level_from_str() {
        assert_eq!(ClangOptLevel::from_str("O0"), Some(ClangOptLevel::O0));
        assert_eq!(ClangOptLevel::from_str("O2"), Some(ClangOptLevel::O2));
        assert_eq!(ClangOptLevel::from_str("Os"), Some(ClangOptLevel::Os));
        assert_eq!(ClangOptLevel::from_str("Oz"), Some(ClangOptLevel::Oz));
        assert_eq!(ClangOptLevel::from_str("O5"), None);
    }

    #[test]
    fn test_opt_level_to_flag() {
        assert_eq!(ClangOptLevel::O0.to_flag(), "-O0");
        assert_eq!(ClangOptLevel::O3.to_flag(), "-O3");
        assert_eq!(ClangOptLevel::Os.to_flag(), "-Os");
    }

    #[test]
    fn test_opt_level_is_optimizing() {
        assert!(!ClangOptLevel::O0.is_optimizing());
        assert!(ClangOptLevel::O2.is_optimizing());
    }

    #[test]
    fn test_opt_level_is_size_optimized() {
        assert!(!ClangOptLevel::O2.is_size_optimized());
        assert!(ClangOptLevel::Os.is_size_optimized());
        assert!(ClangOptLevel::Oz.is_size_optimized());
    }

    #[test]
    fn test_opt_level_inline_threshold() {
        assert_eq!(ClangOptLevel::O0.inline_threshold(), 0);
        assert_eq!(ClangOptLevel::O1.inline_threshold(), 75);
        assert_eq!(ClangOptLevel::O2.inline_threshold(), 225);
        assert_eq!(ClangOptLevel::O3.inline_threshold(), 275);
        assert_eq!(ClangOptLevel::Os.inline_threshold(), 75);
        assert_eq!(ClangOptLevel::Oz.inline_threshold(), 25);
    }

    // ── Pipeline construction tests ────────────────────────────────────

    #[test]
    fn test_build_o0_pipeline() {
        let pipeline = build_optimization_pipeline(ClangOptLevel::O0);
        assert_eq!(pipeline.opt_level, ClangOptLevel::O0);
        assert!(!pipeline.passes.is_empty());
    }

    #[test]
    fn test_build_o1_pipeline() {
        let pipeline = build_optimization_pipeline(ClangOptLevel::O1);
        assert!(pipeline.enabled_pass_count() > 0);
    }

    #[test]
    fn test_build_o2_pipeline() {
        let pipeline = build_optimization_pipeline(ClangOptLevel::O2);
        let names = pipeline.enabled_pass_names();
        assert!(names.contains(&"gvn".to_string()));
        assert!(names.contains(&"loop-rotate".to_string()));
    }

    #[test]
    fn test_build_o3_pipeline() {
        let pipeline = build_optimization_pipeline(ClangOptLevel::O3);
        let names = pipeline.enabled_pass_names();
        assert!(names.contains(&"loop-vectorize".to_string()));
        assert!(names.contains(&"argpromotion".to_string()));
    }

    #[test]
    fn test_build_os_pipeline() {
        let pipeline = build_optimization_pipeline(ClangOptLevel::Os);
        let names = pipeline.enabled_pass_names();
        // Os should NOT have loop-unroll
        assert!(!names.contains(&"loop-unroll".to_string()));
        // Os should NOT have loop-vectorize
        assert!(!names.contains(&"loop-vectorize".to_string()));
    }

    #[test]
    fn test_build_oz_pipeline() {
        let pipeline = build_optimization_pipeline(ClangOptLevel::Oz);
        let names = pipeline.enabled_pass_names();
        // Oz should NOT have slp-vectorizer
        assert!(!names.contains(&"slp-vectorizer".to_string()));
    }

    #[test]
    fn test_build_lto_pipeline() {
        let pipeline = build_lto_pipeline(false);
        assert!(!pipeline.passes.is_empty());
        let names = pipeline.enabled_pass_names();
        assert!(names.contains(&"internalize".to_string()));
    }

    #[test]
    fn test_build_thin_lto_pipeline() {
        let pipeline = build_lto_pipeline(true);
        assert!(pipeline.description.contains("ThinLTO"));
    }

    // ── Pipeline config tests ──────────────────────────────────────────

    #[test]
    fn test_pipeline_config_default() {
        let config = OptimizationPipelineConfig::default();
        assert_eq!(config.opt_level, ClangOptLevel::O2);
        assert!(config.vectorize);
    }

    #[test]
    fn test_pipeline_config_for_level_o0() {
        let config = OptimizationPipelineConfig::for_level(ClangOptLevel::O0);
        assert!(!config.vectorize);
        assert!(!config.inline_functions);
    }

    #[test]
    fn test_pipeline_config_builder() {
        let config = OptimizationPipelineConfig::for_level(ClangOptLevel::O3)
            .with_fast_math()
            .with_lto(true)
            .with_remarks(RemarkFormat::YAML)
            .add_pass(PassName::LoopUnswitch);
        assert!(config.fast_math);
        assert!(config.lto);
        assert!(config.thin_lto);
        assert!(config.emit_remarks);
        assert_eq!(config.custom_passes.len(), 1);
    }

    // ── Pipeline pass tests ────────────────────────────────────────────

    #[test]
    fn test_pipeline_pass_new() {
        let pass = PipelinePass::new(PassName::PromoteMemoryToRegister);
        assert!(pass.enabled);
        assert_eq!(pass.name.name(), "mem2reg");
    }

    #[test]
    fn test_pipeline_pass_disabled() {
        let pass = PipelinePass::disabled(PassName::LoopUnroll);
        assert!(!pass.enabled);
    }

    #[test]
    fn test_pipeline_pass_with_param() {
        let pass = PipelinePass::new(PassName::LoopUnroll).with_param("threshold", "150");
        assert_eq!(pass.params.get("threshold").unwrap(), "150");
    }

    // ── PassBuilder tests ──────────────────────────────────────────────

    #[test]
    fn test_pass_builder_new() {
        let config = OptimizationPipelineConfig::for_level(ClangOptLevel::O2);
        let builder = PassBuilder::new(config);
        assert!(builder.has_pass(PassName::PromoteMemoryToRegister));
    }

    #[test]
    fn test_pass_builder_build_pipeline() {
        let config = OptimizationPipelineConfig::for_level(ClangOptLevel::O2);
        let builder = PassBuilder::new(config);
        let pipeline = builder.build_pipeline();
        assert!(!pipeline.passes.is_empty());
    }

    #[test]
    fn test_pass_builder_without_vectorize() {
        let config = OptimizationPipelineConfig::for_level(ClangOptLevel::O2)
            .with_vectorize(false);
        let builder = PassBuilder::new(config);
        assert!(!builder.has_pass(PassName::LoopVectorize));
    }

    #[test]
    fn test_pass_builder_get_inline_threshold() {
        let config = OptimizationPipelineConfig::for_level(ClangOptLevel::O3);
        let builder = PassBuilder::new(config);
        assert_eq!(builder.get_inline_threshold(), 275);
    }

    #[test]
    fn test_pass_builder_custom_threshold() {
        let mut config = OptimizationPipelineConfig::for_level(ClangOptLevel::O2);
        config.inline_threshold = 500;
        let builder = PassBuilder::new(config);
        assert_eq!(builder.get_inline_threshold(), 500);
    }

    // ── OptimizationFlags tests ────────────────────────────────────────

    #[test]
    fn test_optimization_flags_default() {
        let flags = OptimizationFlags::default();
        assert!(!flags.fast_math);
        assert!(flags.vectorize);
    }

    #[test]
    fn test_optimization_flags_from_args() {
        let args = vec![
            "-ffast-math".to_string(),
            "-fno-vectorize".to_string(),
            "-flto".to_string(),
            "-fno-omit-frame-pointer".to_string(),
        ];
        let flags = OptimizationFlags::from_args(&args);
        assert!(flags.fast_math);
        assert!(flags.no_vectorize);
        assert!(flags.lto);
        assert!(flags.no_omit_frame_pointer);
    }

    #[test]
    fn test_optimization_flags_sanitizers() {
        let args = vec![
            "-fsanitize=address".to_string(),
            "-fsanitize=undefined".to_string(),
        ];
        let flags = OptimizationFlags::from_args(&args);
        assert!(flags.sanitize_address);
        assert!(flags.sanitize_undefined);
        assert!(!flags.sanitize_memory);
    }

    #[test]
    fn test_optimization_flags_apply_to_config() {
        let flags = OptimizationFlags {
            fast_math: true,
            no_vectorize: true,
            ..Default::default()
        };
        let mut config = OptimizationPipelineConfig::for_level(ClangOptLevel::O2);
        flags.apply_to_config(&mut config);
        assert!(config.fast_math);
        assert!(!config.vectorize);
    }

    // ── OptimizationRemark tests ───────────────────────────────────────

    #[test]
    fn test_remark_new() {
        let remark = OptimizationRemark::new(
            RemarkKind::Missed,
            "inline",
            "foo",
            "foo not inlined into bar",
        );
        assert_eq!(remark.pass_name, "inline");
        assert_eq!(remark.function, "foo");
    }

    #[test]
    fn test_remark_to_yaml() {
        let remark = OptimizationRemark::new(
            RemarkKind::Passed,
            "gvn",
            "main",
            "Redundant load eliminated",
        )
        .with_location("test.c", 10, 5)
        .with_arg("load", "%ptr");
        let yaml = remark.to_yaml();
        assert!(yaml.contains("Passed"));
        assert!(yaml.contains("gvn"));
        assert!(yaml.contains("test.c"));
    }

    #[test]
    fn test_remark_summary() {
        let remark = OptimizationRemark::new(
            RemarkKind::Missed,
            "inline",
            "foo",
            "not inlined",
        )
        .with_location("a.c", 5, 1);
        let summary = remark.summary();
        assert!(summary.contains("a.c:5:1"));
        assert!(summary.contains("missed"));
    }

    #[test]
    fn test_remark_kind_from_flag() {
        assert_eq!(RemarkKind::from_flag("missed"), Some(RemarkKind::Missed));
        assert_eq!(RemarkKind::from_flag("passed"), Some(RemarkKind::Passed));
        assert_eq!(RemarkKind::from_flag("unknown"), None);
    }

    // ── OptimizationRemarkEmitter tests ────────────────────────────────

    #[test]
    fn test_remark_emitter_disabled() {
        let mut emitter = OptimizationRemarkEmitter::new();
        emitter.missed("inline", "f", "msg");
        assert_eq!(emitter.remark_count(), 0);
    }

    #[test]
    fn test_remark_emitter_enabled() {
        let mut emitter = OptimizationRemarkEmitter::new();
        emitter.enable();
        emitter.missed("inline", "f", "msg");
        emitter.passed("gvn", "f", "msg2");
        assert_eq!(emitter.remark_count(), 2);
    }

    #[test]
    fn test_remark_emitter_filter() {
        let mut emitter = OptimizationRemarkEmitter::new()
            .filter_pass("gvn");
        emitter.enable();
        emitter.missed("inline", "f", "msg");
        emitter.passed("gvn", "f", "msg2");
        assert_eq!(emitter.remark_count(), 1);
    }

    #[test]
    fn test_remark_emitter_format_all() {
        let mut emitter = OptimizationRemarkEmitter::new().with_format(RemarkFormat::YAML);
        emitter.enable();
        emitter.passed("mem2reg", "main", "Promoted alloca");
        let output = emitter.format_all();
        assert!(output.contains("Passed"));
        assert!(output.contains("mem2reg"));
    }

    #[test]
    fn test_remark_emitter_clear() {
        let mut emitter = OptimizationRemarkEmitter::new();
        emitter.enable();
        emitter.missed("gvn", "f", "msg");
        emitter.clear();
        assert_eq!(emitter.remark_count(), 0);
    }

    // ── OptimizationSummary tests ─────────────────────────────────────

    #[test]
    fn test_optimization_summary_from_builder() {
        let config = OptimizationPipelineConfig::for_level(ClangOptLevel::O3);
        let builder = PassBuilder::new(config);
        let summary = OptimizationSummary::from_builder(&builder);
        assert_eq!(summary.opt_level, ClangOptLevel::O3);
        assert!(summary.pass_count > 0);
        assert!(summary.vectorization);
    }

    #[test]
    fn test_optimization_summary_format() {
        let config = OptimizationPipelineConfig::for_level(ClangOptLevel::O2);
        let builder = PassBuilder::new(config);
        let summary = OptimizationSummary::from_builder(&builder);
        let formatted = summary.format();
        assert!(formatted.contains("O2"));
        assert!(formatted.contains("Vectorization"));
    }

    // ── PassName tests ─────────────────────────────────────────────────

    #[test]
    fn test_pass_name_name() {
        assert_eq!(PassName::PromoteMemoryToRegister.name(), "mem2reg");
        assert_eq!(PassName::LoopVectorize.name(), "loop-vectorize");
        assert_eq!(PassName::AggressiveInstCombine.name(), "aggressive-instcombine");
    }

    #[test]
    fn test_all_pass_names() {
        // Verify all pass names are valid
        let passes = [
            PassName::PromoteMemoryToRegister,
            PassName::InstructionCombining,
            PassName::SimplifyCFG,
            PassName::DeadCodeElimination,
            PassName::GlobalValueNumbering,
            PassName::EarlyCSE,
            PassName::LoopInvariantCodeMotion,
            PassName::LoopRotate,
            PassName::LoopUnroll,
            PassName::SLPVectorize,
            PassName::LoopVectorize,
            PassName::AggressiveInstCombine,
            PassName::ArgumentPromotion,
            PassName::GlobalOptimizer,
            PassName::GlobalDCE,
            PassName::Reassociate,
            PassName::SCCP,
            PassName::JumpThreading,
            PassName::TailCallElimination,
            PassName::FunctionAttrs,
            PassName::MergeFunctions,
        ];
        for pass in &passes {
            assert!(!pass.name().is_empty());
        }
    }

    #[test]
    fn test_pipeline_pass_count() {
        let pipeline = build_optimization_pipeline(ClangOptLevel::O2);
        assert!(pipeline.passes.len() >= 15); // O2 should have many passes
    }

    #[test]
    fn test_o0_has_disabled_passes() {
        let pipeline = build_optimization_pipeline(ClangOptLevel::O0);
        let disabled: Vec<_> = pipeline.passes.iter().filter(|p| !p.enabled).collect();
        assert!(!disabled.is_empty());
    }
}