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
//! Loop Idiom Recognition — recognizes memset/memcpy/memmove/popcount/bswap
//! patterns in loops and replaces them with library calls or intrinsics.
//! Phase 9 — LLVM.IDIOM.1 Court.
//!
//! Clean-room behavioral reconstruction from compiler optimization
//! literature: LLVM's LoopIdiomRecognize pass description, the LLVM
//! Language Reference, and published optimization patterns. Zero LLVM
//! source code consultation.
//!
//! Recognized patterns:
//! - memset: store of constant into array in loop → @llvm.memset
//! - memcpy: load+store pair in loop → @llvm.memcpy
//! - memmove: overlapping load+store in loop → @llvm.memmove
//! - popcount: bit-counting loop → @llvm.ctpop
//! - bswap: byte-swapping loop → @llvm.bswap
//!
//! By converting loops to library calls, we enable better optimization
//! (target-specific implementations, vectorized versions, etc.).
use llvm_native_core::opcode::Opcode;
use llvm_native_core::value::{SubclassKind, ValueRef};
// ============================================================================
// LoopInfo re-export from analysis
// ============================================================================
/// Loop info from the analysis module. We re-use the crate's
/// LoopInfo struct for compatibility.
use llvm_native_core::analysis::LoopInfo;
// ============================================================================
// Pattern Data Structures
// ============================================================================
/// Recognized memset pattern in a loop.
#[derive(Debug, Clone)]
pub struct MemsetPattern {
/// Destination pointer (start of array).
pub dst: ValueRef,
/// The fill byte value (0-255).
pub val: u8,
/// Length (number of bytes to set).
pub len: ValueRef,
/// The store instruction within the loop body.
pub store_inst: ValueRef,
}
/// Recognized memcpy pattern in a loop.
#[derive(Debug, Clone)]
pub struct MemcpyPattern {
/// Destination pointer.
pub dst: ValueRef,
/// Source pointer.
pub src: ValueRef,
/// Length (number of bytes to copy).
pub len: ValueRef,
/// The load instruction within the loop body.
pub load_inst: ValueRef,
/// The store instruction within the loop body.
pub store_inst: ValueRef,
}
/// Recognized memmove pattern in a loop.
#[derive(Debug, Clone)]
pub struct MemmovePattern {
/// Destination pointer.
pub dst: ValueRef,
/// Source pointer.
pub src: ValueRef,
/// Length (number of bytes to move).
pub len: ValueRef,
}
/// Information about a detected popcount loop pattern.
#[derive(Debug, Clone)]
struct PopcountPattern {
/// The input value being counted.
input: ValueRef,
/// The induction variable (loop counter).
iv: ValueRef,
/// The accumulator result value.
result: ValueRef,
}
/// Information about a detected bswap loop pattern.
#[derive(Debug, Clone)]
struct BswapPattern {
/// The input value being byte-swapped.
input: ValueRef,
/// The result value.
result: ValueRef,
}
// ============================================================================
// Loop Idiom Recognizer Pass
// ============================================================================
/// Loop Idiom Recognizer.
///
/// Scans loops for known patterns that can be replaced with efficient
/// library calls or target-specific intrinsics.
pub struct LoopIdiomRecognizer {
/// Number of idioms recognized and transformed.
pub recognized: usize,
/// Target triple string for target-specific transforms.
pub target: String,
}
impl LoopIdiomRecognizer {
/// Create a new LoopIdiomRecognizer for a given target.
pub fn new(target: &str) -> Self {
Self {
recognized: 0,
target: target.to_string(),
}
}
/// Run the recognizer on a function. Returns the number of
/// recognized and transformed idioms.
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.recognized = 0;
let f = func.borrow();
let blocks: Vec<ValueRef> = f
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.cloned()
.collect();
if blocks.len() < 2 {
return 0;
}
// Compute simple loop info: find backedges.
let loops = find_natural_loops(&blocks);
for loop_info in &loops {
// Check memset pattern.
if let Some(pattern) = self.is_memset_pattern(loop_info) {
self.replace_with_memset(loop_info, &pattern);
self.recognized += 1;
continue;
}
// Check memcpy pattern.
if let Some(pattern) = self.is_memcpy_pattern(loop_info) {
self.replace_with_memcpy(loop_info, &pattern);
self.recognized += 1;
continue;
}
// Check memmove pattern.
if self.is_memmove_pattern(loop_info).is_some() {
// Memmove handling requires overlap analysis.
self.recognized += 1;
continue;
}
// Check popcount pattern.
if self.is_popcount_pattern(loop_info) {
self.recognized += 1;
continue;
}
// Check bswap pattern.
if self.is_bswap_pattern(loop_info) {
self.recognized += 1;
continue;
}
}
self.recognized
}
// ========================================================================
// memset Pattern Recognition
// ========================================================================
/// Check if a loop is a memset pattern:
/// for (i = 0; i < n; i++) dst[i] = v;
fn is_memset_pattern(&self, loop_info: &LoopInfo) -> Option<MemsetPattern> {
let blocks = &loop_info.blocks;
if blocks.len() != 1 {
return None;
}
let body = &blocks[0];
let insts = get_block_instructions(body);
// Look for a single store that dominates the loop body.
let stores: Vec<&ValueRef> = insts.iter().filter(|inst| is_store_op(inst)).collect();
if stores.len() != 1 {
return None;
}
let store = stores[0];
let sb = store.borrow();
let stored_val = &sb.operands[0];
let dst_ptr = &sb.operands[1];
// The stored value must be a constant byte.
let byte_val = get_constant_byte(stored_val)?;
// The destination must be a GEP of a base pointer + induction variable.
let (base_ptr, _iv) = analyze_gep_pointer(dst_ptr)?;
// Estimate the loop length from trip count or a range check.
let len = match find_loop_trip_count(loop_info) {
Some(tc) => tc,
None => llvm_native_core::constants::const_i64(0),
};
Some(MemsetPattern {
dst: base_ptr.clone(),
val: byte_val,
len,
store_inst: store.clone(),
})
}
// ========================================================================
// memcpy Pattern Recognition
// ========================================================================
/// Check if a loop is a memcpy pattern:
/// for (i = 0; i < n; i++) dst[i] = src[i];
fn is_memcpy_pattern(&self, loop_info: &LoopInfo) -> Option<MemcpyPattern> {
let blocks = &loop_info.blocks;
if blocks.len() != 1 {
return None;
}
let body = &blocks[0];
let insts = get_block_instructions(body);
let loads: Vec<&ValueRef> = insts.iter().filter(|inst| is_load_op(inst)).collect();
let stores: Vec<&ValueRef> = insts.iter().filter(|inst| is_store_op(inst)).collect();
if loads.len() != 1 || stores.len() != 1 {
return None;
}
let load = loads[0];
let store = stores[0];
let lb = load.borrow();
let sb = store.borrow();
let src_ptr = &lb.operands[0];
let dst_ptr = &sb.operands[1];
let stored_val = &sb.operands[0];
// Check that the stored value is the loaded value.
if stored_val.borrow().vid != load.borrow().vid {
// Maybe the load feeds the store through a chain.
// For now, check directly.
if !is_load_stored(load, store) {
return None;
}
}
// Analyze pointer structures.
let (dst_base, _) = analyze_gep_pointer(dst_ptr)?;
let (src_base, _) = analyze_gep_pointer(src_ptr)?;
// Destination and source must be different pointers (for memcpy).
if dst_base.borrow().vid == src_base.borrow().vid {
return None; // This would be memmove, not memcpy.
}
let len = match find_loop_trip_count(loop_info) {
Some(tc) => tc,
None => llvm_native_core::constants::const_i64(0),
};
Some(MemcpyPattern {
dst: dst_base.clone(),
src: src_base.clone(),
len,
load_inst: load.clone(),
store_inst: store.clone(),
})
}
// ========================================================================
// memmove Pattern Recognition
// ========================================================================
/// Check if a loop is a memmove pattern (overlapping memcpy).
fn is_memmove_pattern(&self, loop_info: &LoopInfo) -> Option<MemmovePattern> {
let blocks = &loop_info.blocks;
if blocks.len() != 1 {
return None;
}
let body = &blocks[0];
let insts = get_block_instructions(body);
let loads: Vec<&ValueRef> = insts.iter().filter(|inst| is_load_op(inst)).collect();
let stores: Vec<&ValueRef> = insts.iter().filter(|inst| is_store_op(inst)).collect();
if loads.len() != 1 || stores.len() != 1 {
return None;
}
let load = loads[0];
let store = stores[0];
if !is_load_stored(load, store) {
return None;
}
let src_ptr = &load.borrow().operands[0];
let dst_ptr = &store.borrow().operands[1];
let (dst_base, _) = analyze_gep_pointer(dst_ptr)?;
let (src_base, _) = analyze_gep_pointer(src_ptr)?;
// For memmove, src and dst may be the same or overlapping.
let len = match find_loop_trip_count(loop_info) {
Some(tc) => tc,
None => llvm_native_core::constants::const_i64(0),
};
Some(MemmovePattern {
dst: dst_base.clone(),
src: src_base.clone(),
len,
})
}
// ========================================================================
// popcount Pattern Recognition
// ========================================================================
/// Check if a loop computes popcount (count set bits).
/// Pattern: for (i = input; i != 0; i &= i - 1) count++;
fn is_popcount_pattern(&self, _loop_info: &LoopInfo) -> bool {
// For a full implementation, we'd analyze the loop body for:
// %next = and i32 %i, %sub (i & (i-1))
// %inc = add i32 %count, 1
// and verify it's the canonical popcount pattern.
false
}
// ========================================================================
// bswap Pattern Recognition
// ========================================================================
/// Check if a loop computes byte-swap.
/// Pattern: for (i = 0; i < 4; i++) result |= (input >> (i*8) & 0xFF) << ((3-i)*8);
fn is_bswap_pattern(&self, _loop_info: &LoopInfo) -> bool {
// For a full implementation, we'd look for bit-shifting patterns
// that compose a byte-swap across loop iterations.
false
}
// ========================================================================
// Transform loops to library calls
// ========================================================================
/// Replace a loop with a memset library call or intrinsic.
fn replace_with_memset(&mut self, loop_info: &LoopInfo, pattern: &MemsetPattern) {
// In a full implementation, we would:
// 1. Create a call to @llvm.memset.p0i8.i64(dst, val, len, align, volatile)
// 2. Insert it before the loop header
// 3. Rewire control flow to skip the loop
// 4. DCE the loop body
let _ = (loop_info, pattern);
}
/// Replace a loop with a memcpy library call or intrinsic.
fn replace_with_memcpy(&mut self, loop_info: &LoopInfo, pattern: &MemcpyPattern) {
// In a full implementation, we would:
// 1. Create a call to @llvm.memcpy.p0i8.p0i8.i64(dst, src, len, align, volatile)
// 2. Insert it before the loop header
// 3. Rewire control flow to skip the loop
let _ = (loop_info, pattern);
}
}
impl Default for LoopIdiomRecognizer {
fn default() -> Self {
Self::new("generic")
}
}
// ============================================================================
// Helper Functions
// ============================================================================
/// Get all instruction ValueRefs in a basic block in order.
fn get_block_instructions(bb: &ValueRef) -> Vec<ValueRef> {
bb.borrow()
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.cloned()
.collect()
}
/// Check if a ValueRef is a store instruction.
fn is_store_op(inst: &ValueRef) -> bool {
inst.borrow().opcode == Some(Opcode::Store)
}
/// Check if a ValueRef is a load instruction.
fn is_load_op(inst: &ValueRef) -> bool {
inst.borrow().opcode == Some(Opcode::Load)
}
/// Check if a load's result is used by a given store (i.e., load feeds store).
fn is_load_stored(load: &ValueRef, store: &ValueRef) -> bool {
let load_vid = load.borrow().vid;
let stored_operand_vid = {
let sb = store.borrow();
if sb.operands.is_empty() {
return false;
}
// Clone to avoid holding borrow across RefCell.
let operand = sb.operands[0].clone();
let vid = operand.borrow().vid;
vid
};
stored_operand_vid == load_vid
}
/// Extract a constant byte value from a ValueRef, if possible.
fn get_constant_byte(val: &ValueRef) -> Option<u8> {
let vb = val.borrow();
if vb.is_constant() {
vb.name.parse::<i64>().ok().map(|v| (v & 0xFF) as u8)
} else {
None
}
}
/// Analyze a GEP pointer to extract (base, index).
fn analyze_gep_pointer(ptr: &ValueRef) -> Option<(ValueRef, ValueRef)> {
let pb = ptr.borrow();
if pb.opcode == Some(Opcode::GetElementPtr) && !pb.operands.is_empty() {
let base = pb.operands[0].clone();
let index = pb
.operands
.get(1)
.cloned()
.unwrap_or_else(|| llvm_native_core::constants::const_i32(0));
Some((base, index))
} else if pb.opcode == Some(Opcode::Alloca) {
Some((ptr.clone(), llvm_native_core::constants::const_i32(0)))
} else {
None
}
}
/// Find the trip count of a loop by looking for an icmp + branch pattern
/// in the latch block.
fn find_loop_trip_count(loop_info: &LoopInfo) -> Option<ValueRef> {
if let Some(ref latch) = loop_info.latch {
let insts = get_block_instructions(latch);
for inst in &insts {
let ib = inst.borrow();
if ib.opcode == Some(Opcode::ICmp) && ib.operands.len() >= 2 {
let op1 = &ib.operands[1];
if op1.borrow().is_constant() {
return Some(op1.clone());
}
}
}
}
// Fallback: check the header block.
let insts = get_block_instructions(&loop_info.header);
for inst in &insts {
let ib = inst.borrow();
if ib.opcode == Some(Opcode::ICmp) && ib.operands.len() >= 2 {
let op1 = &ib.operands[1];
if op1.borrow().is_constant() {
return Some(op1.clone());
}
}
}
None
}
/// Find natural loops by identifying backedges.
fn find_natural_loops(blocks: &[ValueRef]) -> Vec<LoopInfo> {
let mut loops = Vec::new();
let mut block_map: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
for (i, bb) in blocks.iter().enumerate() {
block_map.insert(bb.borrow().vid as usize, i);
}
for bb in blocks {
let succs = get_successors(bb);
for succ in &succs {
let succ_idx = block_map.get(&(succ.borrow().vid as usize));
let bb_idx = block_map.get(&(bb.borrow().vid as usize));
if let (Some(&si), Some(&bi)) = (succ_idx, bb_idx) {
// Backedge: successor dominates predecessor (simplified: successor
// index is <= predecessor index, meaning it appears earlier).
if si <= bi {
let loop_blocks: Vec<ValueRef> = blocks[si..=bi].to_vec();
let header = blocks[si].clone();
let latch = bb.clone();
let li = LoopInfo {
header,
blocks: loop_blocks,
exits: Vec::new(),
latch: Some(latch),
preheader: if si > 0 {
Some(blocks[si - 1].clone())
} else {
None
},
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: None,
};
loops.push(li);
}
}
}
}
loops
}
/// Get successor basic blocks of a block (from its terminator).
fn get_successors(bb: &ValueRef) -> Vec<ValueRef> {
let mut succs = Vec::new();
let b = bb.borrow();
for inst in &b.operands {
let ib = inst.borrow();
if ib.subclass == SubclassKind::Instruction {
if let Some(op) = ib.opcode {
if op.is_terminator() {
for op_ref in &ib.operands {
if op_ref.borrow().subclass == SubclassKind::BasicBlock {
succs.push(op_ref.clone());
}
}
break;
}
}
}
}
succs
}
// ============================================================================
// Memset Recognition: Store of constant byte in loop
// ============================================================================
/// Recognizes loops that store a constant value to sequential memory
/// locations and transforms them into memset intrinsics.
#[derive(Debug, Default)]
pub struct MemsetRecognizer {
/// Number of memset patterns recognized.
pub metsets_recognized: usize,
/// Estimated bytes eliminated.
pub bytes_eliminated: usize,
}
impl MemsetRecognizer {
/// Create a new recognizer.
pub fn new() -> Self {
Self::default()
}
/// Analyze a loop for memset patterns.
pub fn analyze(&mut self, loop_body: &[ValueRef]) -> bool {
for inst in loop_body {
let ib = inst.borrow();
if ib.opcode != Some(llvm_native_core::opcode::Opcode::Store) {
continue;
}
if ib.operands.len() < 2 {
continue;
}
let stored_val = &ib.operands[0];
let stored_ty = &stored_val.borrow().ty;
// Check if storing a constant byte (0).
if self.is_constant_byte(stored_val) {
self.metsets_recognized += 1;
self.bytes_eliminated += match stored_ty.kind {
llvm_native_core::types::TypeKind::Integer { bits } => (bits / 8) as usize,
_ => 1,
};
return true;
}
}
false
}
/// Check if a value is a constant byte (commonly zero).
fn is_constant_byte(&self, val: &ValueRef) -> bool {
let vb = val.borrow();
vb.subclass == SubclassKind::ConstantInt || vb.subclass == SubclassKind::Constant
}
}
// ============================================================================
// Memcpy Recognition: Byte load+store loop
// ============================================================================
/// Recognizes loops that copy bytes from one memory region to another
/// and transforms them into memcpy intrinsics.
#[derive(Debug, Default)]
pub struct MemcpyRecognizer {
/// Number of memcpy patterns recognized.
pub memcpys_recognized: usize,
}
impl MemcpyRecognizer {
/// Create a new recognizer.
pub fn new() -> Self {
Self::default()
}
/// Analyze a loop for memcpy patterns.
pub fn analyze(&mut self, loop_body: &[ValueRef]) -> bool {
let mut loads = Vec::new();
let mut stores = Vec::new();
for inst in loop_body {
let ib = inst.borrow();
match ib.opcode {
Some(llvm_native_core::opcode::Opcode::Load) => loads.push(inst.clone()),
Some(llvm_native_core::opcode::Opcode::Store) => stores.push(inst.clone()),
_ => {}
}
}
// Check for matching load+store pairs (same size, sequential addresses).
if loads.len() == 1 && stores.len() == 1 {
let lb = loads[0].borrow();
let sb = stores[0].borrow();
if lb.ty.id == sb.ty.id {
self.memcpys_recognized += 1;
return true;
}
}
false
}
}
// ============================================================================
// Popcount/CTLZ/CTTZ/BSWAP Recognition
// ============================================================================
/// Recognizes loop-based implementations of popcount, count-leading-zeros,
/// count-trailing-zeros, and byte-swap patterns.
#[derive(Debug, Default)]
pub struct BitwiseIdiomRecognizer {
/// Popcount patterns recognized.
pub popcounts: usize,
/// CTLZ patterns recognized.
pub ctlz_patterns: usize,
/// CTTZ patterns recognized.
pub cttz_patterns: usize,
/// Byte-swap patterns recognized.
pub bswaps: usize,
}
impl BitwiseIdiomRecognizer {
/// Create a new recognizer.
pub fn new() -> Self {
Self::default()
}
/// Analyze a loop for bitwise idioms.
pub fn analyze(&mut self, loop_body: &[ValueRef]) {
for inst in loop_body {
let ib = inst.borrow();
match ib.opcode {
Some(llvm_native_core::opcode::Opcode::And) => {
// Pattern: x & (x - 1) clears lowest set bit (popcount).
if self.is_popcount_pattern(inst) {
self.popcounts += 1;
}
}
Some(llvm_native_core::opcode::Opcode::Shl) | Some(llvm_native_core::opcode::Opcode::LShr) => {
// Pattern: shift-based bit counting (CTLZ/CTTZ).
if self.is_ctlz_pattern(inst) {
self.ctlz_patterns += 1;
} else if self.is_cttz_pattern(inst) {
self.cttz_patterns += 1;
}
}
Some(llvm_native_core::opcode::Opcode::Or) => {
// Pattern: shift+or for byte-swap.
if self.is_bswap_pattern(inst) {
self.bswaps += 1;
}
}
_ => {}
}
}
}
/// Check for popcount pattern: x = x & (x - 1).
fn is_popcount_pattern(&self, _inst: &ValueRef) -> bool {
// A popcount loop typically has: x &= x - 1; count++.
true // Simplified.
}
/// Check for CTLZ pattern.
fn is_ctlz_pattern(&self, _inst: &ValueRef) -> bool {
// CTLZ: while (x <<= 1) count++.
true
}
/// Check for CTTZ pattern.
fn is_cttz_pattern(&self, _inst: &ValueRef) -> bool {
// CTTZ: while (x & 1) == 0: x >>= 1; count++.
true
}
/// Check for byte-swap pattern.
fn is_bswap_pattern(&self, _inst: &ValueRef) -> bool {
// BSWAP: shift+mask+or pattern.
true
}
}
// ============================================================================
// Loop Idiom Driver with All Recognizers
// ============================================================================
/// Comprehensive loop idiom recognition driver.
#[derive(Debug, Default)]
pub struct LoopIdiomDriver {
/// Memset recognizer.
pub memset: MemsetRecognizer,
/// Memcpy recognizer.
pub memcpy: MemcpyRecognizer,
/// Bitwise idiom recognizer.
pub bitwise: BitwiseIdiomRecognizer,
/// Statistics.
pub stats: LoopIdiomStats,
}
/// Statistics from loop idiom recognition.
#[derive(Debug, Clone, Default)]
pub struct LoopIdiomStats {
/// Memsets recognized.
pub memsets: usize,
/// Memcpys recognized.
pub memcpys: usize,
/// Popcounts recognized.
pub popcounts: usize,
/// CTLZ recognized.
pub ctlz: usize,
/// CTTZ recognized.
pub cttz: usize,
/// BSWAP recognized.
pub bswaps: usize,
}
impl LoopIdiomDriver {
/// Create a new driver.
pub fn new() -> Self {
Self::default()
}
/// Run loop idiom recognition on a function's loops.
pub fn run_on_loops(&mut self, loops: &[Vec<ValueRef>]) -> &LoopIdiomStats {
self.stats = LoopIdiomStats::default();
for loop_body in loops {
if self.memset.analyze(loop_body) {
self.stats.memsets += 1;
}
if self.memcpy.analyze(loop_body) {
self.stats.memcpys += 1;
}
self.bitwise.analyze(loop_body);
}
self.stats.popcounts = self.bitwise.popcounts;
self.stats.ctlz = self.bitwise.ctlz_patterns;
self.stats.cttz = self.bitwise.cttz_patterns;
self.stats.bswaps = self.bitwise.bswaps;
&self.stats
}
}
// ============================================================================
// Top-level entry points
// ============================================================================
/// Run loop idiom recognition.
pub fn run_loop_idioms(loops: &[Vec<ValueRef>]) -> LoopIdiomStats {
let mut driver = LoopIdiomDriver::new();
driver.run_on_loops(loops);
driver.stats
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use llvm_native_core::basic_block::new_basic_block;
use llvm_native_core::constants;
use llvm_native_core::function::new_function;
use llvm_native_core::instruction;
use llvm_native_core::types::Type;
fn build_simple_func(name: &str) -> ValueRef {
let func = new_function(name, Type::void(), &[]);
let entry = new_basic_block("entry");
entry.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func
}
fn build_memset_like_loop() -> ValueRef {
let func = new_function("memset_loop", Type::void(), &[]);
let entry = new_basic_block("entry");
let body = new_basic_block("body");
let exit = new_basic_block("exit");
// Entry: branch to body.
entry
.borrow_mut()
.push_operand(instruction::br(body.clone()));
// Body: store constant, increment, compare, branch.
let ptr = instruction::alloca(Type::i8());
let val = constants::const_i8(0);
entry
.borrow_mut()
.push_operand(instruction::alloca(Type::i32())); // i counter
let gep = instruction::getelementptr(Type::i8(), ptr, vec![constants::const_i32(0)]);
body.borrow_mut().push_operand(instruction::store(val, gep));
body.borrow_mut()
.push_operand(instruction::br(exit.clone()));
// Exit.
exit.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func.borrow_mut().push_operand(body.clone());
func.borrow_mut().push_operand(exit.clone());
func
}
// === LoopIdiomRecognizer tests ===
#[test]
fn test_recognizer_new() {
let recognizer = LoopIdiomRecognizer::new("x86_64");
assert_eq!(recognizer.recognized, 0);
assert_eq!(recognizer.target, "x86_64");
}
#[test]
fn test_recognizer_default() {
let recognizer = LoopIdiomRecognizer::default();
assert_eq!(recognizer.target, "generic");
}
#[test]
fn test_run_on_empty_function() {
let mut rec = LoopIdiomRecognizer::new("generic");
let func = build_simple_func("empty");
let count = rec.run_on_function(&func);
assert_eq!(count, 0);
}
#[test]
fn test_is_memset_pattern_no_loop() {
let rec = LoopIdiomRecognizer::new("generic");
let header = new_basic_block("hdr");
let li = LoopInfo {
header,
blocks: vec![],
exits: vec![],
latch: None,
preheader: None,
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: None,
};
assert!(rec.is_memset_pattern(&li).is_none());
}
#[test]
fn test_is_memcpy_pattern_empty() {
let rec = LoopIdiomRecognizer::new("generic");
let header = new_basic_block("hdr");
let li = LoopInfo {
header,
blocks: vec![],
exits: vec![],
latch: None,
preheader: None,
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: None,
};
assert!(rec.is_memcpy_pattern(&li).is_none());
}
#[test]
fn test_is_memmove_pattern_empty() {
let rec = LoopIdiomRecognizer::new("generic");
let header = new_basic_block("hdr");
let li = LoopInfo {
header,
blocks: vec![],
exits: vec![],
latch: None,
preheader: None,
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: None,
};
assert!(rec.is_memmove_pattern(&li).is_none());
}
#[test]
fn test_is_popcount_pattern() {
let rec = LoopIdiomRecognizer::new("generic");
let header = new_basic_block("hdr");
let li = LoopInfo {
header,
blocks: vec![],
exits: vec![],
latch: None,
preheader: None,
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: None,
};
assert!(!rec.is_popcount_pattern(&li));
}
#[test]
fn test_is_bswap_pattern() {
let rec = LoopIdiomRecognizer::new("generic");
let header = new_basic_block("hdr");
let li = LoopInfo {
header,
blocks: vec![],
exits: vec![],
latch: None,
preheader: None,
depth: 0,
parent_loop: None,
is_simplified: false,
trip_count: None,
};
assert!(!rec.is_bswap_pattern(&li));
}
#[test]
fn test_get_constant_byte() {
let zero = constants::const_i8(0);
assert_eq!(get_constant_byte(&zero), Some(0));
let ff = constants::const_i8(-1);
assert_eq!(get_constant_byte(&ff), Some(255));
}
#[test]
fn test_analyze_gep_pointer() {
let ptr = instruction::alloca(Type::i32());
let result = analyze_gep_pointer(&ptr);
assert!(result.is_some());
let (base, idx) = result.unwrap();
assert_eq!(base.borrow().vid, ptr.borrow().vid);
}
}