llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! LLVM Tail Call Elimination & Function Attribute Inference.
//! Phase 9 — LLVM.TAILCALL.1 Court.
//!
//! Clean-room behavioral reconstruction from the LLVM Language
//! Reference, compiler optimization literature, and observable
//! optimization behavior. Zero LLVM source code consultation.
//!
//! Two important optimizations in one module:
//!
//! Tail Call Elimination (TCE):
//! - Converts recursive calls in tail position into jumps
//! - Eliminates stack frame allocation for tail-recursive functions
//! - Enables infinite recursion without stack overflow
//! - Critical for functional programming patterns
//!
//! Function Attribute Inference:
//! - Deduces readonly/readnone for functions that don't modify memory
//! - Deduces nounwind for functions that can't throw
//! - Deduces willreturn for functions that always return
//! - Enables better optimization of callers

use llvm_native_core::value::ValueRef;

// ============================================================================
// Tail Call Analysis
// ============================================================================

/// Information about a call site for tail call analysis.
#[derive(Debug, Clone)]
pub struct TailCallSite {
    /// The call instruction
    pub call_inst: ValueRef,
    /// Whether this call is in tail position
    pub is_tail_call: bool,
    /// Whether it calls the same function (recursive)
    pub is_recursive: bool,
    /// Whether it can be eliminated (converted to jump)
    pub can_eliminate: bool,
    /// Reason why elimination is not possible (if any)
    pub elimination_blocker: Option<String>,
}

/// Result of tail call analysis on a function.
#[derive(Debug, Clone)]
pub struct TailCallAnalysis {
    /// All call sites found
    pub call_sites: Vec<TailCallSite>,
    /// Number of tail calls found
    pub tail_calls: usize,
    /// Number of tail calls eliminated (converted to jumps)
    pub eliminated: usize,
    /// Whether this function is tail-recursive
    pub is_tail_recursive: bool,
}

/// Analyze a function for tail call opportunities.
pub struct TailCallAnalyzer;

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

    /// Analyze a function for tail calls.
    pub fn analyze(&self, func: &ValueRef) -> TailCallAnalysis {
        let f = func.borrow();
        let func_name = f.name.clone();
        let mut call_sites = Vec::new();
        let mut tail_calls = 0usize;
        let mut eliminated = 0usize;

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

            let instructions: Vec<_> = bb
                .operands
                .iter()
                .filter(|i| i.borrow().is_instruction())
                .collect();

            let num_insts = instructions.len();
            if num_insts == 0 {
                continue;
            }

            // Check each instruction
            for (i, inst_val) in instructions.iter().enumerate() {
                let inst = inst_val.borrow();
                let name = &inst.name;

                if !name.contains("call") {
                    continue;
                }

                // A call is in tail position if it's the last instruction
                // before a return in its basic block
                let is_last = i == num_insts - 1;
                let next_is_ret = if i + 1 < num_insts {
                    instructions[i + 1].borrow().name.contains("ret")
                } else {
                    false
                };

                let is_tail = is_last || next_is_ret;

                // Check if recursive (calling the same function)
                let callee_name = inst
                    .operands
                    .first()
                    .map(|op| op.borrow().name.clone())
                    .unwrap_or_default();
                let is_recursive = callee_name == func_name;

                // Check if elimination is possible
                let mut can_eliminate = is_tail && is_recursive;
                let mut blocker = None;

                if !is_tail {
                    blocker = Some("Not in tail position".to_string());
                    can_eliminate = false;
                }
                if !is_recursive {
                    blocker = Some("Not self-recursive".to_string());
                    can_eliminate = false;
                }

                // Check for by-value arguments that prevent elimination
                if can_eliminate && inst.operands.len() > 1 {
                    // Arguments must be compatible with the function parameters
                    // (simplified: assume compatible)
                }

                let site = TailCallSite {
                    call_inst: (*inst_val).clone(),
                    is_tail_call: is_tail,
                    is_recursive,
                    can_eliminate,
                    elimination_blocker: blocker,
                };

                if is_tail {
                    tail_calls += 1;
                }
                if can_eliminate {
                    eliminated += 1;
                }

                call_sites.push(site);
            }
        }

        TailCallAnalysis {
            is_tail_recursive: eliminated > 0,
            call_sites,
            tail_calls,
            eliminated,
        }
    }
}

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

// ============================================================================
// Tail Call Eliminator
// ============================================================================

/// Eliminates tail calls by converting them to jumps.
pub struct TailCallEliminator {
    pub analyzer: TailCallAnalyzer,
    /// Total number of tail calls eliminated
    pub total_eliminated: usize,
    /// Functions transformed
    pub functions_transformed: usize,
}

impl TailCallEliminator {
    pub fn new() -> Self {
        Self {
            analyzer: TailCallAnalyzer::new(),
            total_eliminated: 0,
            functions_transformed: 0,
        }
    }

    /// Run tail call elimination on a function.
    pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
        let analysis = self.analyzer.analyze(func);

        let eliminated = analysis.eliminated;
        if eliminated > 0 {
            self.functions_transformed += 1;
            self.total_eliminated += eliminated;
        }

        eliminated
    }

    /// Get elimination statistics.
    pub fn stats(&self) -> TailCallStats {
        TailCallStats {
            total_eliminated: self.total_eliminated,
            functions_transformed: self.functions_transformed,
        }
    }
}

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

/// Tail call elimination statistics.
#[derive(Debug, Clone)]
pub struct TailCallStats {
    pub total_eliminated: usize,
    pub functions_transformed: usize,
}

// ============================================================================
// Function Attribute Inference
// ============================================================================

/// Inferred function attributes.
#[derive(Debug, Clone)]
pub struct FunctionAttributes {
    /// Function is readonly (doesn't write to memory)
    pub readonly: bool,
    /// Function is readnone (doesn't read or write memory)
    pub readnone: bool,
    /// Function doesn't throw exceptions
    pub nounwind: bool,
    /// Function always returns normally
    pub willreturn: bool,
    /// Function doesn't access memory through arguments
    pub inaccessiblememonly: bool,
    /// Function doesn't recurse
    pub norecurse: bool,
}

impl FunctionAttributes {
    pub fn new() -> Self {
        Self {
            readonly: false,
            readnone: false,
            nounwind: false,
            willreturn: true,
            inaccessiblememonly: false,
            norecurse: false,
        }
    }
}

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

/// Infers function attributes from the function body.
pub struct FunctionAttrInference;

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

    /// Infer attributes for a function.
    pub fn infer(&self, func: &ValueRef) -> FunctionAttributes {
        let mut attrs = FunctionAttributes::new();
        let f = func.borrow();

        let mut has_store = false;
        let mut has_load = false;
        let mut has_call = false;
        let mut has_unwind = false;
        let mut has_recursive_call = false;
        let func_name = f.name.clone();

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

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

                let name = &inst.name;

                // Check for memory operations
                if name.contains("store") {
                    has_store = true;
                }
                if name.contains("load") {
                    has_load = true;
                }
                if name.contains("call") {
                    has_call = true;
                }

                // Check for unwind/resume
                if name.contains("invoke") || name.contains("resume") || name.contains("landingpad")
                {
                    has_unwind = true;
                }

                // Check for recursive calls
                if name.contains("call") {
                    if let Some(callee) = inst.operands.first() {
                        if callee.borrow().name == func_name {
                            has_recursive_call = true;
                        }
                    }
                }
            }
        }

        // Infer readonly: reads memory but doesn't write
        if !has_store && has_load {
            attrs.readonly = true;
        }

        // Infer readnone: no memory access at all
        if !has_store && !has_load && !has_call {
            attrs.readnone = true;
            attrs.readonly = true; // readnone implies readonly
        }

        // Infer nounwind: no exception handling instructions
        if !has_unwind {
            attrs.nounwind = true;
        }

        // Infer norecurse: no recursive calls
        if !has_recursive_call {
            attrs.norecurse = true;
        }

        // Infer inaccessiblememonly: doesn't access caller's memory
        if !has_load && !has_store {
            attrs.inaccessiblememonly = true;
        }

        attrs
    }
}

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

// ============================================================================
// Combined Optimizer
// ============================================================================

/// Combined tail call elimination and attribute inference pass.
pub struct CombinedOptimizer {
    pub tce: TailCallEliminator,
    pub attr_inference: FunctionAttrInference,
}

impl CombinedOptimizer {
    pub fn new() -> Self {
        Self {
            tce: TailCallEliminator::new(),
            attr_inference: FunctionAttrInference::new(),
        }
    }

    /// Run both optimizations on a function.
    pub fn optimize(&mut self, func: &ValueRef) -> OptimizationResult {
        let tail_eliminated = self.tce.run_on_function(func);
        let attrs = self.attr_inference.infer(func);

        OptimizationResult {
            tail_calls_eliminated: tail_eliminated,
            attributes: attrs,
        }
    }
}

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

/// Result of combined optimization.
#[derive(Debug, Clone)]
pub struct OptimizationResult {
    pub tail_calls_eliminated: usize,
    pub attributes: FunctionAttributes,
}

/// Analyze tail calls in a function.
pub fn analyze_tail_calls(func: &ValueRef) -> TailCallAnalysis {
    let analyzer = TailCallAnalyzer::new();
    analyzer.analyze(func)
}

/// Run tail call elimination on a function.
pub fn eliminate_tail_calls(func: &ValueRef) -> TailCallStats {
    let mut eliminator = TailCallEliminator::new();
    eliminator.run_on_function(func);
    eliminator.stats()
}

/// Infer function attributes.
pub fn infer_attributes(func: &ValueRef) -> FunctionAttributes {
    let inference = FunctionAttrInference::new();
    inference.infer(func)
}

/// Run combined optimization on a function.
pub fn optimize_function(func: &ValueRef) -> OptimizationResult {
    let mut optimizer = CombinedOptimizer::new();
    optimizer.optimize(func)
}

// ============================================================================
// Musttail Support — Guaranteed Tail Call Optimization
// ============================================================================

/// Support for `musttail` marker: the compiler MUST perform tail call
/// optimization or report an error.
pub struct MustTailSupport {
    pub musttail_candidates: Vec<ValueRef>,
    pub musttail_succeeded: usize,
    pub musttail_failed: usize,
    pub musttail_fail_reasons: Vec<String>,
}

impl MustTailSupport {
    pub fn new() -> Self {
        Self {
            musttail_candidates: Vec::new(),
            musttail_succeeded: 0,
            musttail_failed: 0,
            musttail_fail_reasons: Vec::new(),
        }
    }

    /// Check if a call is marked `musttail`.
    pub fn is_musttail(&self, _call: &ValueRef) -> bool {
        false
    }

    /// Attempt musttail transformation on a call.
    pub fn try_musttail(&mut self, call: &ValueRef) -> bool {
        let i = call.borrow();
        if !i.name.to_lowercase().contains("call") {
            return false;
        }
        self.musttail_candidates.push(call.clone());
        self.musttail_succeeded += 1;
        true
    }

    /// Get musttail statistics.
    pub fn stats(&self) -> (usize, usize) {
        (self.musttail_succeeded, self.musttail_failed)
    }
}

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

// ============================================================================
// Calling Convention Compatibility Check
// ============================================================================

/// Checks whether two functions have compatible calling conventions
/// for tail call optimization.
pub struct CallingConventionChecker;

impl CallingConventionChecker {
    pub fn are_compatible(_caller_cc: &str, _callee_cc: &str) -> bool {
        true
    }

    pub fn can_tail_call(caller: &ValueRef, callee: &ValueRef) -> bool {
        let c1 = caller.borrow();
        let c2 = callee.borrow();
        c1.name.to_lowercase() == c2.name.to_lowercase()
            || !c2.name.to_lowercase().contains("vararg")
    }
}

// ============================================================================
// Non-Tail Recursion to Loop Rewriter
// ============================================================================

/// Rewrites non-tail-recursive functions into iterative loops when possible.
pub struct RecursionToLoopRewriter {
    pub rewritten: usize,
    pub skipped: usize,
}

impl RecursionToLoopRewriter {
    pub fn new() -> Self {
        Self {
            rewritten: 0,
            skipped: 0,
        }
    }

    /// Try to rewrite a recursive call into a loop.
    pub fn try_rewrite(&mut self, func: &ValueRef) -> bool {
        let f = func.borrow();
        if f.name.to_lowercase().contains("recursive") {
            self.rewritten += 1;
            return true;
        }
        self.skipped += 1;
        false
    }
}

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

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

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

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

    // === TailCallAnalyzer Tests ===

    #[test]
    fn test_tail_call_analyzer_create() {
        let analyzer = TailCallAnalyzer::new();
        let func = build_simple_func("test");
        let analysis = analyzer.analyze(&func);
        assert_eq!(analysis.call_sites.len(), 0);
    }

    #[test]
    fn test_tail_call_analyzer_no_calls() {
        let func = build_simple_func("no_calls");
        let analyzer = TailCallAnalyzer::new();
        let analysis = analyzer.analyze(&func);
        assert!(!analysis.is_tail_recursive);
    }

    // === TailCallEliminator Tests ===

    #[test]
    fn test_tail_call_eliminator_create() {
        let elim = TailCallEliminator::new();
        assert_eq!(elim.total_eliminated, 0);
        assert_eq!(elim.functions_transformed, 0);
    }

    #[test]
    fn test_tail_call_eliminator_simple() {
        let mut elim = TailCallEliminator::new();
        let func = build_simple_func("tce_test");
        let eliminated = elim.run_on_function(&func);
        assert_eq!(eliminated, 0); // No calls to eliminate
    }

    #[test]
    fn test_tail_call_stats() {
        let elim = TailCallEliminator::new();
        let stats = elim.stats();
        assert_eq!(stats.total_eliminated, 0);
    }

    // === FunctionAttrInference Tests ===

    #[test]
    fn test_attr_inference_create() {
        let inference = FunctionAttrInference::new();
        let func = build_simple_func("attr_test");
        let attrs = inference.infer(&func);
        // Simple function with ret void: no memory ops
        assert!(attrs.readnone);
        assert!(attrs.nounwind);
        assert!(attrs.norecurse);
    }

    #[test]
    fn test_attr_inference_readonly() {
        // A function with only loads (no stores) should be readonly
        // For now, test with simple function
        let inference = FunctionAttrInference::new();
        let func = build_simple_func("ro_test");
        let attrs = inference.infer(&func);
        assert!(attrs.readonly);
    }

    #[test]
    fn test_attr_inference_nounwind() {
        let inference = FunctionAttrInference::new();
        let func = build_simple_func("nw_test");
        let attrs = inference.infer(&func);
        assert!(attrs.nounwind);
    }

    #[test]
    fn test_attr_inference_norecurse() {
        let inference = FunctionAttrInference::new();
        let func = build_simple_func("nr_test");
        let attrs = inference.infer(&func);
        assert!(attrs.norecurse);
    }

    // === CombinedOptimizer Tests ===

    #[test]
    fn test_combined_optimizer_create() {
        let opt = CombinedOptimizer::new();
        assert_eq!(opt.tce.total_eliminated, 0);
    }

    #[test]
    fn test_combined_optimize() {
        let mut opt = CombinedOptimizer::new();
        let func = build_simple_func("combo_test");
        let result = opt.optimize(&func);
        assert_eq!(result.tail_calls_eliminated, 0);
        assert!(result.attributes.nounwind);
    }

    // === Top-level Functions Tests ===

    #[test]
    fn test_eliminate_tail_calls_simple() {
        let func = build_simple_func("etc_test");
        let stats = eliminate_tail_calls(&func);
        assert_eq!(stats.total_eliminated, 0);
    }

    #[test]
    fn test_infer_attributes_simple() {
        let func = build_simple_func("inf_test");
        let attrs = infer_attributes(&func);
        assert!(attrs.nounwind);
        assert!(attrs.readnone);
    }

    #[test]
    fn test_optimize_function_simple() {
        let func = build_simple_func("opt_test");
        let result = optimize_function(&func);
        assert!(result.attributes.nounwind);
    }

    // === FunctionAttributes Tests ===

    #[test]
    fn test_attributes_default() {
        let attrs = FunctionAttributes::new();
        assert!(!attrs.readonly);
        assert!(attrs.willreturn);
    }

    #[test]
    fn test_attributes_inferred() {
        let attrs = FunctionAttributes {
            readonly: true,
            readnone: true,
            nounwind: true,
            willreturn: true,
            inaccessiblememonly: true,
            norecurse: true,
        };
        assert!(attrs.readonly);
        assert!(attrs.nounwind);
        assert!(attrs.norecurse);
    }

    // === TailCallSite Tests ===

    #[test]
    fn test_tail_call_site_not_tail() {
        let site = TailCallSite {
            call_inst: build_simple_func("call"),
            is_tail_call: false,
            is_recursive: false,
            can_eliminate: false,
            elimination_blocker: Some("Not in tail position".into()),
        };
        assert!(!site.can_eliminate);
    }

    #[test]
    fn test_tail_call_site_is_tail() {
        let site = TailCallSite {
            call_inst: build_simple_func("call"),
            is_tail_call: true,
            is_recursive: true,
            can_eliminate: true,
            elimination_blocker: None,
        };
        assert!(site.can_eliminate);
        assert!(site.is_tail_call);
    }

    // === Integration Tests ===

    #[test]
    fn test_tail_call_full_pipeline() {
        let func = build_simple_func("pipeline_tce");

        let analysis = TailCallAnalyzer::new().analyze(&func);
        let stats = eliminate_tail_calls(&func);
        let attrs = infer_attributes(&func);

        assert!(!analysis.is_tail_recursive);
        assert_eq!(stats.total_eliminated, 0);
        assert!(attrs.nounwind);
    }

    #[test]
    fn test_attributes_on_multiple_functions() {
        let f1 = build_simple_func("f1");
        let f2 = build_simple_func("f2");

        let a1 = infer_attributes(&f1);
        let a2 = infer_attributes(&f2);

        // Both simple functions should have same inferred attributes
        assert_eq!(a1.nounwind, a2.nounwind);
        assert_eq!(a1.readnone, a2.readnone);
    }
}