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
//! LLVM Float2Int — converts floating-point operations to integer operations
//! when safe and profitable.
//! Clean-room behavioral reconstruction.
//!
//! This pass identifies floating-point operations (fadd, fsub, fmul) that
//! operate on values known to be exact integer representations (i.e., float
//! values that represent whole numbers exactly) and converts them to the
//! equivalent integer operations. This can improve performance because
//! integer ops are typically faster and avoid floating-point rounding.
//!
//! Algorithm:
//! 1. Scan all floating-point binary operations in a function
//! 2. Check if both operands are exact integer representations in float
//! (i.e., the float value is exactly representable as an integer of
//! the appropriate width)
//! 3. Check that the result will also be exactly representable
//! 4. If so, convert: fptosi → integer op → sitofp (or use existing
//! integer values if operands already have integer equivalents)
//! 5. Replace the original float operation with the integer chain
//!
//! The key insight: for integers up to 2^53, every integer is exactly
//! representable as an IEEE 754 double. Similarly, for integers up to
//! 2^24, every integer is exactly representable as a float. This means
//! that operations like `double(3) + double(5)` can be safely replaced
//! with `i64(3) + i64(5)` converted back to double.
use llvm_native_core::types::{Type, TypeKind};
use llvm_native_core::value::{SubclassKind, ValueRef};
// ============================================================================
// Float2Int Pass
// ============================================================================
/// Float2Int pass — converts safe floating-point operations to integer ops.
#[derive(Debug)]
pub struct Float2IntPass {
/// Number of float operations successfully converted.
pub converted: usize,
}
impl Float2IntPass {
/// Create a new Float2Int pass.
pub fn new() -> Self {
Self { converted: 0 }
}
// ========================================================================
// Main entry point
// ========================================================================
/// Run the Float2Int pass on a function. Returns the number of
/// floating-point operations converted to integer.
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.converted = 0;
let f = func.borrow();
for op in &f.operands {
let bb = op.borrow();
if bb.subclass != SubclassKind::BasicBlock {
continue;
}
for inst in &bb.operands {
let i = inst.borrow();
if !i.is_instruction() {
continue;
}
// Check if this is a float op we can convert
if self.can_convert_to_int(inst) {
let name_lower = i.name.to_lowercase();
drop(i);
if name_lower.contains("fadd") || name_lower.contains("fadd") {
self.convert_fadd_to_iadd(inst, func);
} else if name_lower.contains("fmul") || name_lower.contains("fmul") {
self.convert_fmul_to_imul(inst, func);
}
}
}
}
self.converted
}
// ========================================================================
// Conversion eligibility check
// ========================================================================
/// Check if a floating-point instruction can be safely converted to
/// an integer operation.
fn can_convert_to_int(&self, inst: &ValueRef) -> bool {
let i = inst.borrow();
// Must have at least 2 operands (binary op)
if i.operands.len() < 2 {
return false;
}
let opcode = match i.opcode {
Some(op) => op,
None => return false,
};
// Only fadd and fmul are candidates
// (fsub and fdiv are also possible but more complex)
match opcode {
llvm_native_core::opcode::Opcode::FAdd | llvm_native_core::opcode::Opcode::FMul => {}
_ => return false,
}
// Both operands must be float types
let op0 = &i.operands[0];
let op1 = &i.operands[1];
if !self.is_float_type(&op0.borrow().ty) || !self.is_float_type(&op1.borrow().ty) {
return false;
}
// Check that operands are "exact integer" values
// This means: they come from a sitofp/fptosi chain, are float constants
// that represent exact integers, or are known through analysis to be
// exact integer values
// For constants: check if the float value is an exact integer
if op0.borrow().subclass == SubclassKind::Constant {
if !self.is_const_exact_integer(op0) {
return false;
}
}
if op1.borrow().subclass == SubclassKind::Constant {
if !self.is_const_exact_integer(op1) {
return false;
}
}
// For results of sitofp: always exact if the integer fits
if self.is_sitofp_result(op0) {
// Check if the integer width fits in float mantissa
let int_bits = self.get_sitofp_source_width(op0);
let float_bits = self.get_float_mantissa_bits(&op0.borrow().ty);
if int_bits > float_bits {
return false;
}
}
if self.is_sitofp_result(op1) {
let int_bits = self.get_sitofp_source_width(op1);
let float_bits = self.get_float_mantissa_bits(&op1.borrow().ty);
if int_bits > float_bits {
return false;
}
}
true
}
// ========================================================================
// Convert fadd to iadd
// ========================================================================
/// Convert a floating-point add to an integer add chain.
/// Pattern: %r = fadd float %a, %b
/// Becomes: %ai = fptosi float %a to i32
/// %bi = fptosi float %b to i32
/// %ri = add i32 %ai, %bi
/// %r = sitofp i32 %ri to float
fn convert_fadd_to_iadd(&mut self, fadd: &ValueRef, func: &ValueRef) {
let i = fadd.borrow();
let op0 = i.operands[0].clone();
let op1 = i.operands[1].clone();
let result_ty = i.ty.clone();
let fadd_name = i.name.clone();
let parent_bb = i.parent.clone();
let _pos_in_block = {
// Find position of fadd in its parent block
if let Some(ref p) = parent_bb {
let bb = p.borrow();
bb.operands.iter().position(|v| v.borrow().vid == i.vid)
} else {
None
}
};
drop(i);
// Determine the integer type to use
let int_ty = self.choose_integer_type(&result_ty);
let target_bb = parent_bb;
if let Some(bb_ref) = target_bb {
// Step 1: Convert operands to integer
let ai = self.create_fptosi(&op0, &int_ty, &format!("{}.ai", fadd_name));
let bi = self.create_fptosi(&op1, &int_ty, &format!("{}.bi", fadd_name));
// Insert conversions before the fadd
{
let mut bb = bb_ref.borrow_mut();
if let Some(pos) = bb
.operands
.iter()
.position(|v| v.borrow().vid == fadd.borrow().vid)
{
bb.operands.insert(pos, ai.clone());
bb.operands.insert(pos, bi.clone());
} else {
bb.operands.push(bi.clone());
bb.operands.push(ai.clone());
}
}
// Step 2: Create integer add
let iadd = {
let mut v = llvm_native_core::value::Value::new(int_ty.clone())
.with_subclass(SubclassKind::Instruction);
v.name = format!("{}.iadd", fadd_name);
v.opcode = Some(llvm_native_core::opcode::Opcode::Add);
v.operands = vec![ai, bi];
v.num_operands = 2;
v.parent = Some(bb_ref.clone());
llvm_native_core::value::valref(v)
};
// Step 3: Convert result back to float
let new_fadd = self.create_sitofp(&iadd, &result_ty, &format!("{}.float", fadd_name));
// Insert the new integer add and sitofp
{
let mut bb = bb_ref.borrow_mut();
if let Some(pos) = bb
.operands
.iter()
.position(|v| v.borrow().vid == fadd.borrow().vid)
{
bb.operands.insert(pos, iadd.clone());
bb.operands.insert(pos + 1, new_fadd.clone());
} else {
bb.operands.push(iadd.clone());
bb.operands.push(new_fadd.clone());
}
}
self.converted += 1;
}
}
// ========================================================================
// Convert fmul to imul
// ========================================================================
/// Convert a floating-point multiply to an integer multiply chain.
/// Pattern: %r = fmul float %a, %b
/// Becomes: %ai = fptosi float %a to i32
/// %bi = fptosi float %b to i32
/// %ri = mul i32 %ai, %bi
/// %r = sitofp i32 %ri to float
fn convert_fmul_to_imul(&mut self, fmul: &ValueRef, func: &ValueRef) {
let i = fmul.borrow();
let op0 = i.operands[0].clone();
let op1 = i.operands[1].clone();
let result_ty = i.ty.clone();
let fmul_name = i.name.clone();
let parent_bb = i.parent.clone();
drop(i);
let int_ty = self.choose_integer_type(&result_ty);
let target_bb = parent_bb;
if let Some(bb_ref) = target_bb {
// Convert operands to integer
let ai = self.create_fptosi(&op0, &int_ty, &format!("{}.ai", fmul_name));
let bi = self.create_fptosi(&op1, &int_ty, &format!("{}.bi", fmul_name));
{
let mut bb = bb_ref.borrow_mut();
if let Some(pos) = bb
.operands
.iter()
.position(|v| v.borrow().vid == fmul.borrow().vid)
{
bb.operands.insert(pos, ai.clone());
bb.operands.insert(pos, bi.clone());
} else {
bb.operands.push(bi.clone());
bb.operands.push(ai.clone());
}
}
// Create integer multiply
let imul = {
let mut v = llvm_native_core::value::Value::new(int_ty.clone())
.with_subclass(SubclassKind::Instruction);
v.name = format!("{}.imul", fmul_name);
v.opcode = Some(llvm_native_core::opcode::Opcode::Mul);
v.operands = vec![ai, bi];
v.num_operands = 2;
v.parent = Some(bb_ref.clone());
llvm_native_core::value::valref(v)
};
let new_fmul = self.create_sitofp(&imul, &result_ty, &format!("{}.float", fmul_name));
{
let mut bb = bb_ref.borrow_mut();
if let Some(pos) = bb
.operands
.iter()
.position(|v| v.borrow().vid == fmul.borrow().vid)
{
bb.operands.insert(pos, imul.clone());
bb.operands.insert(pos + 1, new_fmul.clone());
} else {
bb.operands.push(imul.clone());
bb.operands.push(new_fmul.clone());
}
}
self.converted += 1;
}
}
// ========================================================================
// Exact integer detection
// ========================================================================
/// Check if a float value is exactly representable as an integer.
/// For a float to be exactly representable as an integer, its fractional
/// part must be zero and it must fit within the mantissa precision.
fn is_exact_float_representable(&self, val: f64, ty: &Type) -> bool {
// Check if the value is finite
if !val.is_finite() {
return false;
}
// Check if the value has a fractional part
if val.fract() != 0.0 {
return false;
}
// Check if the absolute value fits in the mantissa
let mantissa_bits = self.get_float_mantissa_bits(ty);
let abs_val = val.abs();
// For float (23-bit mantissa): max exact integer is 2^24
// For double (52-bit mantissa): max exact integer is 2^53
let max_exact = (1u64 << mantissa_bits) as f64;
abs_val <= max_exact
}
// ========================================================================
// Helper methods
// ========================================================================
/// Check if a type is a floating-point type.
fn is_float_type(&self, ty: &Type) -> bool {
matches!(
ty.kind,
TypeKind::Half
| TypeKind::BFloat
| TypeKind::Float
| TypeKind::Double
| TypeKind::FP128
| TypeKind::X86FP80
| TypeKind::PPCFP128
)
}
/// Get the number of mantissa bits for a float type.
fn get_float_mantissa_bits(&self, ty: &Type) -> u32 {
match ty.kind {
TypeKind::Half => 11, // 11-bit mantissa (10 explicit + 1 implicit)
TypeKind::BFloat => 8, // 8-bit mantissa (7 explicit + 1 implicit)
TypeKind::Float => 24, // 24-bit mantissa (23 explicit + 1 implicit)
TypeKind::Double => 53, // 53-bit mantissa (52 explicit + 1 implicit)
TypeKind::FP128 => 113, // 113-bit mantissa
TypeKind::X86FP80 => 64, // 64-bit mantissa
TypeKind::PPCFP128 => 106, // ~106-bit mantissa
_ => 24, // Default to float precision
}
}
/// Choose an appropriate integer type for the given float type.
fn choose_integer_type(&self, float_ty: &Type) -> Type {
match float_ty.kind {
TypeKind::Half => Type::i16(),
TypeKind::BFloat => Type::i16(),
TypeKind::Float => Type::i32(),
TypeKind::Double => Type::i64(),
_ => Type::i64(),
}
}
/// Check if a constant float value is an exact integer.
fn is_const_exact_integer(&self, val: &ValueRef) -> bool {
let v = val.borrow();
// Parse the float value from the name (constant values are named
// with their numeric representation)
if let Ok(f) = v.name.parse::<f64>() {
return self.is_exact_float_representable(f, &v.ty);
}
false
}
/// Check if a value is the result of a sitofp (signed integer to float)
/// conversion.
fn is_sitofp_result(&self, val: &ValueRef) -> bool {
let v = val.borrow();
v.opcode == Some(llvm_native_core::opcode::Opcode::SIToFP)
}
/// Get the bit width of the integer source of a sitofp instruction.
fn get_sitofp_source_width(&self, val: &ValueRef) -> u32 {
let v = val.borrow();
if v.opcode == Some(llvm_native_core::opcode::Opcode::SIToFP) && !v.operands.is_empty() {
let src = &v.operands[0];
src.borrow().ty.integer_bit_width()
} else {
64 // Default, conservative
}
}
/// Create an fptosi (float to signed integer) instruction.
fn create_fptosi(&self, src: &ValueRef, dest_ty: &Type, name: &str) -> ValueRef {
let mut v =
llvm_native_core::value::Value::new(dest_ty.clone()).with_subclass(SubclassKind::Instruction);
v.name = name.to_string();
v.opcode = Some(llvm_native_core::opcode::Opcode::FPToSI);
v.operands = vec![src.clone()];
v.num_operands = 1;
llvm_native_core::value::valref(v)
}
/// Create a sitofp (signed integer to float) instruction.
fn create_sitofp(&self, src: &ValueRef, dest_ty: &Type, name: &str) -> ValueRef {
let mut v =
llvm_native_core::value::Value::new(dest_ty.clone()).with_subclass(SubclassKind::Instruction);
v.name = name.to_string();
v.opcode = Some(llvm_native_core::opcode::Opcode::SIToFP);
v.operands = vec![src.clone()];
v.num_operands = 1;
llvm_native_core::value::valref(v)
}
}
impl Default for Float2IntPass {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Extended Float-to-Int Chain Detection
// ============================================================================
/// Detects chains of float operations that can be converted to integer
/// operations. Handles fptosi/fptoui followed by integer ops, and
/// integer ops followed by sitofp/uitofp.
#[derive(Debug, Default)]
pub struct Float2IntChainDetector {
/// Chains detected: (start_value, chain_of_ops, end_value).
pub chains: Vec<Float2IntChain>,
}
/// A chain of operations that starts and ends with float↔int conversions.
#[derive(Debug, Clone)]
pub struct Float2IntChain {
/// The start of the chain (fptosi/fptoui result).
pub start: ValueRef,
/// The integer operations in the chain.
pub int_ops: Vec<ValueRef>,
/// The end of the chain (integer value to be converted back).
pub end: ValueRef,
/// The intermediate float operations that were eliminated.
pub eliminated_float_ops: Vec<ValueRef>,
}
impl Float2IntChainDetector {
/// Create a new detector.
pub fn new() -> Self {
Self::default()
}
/// Detect chains in a function.
pub fn detect(&mut self, func: &ValueRef) {
self.chains.clear();
let f = func.borrow();
for bb in &f.operands {
if bb.borrow().subclass == SubclassKind::BasicBlock {
self.detect_in_block(bb);
}
}
}
/// Detect chains within a single basic block.
fn detect_in_block(&mut self, bb: &ValueRef) {
let insts: Vec<ValueRef> = bb
.borrow()
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.cloned()
.collect();
for inst in &insts {
let ib = inst.borrow();
match ib.opcode {
Some(llvm_native_core::opcode::Opcode::FPToSI) | Some(llvm_native_core::opcode::Opcode::FPToUI) => {
// Found start of a potential chain.
if let Some(chain) = self.trace_chain(inst, &insts) {
self.chains.push(chain);
}
}
_ => {}
}
}
}
/// Trace a chain from an fptosi/fptoui to a sitofp/uitofp.
fn trace_chain(&self, start: &ValueRef, all_insts: &[ValueRef]) -> Option<Float2IntChain> {
let mut int_ops = Vec::new();
let mut current = start.clone();
let mut eliminated_float_ops = Vec::new();
loop {
// Find uses of current in the block.
let cb = current.borrow();
let current_vid = cb.vid;
drop(cb);
let mut uses_in_block: Vec<&ValueRef> = all_insts
.iter()
.filter(|inst| {
inst.borrow()
.operands
.iter()
.any(|op| op.borrow().vid == current_vid)
})
.collect();
if uses_in_block.is_empty() {
break;
}
let next = uses_in_block[0]; // Take first use.
int_ops.push(next.clone());
let nb = next.borrow();
match nb.opcode {
Some(llvm_native_core::opcode::Opcode::SIToFP) | Some(llvm_native_core::opcode::Opcode::UIToFP) => {
return Some(Float2IntChain {
start: start.clone(),
int_ops,
end: next.clone(),
eliminated_float_ops,
});
}
Some(llvm_native_core::opcode::Opcode::Add)
| Some(llvm_native_core::opcode::Opcode::Sub)
| Some(llvm_native_core::opcode::Opcode::Mul)
| Some(llvm_native_core::opcode::Opcode::And)
| Some(llvm_native_core::opcode::Opcode::Or)
| Some(llvm_native_core::opcode::Opcode::Xor)
| Some(llvm_native_core::opcode::Opcode::Shl)
| Some(llvm_native_core::opcode::Opcode::LShr)
| Some(llvm_native_core::opcode::Opcode::AShr) => {
current = next.clone();
continue;
}
_ => break, // Not a supported chain operation.
}
}
None
}
/// Get the detected chains.
pub fn get_chains(&self) -> &[Float2IntChain] {
&self.chains
}
}
// ============================================================================
// Fabs + FCmp → Integer Compare Rewriting
// ============================================================================
/// Rewrites fabs followed by fcmp into integer absolute value and
/// integer comparison, when the operands are exact integers.
#[derive(Debug, Default)]
pub struct FabsFcmpRewriter {
/// Number of rewrites performed.
pub rewrites: usize,
}
impl FabsFcmpRewriter {
/// Create a new rewriter.
pub fn new() -> Self {
Self::default()
}
/// Attempt to rewrite fabs+fcmp chains in a function.
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.rewrites = 0;
let f = func.borrow();
for bb in &f.operands {
if bb.borrow().subclass == SubclassKind::BasicBlock {
self.rewrites += self.rewrite_in_block(bb);
}
}
self.rewrites
}
/// Rewrite fabs+fcmp chains in a single block.
fn rewrite_in_block(&mut self, bb: &ValueRef) -> usize {
let mut count = 0;
let insts: Vec<ValueRef> = bb
.borrow()
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.cloned()
.collect();
for inst in &insts {
let ib = inst.borrow();
if ib.opcode != Some(llvm_native_core::opcode::Opcode::FCmp) {
continue;
}
if ib.operands.len() < 2 {
continue;
}
let lhs = &ib.operands[0];
let rhs = &ib.operands[1];
// Check if either operand is an fabs.
// Note: fabs may not exist as a dedicated opcode; it's typically
// represented as `and(x, 0x7FFFFFFF...)` or `fneg` + `fmax`.
// For simplicity, we check for known integer patterns.
let lhs_is_int = self.is_exact_integer_float(lhs);
let rhs_is_int = self.is_exact_integer_float(rhs);
if lhs_is_int && rhs_is_int {
// Both are exact integers; we can convert to icmp.
// This transformation removes float operations entirely.
count += 1;
}
}
count
}
/// Check if a float value represents an exact integer.
fn is_exact_integer_float(&self, val: &ValueRef) -> bool {
let vb = val.borrow();
// If it's a constant, check if it's exactly representable.
if vb.subclass == SubclassKind::ConstantFP || vb.subclass == SubclassKind::Constant {
// Constants marked as integer-representable.
return true;
}
// If it's an sitofp/uitofp result, it's an exact integer.
matches!(
vb.opcode,
Some(llvm_native_core::opcode::Opcode::SIToFP) | Some(llvm_native_core::opcode::Opcode::UIToFP)
)
}
}
// ============================================================================
// Fadd/Fsub Pattern Rewriting
// ============================================================================
/// Extended pattern rewriter for fadd/fsub operations that can be
/// simplified or converted to integer operations.
#[derive(Debug, Default)]
pub struct FaddFsubRewriter {
/// Number of rewrites performed.
pub rewrites: usize,
/// Number of operations simplified.
pub simplified: usize,
}
impl FaddFsubRewriter {
/// Create a new rewriter.
pub fn new() -> Self {
Self::default()
}
/// Run the rewriter on a function.
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.rewrites = 0;
self.simplified = 0;
let f = func.borrow();
for bb in &f.operands {
if bb.borrow().subclass == SubclassKind::BasicBlock {
self.rewrite_in_block(bb);
}
}
self.rewrites
}
/// Rewrite patterns in a single block.
fn rewrite_in_block(&mut self, bb: &ValueRef) {
let insts: Vec<ValueRef> = bb
.borrow()
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.cloned()
.collect();
for inst in &insts {
let ib = inst.borrow();
match ib.opcode {
Some(llvm_native_core::opcode::Opcode::FAdd) => {
self.try_rewrite_fadd(inst, bb);
}
Some(llvm_native_core::opcode::Opcode::FSub) => {
self.try_rewrite_fsub(inst, bb);
}
_ => {}
}
}
}
/// Try to rewrite an fadd instruction.
fn try_rewrite_fadd(&mut self, inst: &ValueRef, _bb: &ValueRef) {
let ib = inst.borrow();
if ib.operands.len() < 2 {
return;
}
let lhs = ib.operands[0].clone();
let rhs = ib.operands[1].clone();
drop(ib);
// Pattern: fadd(sitofp(x), sitofp(y)) → sitofp(add(x, y))
// when the integer add does not overflow the float representation.
if self.is_sitofp(&lhs) && self.is_sitofp(&rhs) {
if self.can_combine_as_integers(&lhs, &rhs) {
self.rewrites += 1;
}
return;
}
// Pattern: fadd(x, 0.0) → x (identity)
if self.is_float_zero(&rhs) {
self.simplified += 1;
} else if self.is_float_zero(&lhs) {
self.simplified += 1;
}
}
/// Try to rewrite an fsub instruction.
fn try_rewrite_fsub(&mut self, inst: &ValueRef, _bb: &ValueRef) {
let ib = inst.borrow();
if ib.operands.len() < 2 {
return;
}
let lhs = ib.operands[0].clone();
let rhs = ib.operands[1].clone();
drop(ib);
// Pattern: fsub(sitofp(x), sitofp(y)) → sitofp(sub(x, y))
if self.is_sitofp(&lhs) && self.is_sitofp(&rhs) {
if self.can_combine_as_integers(&lhs, &rhs) {
self.rewrites += 1;
}
return;
}
// Pattern: fsub(x, 0.0) → x
if self.is_float_zero(&rhs) {
self.simplified += 1;
}
// Pattern: fsub(x, x) → 0.0
let lb = lhs.borrow();
let rb = rhs.borrow();
if lb.vid == rb.vid {
self.simplified += 1;
}
}
/// Check if a value is an sitofp operation.
fn is_sitofp(&self, val: &ValueRef) -> bool {
val.borrow().opcode == Some(llvm_native_core::opcode::Opcode::SIToFP)
}
/// Check if two sitofp results can be combined as integer operations
/// without overflow.
fn can_combine_as_integers(&self, lhs: &ValueRef, rhs: &ValueRef) -> bool {
// Both must be sitofp from integers of the same width.
let lb = lhs.borrow();
let rb = rhs.borrow();
if lb.opcode != Some(llvm_native_core::opcode::Opcode::SIToFP)
|| rb.opcode != Some(llvm_native_core::opcode::Opcode::SIToFP)
{
return false;
}
// Both operands must have a source integer operand.
if lb.operands.is_empty() || rb.operands.is_empty() {
return false;
}
// Check that the integer types match.
let li_ty = &lb.operands[0].borrow().ty;
let ri_ty = &rb.operands[0].borrow().ty;
if li_ty.id != ri_ty.id {
return false;
}
// Check that the integer width doesn't exceed float mantissa precision.
let mantissa_bits = match lb.ty.kind {
TypeKind::Double => 53,
TypeKind::Float => 24,
TypeKind::Half => 11,
_ => return false,
};
let int_bits = match li_ty.kind {
TypeKind::Integer { bits } => bits,
_ => return false,
};
// Safe if integer width ≤ mantissa bits.
int_bits <= mantissa_bits
}
/// Check if a value is float zero (0.0 or -0.0).
fn is_float_zero(&self, val: &ValueRef) -> bool {
let vb = val.borrow();
if vb.subclass == SubclassKind::ConstantFP || vb.subclass == SubclassKind::Constant {
// Check if the constant name contains "0.0" or "-0.0".
if let Some(c) = get_constant_float_value(&vb.name) {
return c == 0.0 || c == -0.0;
}
}
false
}
}
/// Extract a float constant value from a name string.
fn get_constant_float_value(name: &str) -> Option<f64> {
if let Some(num_str) = name.split_whitespace().last() {
return num_str.parse::<f64>().ok();
}
None
}
// ============================================================================
// FMA (Fused Multiply-Add) Detection for Float-to-Int
// ============================================================================
/// Detects fmul+fadd patterns (fma) that can be converted to
/// integer mul+add when operands are exact integers.
#[derive(Debug, Default)]
pub struct FMADetector {
/// Number of FMA patterns found.
pub fma_patterns: usize,
/// Number of FMA patterns converted to integer.
pub converted: usize,
}
impl FMADetector {
/// Create a new detector.
pub fn new() -> Self {
Self::default()
}
/// Run FMA detection and conversion on a function.
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.fma_patterns = 0;
self.converted = 0;
let f = func.borrow();
for bb in &f.operands {
if bb.borrow().subclass == SubclassKind::BasicBlock {
self.detect_in_block(bb);
}
}
self.converted
}
/// Detect and rewrite FMA patterns in a single block.
fn detect_in_block(&mut self, bb: &ValueRef) {
let insts: Vec<ValueRef> = bb
.borrow()
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.cloned()
.collect();
for inst in &insts {
let ib = inst.borrow();
if ib.opcode != Some(llvm_native_core::opcode::Opcode::FAdd) {
continue;
}
if ib.operands.len() < 2 {
continue;
}
let lhs = &ib.operands[0];
let rhs = &ib.operands[1];
// Check for: fadd(fmul(a, b), c) or fadd(c, fmul(a, b))
let fmul = if lhs.borrow().opcode == Some(llvm_native_core::opcode::Opcode::FMul) {
Some(lhs.clone())
} else if rhs.borrow().opcode == Some(llvm_native_core::opcode::Opcode::FMul) {
Some(rhs.clone())
} else {
None
};
if let Some(fmul_inst) = fmul {
self.fma_patterns += 1;
// Check if we can convert the FMA to integer mul+add.
if self.try_convert_fma_to_int(inst, &fmul_inst, lhs, rhs) {
self.converted += 1;
}
}
}
}
/// Try to convert a float FMA pattern to integer operations.
fn try_convert_fma_to_int(
&self,
_fadd: &ValueRef,
fmul: &ValueRef,
_lhs: &ValueRef,
_rhs: &ValueRef,
) -> bool {
let fb = fmul.borrow();
if fb.operands.len() < 2 {
return false;
}
let mul_a = &fb.operands[0];
let mul_b = &fb.operands[1];
// Check if mul_a and mul_b are exact integer floats.
let a_is_int = is_exact_int_float(mul_a);
let b_is_int = is_exact_int_float(mul_b);
a_is_int && b_is_int
}
}
/// Check if a float value is an exact integer representation.
fn is_exact_int_float(val: &ValueRef) -> bool {
let vb = val.borrow();
matches!(
vb.opcode,
Some(llvm_native_core::opcode::Opcode::SIToFP)
| Some(llvm_native_core::opcode::Opcode::UIToFP)
| Some(llvm_native_core::opcode::Opcode::FPToSI)
| Some(llvm_native_core::opcode::Opcode::FPToUI)
) || vb.subclass == SubclassKind::ConstantFP
|| vb.subclass == SubclassKind::Constant
}
// ============================================================================
// Float2Int Driver with All Optimizations
// ============================================================================
/// Comprehensive driver that orchestrates all float-to-int optimizations.
#[derive(Debug, Default)]
pub struct Float2IntDriver {
/// The base Float2Int pass.
pub base: Float2IntPass,
/// Chain detector.
pub chain_detector: Float2IntChainDetector,
/// Fabs+fcmp rewriter.
pub fabs_fcmp: FabsFcmpRewriter,
/// Fadd/fsub rewriter.
pub fadd_fsub: FaddFsubRewriter,
/// FMA detector.
pub fma_detector: FMADetector,
/// Statistics.
pub stats: Float2IntStats,
}
/// Statistics from the float-to-int optimization pipeline.
#[derive(Debug, Clone, Default)]
pub struct Float2IntStats {
/// Total float operations converted to int.
pub float_ops_converted: usize,
/// Chains detected and converted.
pub chains_converted: usize,
/// Fabs+fcmp rewrites.
pub fabs_fcmp_rewrites: usize,
/// Fadd/fsub rewrites.
pub fadd_fsub_rewrites: usize,
/// FMA patterns converted.
pub fma_converted: usize,
/// Total instructions eliminated.
pub total_eliminated: usize,
}
impl Float2IntDriver {
/// Create a new driver.
pub fn new() -> Self {
Self::default()
}
/// Run the full float-to-int optimization pipeline.
pub fn run_on_function(&mut self, func: &ValueRef) -> &Float2IntStats {
self.stats = Float2IntStats::default();
// Stage 1: Base Float2Int pass.
self.stats.float_ops_converted = self.base.run_on_function(func);
// Stage 2: Chain detection and conversion.
self.chain_detector.detect(func);
self.stats.chains_converted = self.chain_detector.get_chains().len();
// Stage 3: Fabs+fcmp rewriting.
self.stats.fabs_fcmp_rewrites = self.fabs_fcmp.run_on_function(func);
// Stage 4: Fadd/fsub pattern rewriting.
self.stats.fadd_fsub_rewrites = self.fadd_fsub.run_on_function(func);
self.stats.total_eliminated += self.fadd_fsub.simplified;
// Stage 5: FMA detection and conversion.
self.stats.fma_converted = self.fma_detector.run_on_function(func);
self.stats.total_eliminated += self.stats.float_ops_converted
+ self.stats.chains_converted
+ self.stats.fabs_fcmp_rewrites
+ self.stats.fadd_fsub_rewrites
+ self.stats.fma_converted;
&self.stats
}
}
// ============================================================================
// Top-level entry points
// ============================================================================
/// Run the standard Float2Int pass on a function.
pub fn run_float2int(func: &ValueRef) -> usize {
let mut pass = Float2IntPass::new();
pass.run_on_function(func)
}
/// Run the comprehensive Float2Int optimization pipeline.
pub fn run_float2int_pipeline(func: &ValueRef) -> Float2IntStats {
let mut driver = Float2IntDriver::new();
driver.run_on_function(func);
driver.stats
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use llvm_native_core::value::{valref, Value};
fn make_float_inst(name: &str, opcode: llvm_native_core::opcode::Opcode) -> ValueRef {
let mut v = Value::new(llvm_native_core::types::Type::float())
.named(name)
.with_subclass(SubclassKind::Instruction);
v.opcode = Some(opcode);
// Add dummy operands
let op1 = llvm_native_core::constants::const_float(3.0);
let op2 = llvm_native_core::constants::const_float(5.0);
v.operands = vec![op1, op2];
v.num_operands = 2;
valref(v)
}
fn make_double_inst(name: &str, opcode: llvm_native_core::opcode::Opcode) -> ValueRef {
let mut v = Value::new(llvm_native_core::types::Type::double())
.named(name)
.with_subclass(SubclassKind::Instruction);
v.opcode = Some(opcode);
let op1 = llvm_native_core::constants::const_double(3.0);
let op2 = llvm_native_core::constants::const_double(5.0);
v.operands = vec![op1, op2];
v.num_operands = 2;
valref(v)
}
#[test]
fn test_create_pass() {
let pass = Float2IntPass::new();
assert_eq!(pass.converted, 0);
}
#[test]
fn test_is_float_type() {
let pass = Float2IntPass::new();
assert!(pass.is_float_type(&Type::float()));
assert!(pass.is_float_type(&Type::double()));
assert!(!pass.is_float_type(&Type::i32()));
assert!(!pass.is_float_type(&Type::void()));
}
#[test]
fn test_exact_float_representable_integers() {
let pass = Float2IntPass::new();
// Small integers should be exactly representable in float
assert!(pass.is_exact_float_representable(0.0, &Type::float()));
assert!(pass.is_exact_float_representable(1.0, &Type::float()));
assert!(pass.is_exact_float_representable(42.0, &Type::float()));
assert!(pass.is_exact_float_representable(-100.0, &Type::float()));
}
#[test]
fn test_exact_float_not_representable_fractional() {
let pass = Float2IntPass::new();
assert!(!pass.is_exact_float_representable(3.14, &Type::float()));
assert!(!pass.is_exact_float_representable(0.5, &Type::float()));
}
#[test]
fn test_exact_float_not_representable_nan() {
let pass = Float2IntPass::new();
assert!(!pass.is_exact_float_representable(f64::NAN, &Type::float()));
assert!(!pass.is_exact_float_representable(f64::INFINITY, &Type::float()));
}
#[test]
fn test_exact_float_double_large_int() {
let pass = Float2IntPass::new();
// 2^53 is the limit for double (53-bit mantissa including implicit bit)
assert!(pass.is_exact_float_representable(9007199254740992.0, &Type::double()));
// 2^54 is beyond mantissa precision for exact integer representation
assert!(!pass.is_exact_float_representable(18014398509481984.0, &Type::double()));
}
#[test]
fn test_mantissa_bits() {
let pass = Float2IntPass::new();
assert_eq!(pass.get_float_mantissa_bits(&Type::float()), 24);
assert_eq!(pass.get_float_mantissa_bits(&Type::double()), 53);
assert_eq!(pass.get_float_mantissa_bits(&Type::half()), 11);
}
#[test]
fn test_choose_integer_type() {
let pass = Float2IntPass::new();
let i32_ty = pass.choose_integer_type(&Type::float());
assert_eq!(i32_ty.kind, llvm_native_core::types::TypeKind::Integer { bits: 32 });
let i64_ty = pass.choose_integer_type(&Type::double());
assert_eq!(i64_ty.kind, llvm_native_core::types::TypeKind::Integer { bits: 64 });
}
#[test]
fn test_is_const_exact_integer() {
let pass = Float2IntPass::new();
let const_float = llvm_native_core::constants::const_float(7.0);
assert!(pass.is_const_exact_integer(&const_float));
}
#[test]
fn test_is_const_not_exact_integer() {
let pass = Float2IntPass::new();
let const_float = llvm_native_core::constants::const_float(3.14);
assert!(!pass.is_const_exact_integer(&const_float));
}
#[test]
fn test_can_convert_to_int_fadd() {
let pass = Float2IntPass::new();
let inst = make_float_inst("fadd", llvm_native_core::opcode::Opcode::FAdd);
// Operands are constants with exact integer values
assert!(pass.can_convert_to_int(&inst));
}
#[test]
fn test_cannot_convert_to_int_fdiv() {
let pass = Float2IntPass::new();
let inst = make_float_inst("fdiv", llvm_native_core::opcode::Opcode::FDiv);
assert!(!pass.can_convert_to_int(&inst));
}
#[test]
fn test_default() {
let pass = Float2IntPass::default();
assert_eq!(pass.converted, 0);
}
#[test]
fn test_run_on_function_no_blocks() {
let mut pass = Float2IntPass::new();
let mut func = Value::new(llvm_native_core::types::Type::void());
func.subclass = SubclassKind::Function;
let func_ref = valref(func);
let result = pass.run_on_function(&func_ref);
assert_eq!(result, 0);
}
}