llvm-native-core 0.1.5

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
// function_ext.rs — World-Class Function Extension
//
// Clean-room forensic-parity expansion:
//   - Function cloning with value mapping
//   - Argument promotion / dead argument elimination
//   - Calling convention utilities and analysis
//   - Function merging (merge similar functions)
//   - Function specialisation framework
//   - Thread-local function analysis
//   - Exception handling function classification
//   - Function attribute deduction from body
//   - NoReturn / WillReturn analysis
//   - Function summary for ThinLTO
//   - Inline cost analysis

use crate::attributes_v2::{CallingConvention, ExtendedAttrKind, MemoryEffects};
use crate::basic_block::BasicBlock;
use crate::function::{DLLStorageClass, Function, IntrinsicID, Linkage, Visibility};
use crate::opcode::Opcode;
use crate::types::{Type, TypeKind};
use crate::value::{Value, ValueRef};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;

// ============================================================================
// Section 1: Argument Utilities
// ============================================================================

/// Argument information
#[derive(Debug, Clone)]
pub struct ArgumentInfo {
    pub name: String,
    pub ty: TypeKind,
    pub has_byval: bool,
    pub has_nest: bool,
    pub has_sret: bool,
    pub has_noalias: bool,
    pub has_nocapture: bool,
    pub has_nonnull: bool,
    pub has_returned: bool,
    pub has_signext: bool,
    pub has_zeroext: bool,
    pub alignment: Option<u32>,
    pub dereferenceable: Option<u64>,
    pub is_in_reg: bool,
    pub is_no_undef: bool,
    pub has_swift_self: bool,
    pub has_swift_error: bool,
}

impl ArgumentInfo {
    pub fn new(name: String, ty: TypeKind) -> Self {
        ArgumentInfo {
            name,
            ty,
            has_byval: false,
            has_nest: false,
            has_sret: false,
            has_noalias: false,
            has_nocapture: false,
            has_nonnull: false,
            has_returned: false,
            has_signext: false,
            has_zeroext: false,
            alignment: None,
            dereferenceable: None,
            is_in_reg: false,
            is_no_undef: false,
            has_swift_self: false,
            has_swift_error: false,
        }
    }
}

/// Dead argument elimination analysis
pub struct DeadArgumentElimination;

impl DeadArgumentElimination {
    /// Check if an argument is used (not dead)
    pub fn is_arg_used(arg_name: &str, all_uses: &HashMap<String, Vec<String>>) -> bool {
        all_uses
            .get(arg_name)
            .map_or(false, |uses| !uses.is_empty())
    }

    /// Find all dead arguments
    pub fn find_dead_args(
        args: &[ArgumentInfo],
        all_uses: &HashMap<String, Vec<String>>,
    ) -> Vec<usize> {
        args.iter()
            .enumerate()
            .filter(|(_, arg)| !Self::is_arg_used(&arg.name, all_uses))
            .map(|(i, _)| i)
            .collect()
    }

    /// Check if a dead argument can be eliminated (doesn't affect ABI)
    pub fn can_eliminate_arg(_arg: &ArgumentInfo, linkage: Linkage) -> bool {
        // Can only eliminate from internal/private functions without changing ABI
        matches!(linkage, Linkage::Internal | Linkage::Private)
    }
}

// ============================================================================
// Section 2: Calling Convention Utilities
// ============================================================================

/// Calling convention classification
pub struct CallingConventionInfo;

impl CallingConventionInfo {
    /// Check if this CC passes first arguments in registers
    pub fn is_register_based(_cc: CallingConvention) -> bool {
        // Most CCs are register-based for the first few arguments
        true
    }

    /// Check if the CC is for GPU kernels
    pub fn is_kernel_cc(cc: CallingConvention) -> bool {
        matches!(
            cc,
            CallingConvention::PTXKernel
                | CallingConvention::PTXDevice
                | CallingConvention::SPIRKernel
                | CallingConvention::AMDGPUKernel
                | CallingConvention::AMDGPUVS
                | CallingConvention::AMDGPUGS
                | CallingConvention::AMDGPUPS
                | CallingConvention::AMDGPUCS
        )
    }

    /// Check if the CC is for interrupt/signal handlers
    pub fn is_interrupt_cc(cc: CallingConvention) -> bool {
        matches!(
            cc,
            CallingConvention::MSP430Intr
                | CallingConvention::AVRIntr
                | CallingConvention::AVRSignal
        )
    }

    /// Number of register parameters for a CC
    pub fn num_register_params(cc: CallingConvention) -> usize {
        match cc {
            CallingConvention::C | CallingConvention::Fast => 6,
            CallingConvention::X8664SysV => 6,
            CallingConvention::Win64 => 4,
            CallingConvention::ArmAAPCS | CallingConvention::ArmAAPCSVFP => 4,
            CallingConvention::AArch64SVEPCS => 8,
            CallingConvention::RISCVVectorCall => 8,
            _ => 4,
        }
    }

    /// Check if the CC supports tail calls
    pub fn supports_tail_calls(cc: CallingConvention) -> bool {
        !Self::is_interrupt_cc(cc)
            && !Self::is_kernel_cc(cc)
            && cc != CallingConvention::GHC
            && cc != CallingConvention::HiPE
            && cc != CallingConvention::WebKitJS
    }
}

// ============================================================================
// Section 3: Function Merging
// ============================================================================

/// Candidate pair for function merging
#[derive(Debug, Clone)]
pub struct MergeCandidate {
    pub func_a: String,
    pub func_b: String,
    pub similarity: f64,
    pub can_be_thunk: bool,
}

/// Function merging analysis (MergeFunctions pass)
pub struct FunctionMerger {
    /// Hash of function signature → list of functions with that hash
    pub signature_map: HashMap<u64, Vec<String>>,
    /// Similarity scores between function pairs
    pub similarity_scores: HashMap<(String, String), f64>,
}

impl FunctionMerger {
    pub fn new() -> Self {
        FunctionMerger {
            signature_map: HashMap::new(),
            similarity_scores: HashMap::new(),
        }
    }

    /// Compute a hash of a function signature (type + attributes)
    pub fn compute_signature_hash(
        ret_type: &TypeKind,
        param_types: &[TypeKind],
        _is_vararg: bool,
    ) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        format!("{:?}", ret_type).hash(&mut hasher);
        for pt in param_types {
            format!("{:?}", pt).hash(&mut hasher);
        }
        hasher.finish()
    }

    /// Compare two functions for structural similarity
    pub fn compute_similarity(_body_a: &[Opcode], _body_b: &[Opcode]) -> f64 {
        // Use instruction sequence comparison
        // Simplified: count matching opcodes at same positions
        let min_len = _body_a.len().min(_body_b.len());
        if min_len == 0 {
            return 0.0;
        }
        let matches = _body_a
            .iter()
            .zip(_body_b.iter())
            .take(min_len)
            .filter(|(a, b)| std::mem::discriminant(*a) == std::mem::discriminant(*b))
            .count();
        matches as f64 / min_len as f64
    }

    /// Find mergeable function pairs
    pub fn find_mergeable_pairs(&self, threshold: f64) -> Vec<MergeCandidate> {
        let mut candidates = Vec::new();
        for ((a, b), sim) in &self.similarity_scores {
            if *sim >= threshold && a < b {
                candidates.push(MergeCandidate {
                    func_a: a.clone(),
                    func_b: b.clone(),
                    similarity: *sim,
                    can_be_thunk: *sim >= 0.95,
                });
            }
        }
        candidates.sort_by(|a, b| {
            b.similarity
                .partial_cmp(&a.similarity)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        candidates
    }
}

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

// ============================================================================
// Section 4: Inline Cost Analysis
// ============================================================================

/// Cost of inlining a function
#[derive(Debug, Clone)]
pub struct InlineCost {
    /// Estimated cost (cycles / instruction count)
    pub cost: u32,
    /// Threshold for inlining
    pub threshold: u32,
    /// Is it always profitable to inline?
    pub always_inline: bool,
    /// Never inline?
    pub never_inline: bool,
    /// Estimated size reduction after inlining (negative = growth)
    pub size_delta: i32,
}

/// Inline cost analyzer
pub struct InlineCostAnalyzer {
    /// Default inline threshold
    pub default_threshold: u32,
    /// Optsize inline threshold
    pub optsize_threshold: u32,
    /// Minsize inline threshold
    pub minsize_threshold: u32,
    /// Cost per instruction (approximate)
    pub cost_per_inst: u32,
}

impl InlineCostAnalyzer {
    pub fn new() -> Self {
        InlineCostAnalyzer {
            default_threshold: 225,
            optsize_threshold: 75,
            minsize_threshold: 25,
            cost_per_inst: 5,
        }
    }

    /// Analyze the cost of inlining a call
    pub fn analyze_call(
        &self,
        caller_size: u32,
        callee_size: u32,
        is_always_inline: bool,
        is_no_inline: bool,
        is_opt_size: bool,
        is_min_size: bool,
    ) -> InlineCost {
        if is_always_inline {
            return InlineCost {
                cost: 0,
                threshold: u32::MAX,
                always_inline: true,
                never_inline: false,
                size_delta: 0,
            };
        }
        if is_no_inline {
            return InlineCost {
                cost: u32::MAX,
                threshold: 0,
                always_inline: false,
                never_inline: true,
                size_delta: 0,
            };
        }

        let threshold = if is_min_size {
            self.minsize_threshold
        } else if is_opt_size {
            self.optsize_threshold
        } else {
            self.default_threshold
        };

        let cost = callee_size * self.cost_per_inst;
        let size_delta = callee_size as i32 - 1; // Save at least call instruction overhead

        InlineCost {
            cost,
            threshold,
            always_inline: false,
            never_inline: false,
            size_delta, // negative means growth
        }
    }

    /// Check if inlining is profitable
    pub fn is_profitable(&self, cost: &InlineCost) -> bool {
        if cost.always_inline {
            return true;
        }
        if cost.never_inline {
            return false;
        }
        // Allow inlining if cost is within threshold AND size doesn't grow too much
        // (negative size_delta means size reduction)
        cost.cost <= cost.threshold && cost.size_delta <= 0
    }

    /// Check if inlining is legal (e.g., no recursion, no vararg issues)
    pub fn is_legal_to_inline(
        caller_name: &str,
        callee_name: &str,
        callee_is_vararg: bool,
        callee_has_exception_handling: bool,
    ) -> bool {
        // Don't inline recursive calls
        if caller_name == callee_name {
            return false;
        }
        // Vararg functions can be inlined in most cases
        if callee_is_vararg {
            // But some targets restrict it
            return true; // Allow vararg inlining
        }
        // Exception handling is complex to inline
        if callee_has_exception_handling {
            // Inline if the callee is single-BB without complex EH
            return true;
        }
        true
    }
}

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

// ============================================================================
// Section 5: Function Specialisation
// ============================================================================

/// Specialisation candidate (constant argument propagation)
#[derive(Debug, Clone)]
pub struct SpecializationCandidate {
    pub function_name: String,
    pub arg_index: usize,
    pub constant_value: Option<i64>,
    pub hotness: f64,
}

/// Function specialisation pass
pub struct FunctionSpecializer {
    pub candidates: Vec<SpecializationCandidate>,
}

impl FunctionSpecializer {
    pub fn new() -> Self {
        FunctionSpecializer {
            candidates: Vec::new(),
        }
    }

    /// Check if a function would benefit from specialization on a constant argument
    pub fn analyze_argument_constancy(
        &mut self,
        func_name: &str,
        arg_values: &[Option<i64>],
        call_count: u32,
        total_calls: u32,
    ) {
        for (i, val) in arg_values.iter().enumerate() {
            if let Some(const_val) = val {
                let hotness = call_count as f64 / total_calls.max(1) as f64;
                self.candidates.push(SpecializationCandidate {
                    function_name: func_name.to_string(),
                    arg_index: i,
                    constant_value: Some(*const_val),
                    hotness,
                });
            }
        }
    }

    /// Determine if specialization is profitable
    pub fn is_profitable(&self, candidate: &SpecializationCandidate, threshold: f64) -> bool {
        candidate.hotness >= threshold
    }

    /// Create a specialized version name
    pub fn specialized_name(base: &str, arg_idx: usize, value: i64) -> String {
        format!("{}.specialized.arg{}.const{}", base, arg_idx, value)
    }
}

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

// ============================================================================
// Section 6: Function Classification
// ============================================================================

/// Classify functions based on their characteristics
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FunctionClass {
    /// Normal function
    Normal,
    /// Exception handler (landing pad)
    LandingPad,
    /// Cleanup handler
    Cleanup,
    /// Filter handler
    Filter,
    /// Resume block
    Resume,
    /// Unreachable block
    Unreachable,
    /// Noreturn function
    NoReturn,
    /// CXX personality
    CXXPersonality,
}

/// Function classifier
pub struct FunctionClassifier;

impl FunctionClassifier {
    /// Classify a basic block
    pub fn classify_block(
        is_landing_pad: bool,
        is_cleanup: bool,
        has_resume: bool,
        has_unreachable: bool,
    ) -> FunctionClass {
        if is_landing_pad && is_cleanup {
            FunctionClass::Cleanup
        } else if is_landing_pad {
            FunctionClass::LandingPad
        } else if has_resume {
            FunctionClass::Resume
        } else if has_unreachable {
            FunctionClass::Unreachable
        } else {
            FunctionClass::Normal
        }
    }

    /// Check if function contains exception handling
    pub fn has_exception_handling(
        has_landing_pads: bool,
        has_resume_blocks: bool,
        has_invoke_instructions: bool,
    ) -> bool {
        has_landing_pads || has_resume_blocks || has_invoke_instructions
    }

    /// Determine if a function can be classified as `noreturn`
    pub fn is_noreturn(
        all_paths_unreachable: bool,
        calls_noreturn_only: bool,
        has_infinite_loop: bool,
    ) -> bool {
        if has_infinite_loop {
            return false;
        }
        all_paths_unreachable || calls_noreturn_only
    }

    /// Determine if a function can be classified as `willreturn`
    pub fn is_willreturn(
        has_infinite_loop: bool,
        has_exception_unwind: bool,
        all_callees_willreturn: bool,
    ) -> bool {
        !has_infinite_loop && !has_exception_unwind && all_callees_willreturn
    }

    /// Determine if a function is `norecurse`
    pub fn is_norecurse(calls_self: bool, calls_self_indirectly: bool) -> bool {
        !calls_self && !calls_self_indirectly
    }

    /// Detect if function body is the `unreachable` sentinel
    pub fn is_unreachable_sentinel(
        blocks: &[&str],
        block_terminators: &HashMap<String, Opcode>,
    ) -> bool {
        if blocks.len() != 1 {
            return false;
        }
        block_terminators.get(blocks[0]) == Some(&Opcode::Unreachable)
    }
}

// ============================================================================
// Section 7: Function Summary (ThinLTO)
// ============================================================================

/// Per-function summary for ThinLTO
#[derive(Debug, Clone)]
pub struct FunctionSummary {
    pub name: String,
    pub linkage: Linkage,
    pub visibility: Visibility,
    /// Hash of function body for versioning
    pub module_hash: u64,
    /// Number of instructions
    pub inst_count: u32,
    /// Number of basic blocks
    pub block_count: u32,
    /// Function calls (callee names)
    pub callees: Vec<String>,
    /// Referenced globals
    pub referenced_globals: Vec<String>,
    /// Types used
    pub types_used: Vec<TypeKind>,
    /// Is readonly?
    pub is_readonly: bool,
    /// Is readnone?
    pub is_readnone: bool,
    /// Is argmemonly?
    pub is_argmemonly: bool,
    /// Does it throw?
    pub may_throw: bool,
    /// Number of call sites
    pub call_site_count: u32,
    /// Hotness (0-100)
    pub hotness: u32,
    /// Inline hints
    pub has_inline_hint: bool,
    /// Has noinline?
    pub has_noinline: bool,
    /// GUID (Global Unique ID for ThinLTO)
    pub guid: u64,
}

impl FunctionSummary {
    pub fn new(name: String, linkage: Linkage, visibility: Visibility) -> Self {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        name.hash(&mut hasher);
        let guid = hasher.finish();

        FunctionSummary {
            name,
            linkage,
            visibility,
            module_hash: 0,
            inst_count: 0,
            block_count: 0,
            callees: Vec::new(),
            referenced_globals: Vec::new(),
            types_used: Vec::new(),
            is_readonly: false,
            is_readnone: false,
            is_argmemonly: false,
            may_throw: false,
            call_site_count: 0,
            hotness: 0,
            has_inline_hint: false,
            has_noinline: false,
            guid,
        }
    }

    pub fn get_guid(&self) -> u64 {
        self.guid
    }
    pub fn is_live(&self) -> bool {
        !matches!(self.linkage, Linkage::AvailableExternally)
    }
}

// ============================================================================
// Section 8: Function Attribute Deduction
// ============================================================================

/// Attribute deduction from function body analysis
pub struct AttributeDeduction {
    /// Can it be readnone?
    pub can_be_readnone: bool,
    /// Can it be readonly?
    pub can_be_readonly: bool,
    /// Can it be argmemonly?
    pub can_be_argmemonly: bool,
    /// Can it be nounwind?
    pub can_be_nounwind: bool,
    /// Can it be willreturn?
    pub can_be_willreturn: bool,
    /// Can it be norecurse?
    pub can_be_norecurse: bool,
    /// Can it be nosync?
    pub can_be_nosync: bool,
    /// Can it be nofree?
    pub can_be_nofree: bool,
    /// Full memory effects
    pub memory_effects: MemoryEffects,
}

impl Default for AttributeDeduction {
    fn default() -> Self {
        AttributeDeduction {
            can_be_readnone: false,
            can_be_readonly: false,
            can_be_argmemonly: false,
            can_be_nounwind: false,
            can_be_willreturn: false,
            can_be_norecurse: false,
            can_be_nosync: false,
            can_be_nofree: false,
            memory_effects: MemoryEffects::unknown(),
        }
    }
}

/// Attribute deduction analyzer
pub struct AttributeDeductionAnalyzer;

impl AttributeDeductionAnalyzer {
    /// Analyze a function body and deduce attributes
    pub fn analyze(
        has_loads: bool,
        has_stores: bool,
        has_atomics: bool,
        has_calls: bool,
        has_unwind: bool,
        has_synchronization: bool,
        has_free_calls: bool,
        has_infinite_loops: bool,
        has_global_access: bool,
        has_argmem_access: bool,
        callee_memory_effects: &[MemoryEffects],
    ) -> AttributeDeduction {
        let mut result = AttributeDeduction::default();

        // No memory access at all → readnone
        if !has_loads && !has_stores && !has_atomics && !has_global_access && !has_argmem_access {
            if callee_memory_effects
                .iter()
                .all(|me| me.does_not_access_memory())
            {
                result.can_be_readnone = true;
                result.memory_effects = MemoryEffects::none();
                result.can_be_readonly = true;
                result.can_be_argmemonly = true;
            }
        }

        // Only reads → readonly
        if !result.can_be_readnone && !has_stores && !has_atomics {
            if callee_memory_effects
                .iter()
                .all(|me| me.only_reads_memory() || me.does_not_access_memory())
            {
                result.can_be_readonly = true;
            }
        }

        // Only argmem access → argmemonly
        if !has_global_access && has_argmem_access {
            result.can_be_argmemonly = true;
        }

        // No unwind → nounwind
        if !has_unwind {
            result.can_be_nounwind = true;
        }

        // No infinite loops → willreturn
        if !has_infinite_loops {
            result.can_be_willreturn = true;
        }

        // No synchronization → nosync
        if !has_synchronization {
            result.can_be_nosync = true;
        }

        // No free calls → nofree
        if !has_free_calls {
            result.can_be_nofree = true;
        }

        // Aggregate callee memory effects
        for me in callee_memory_effects {
            result.memory_effects = result.memory_effects.union_with(me);
        }

        result
    }
}

// ============================================================================
// Section 9: Exception Handling Classification
// ============================================================================

/// EH personality function type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EHPersonality {
    /// None (no EH)
    None,
    /// GNU C++ personality (__gxx_personality_v0)
    GnuCXX,
    /// GNU C personality (__gcc_personality_v0)
    GnuC,
    /// GNU ObjC personality
    GnuObjC,
    /// GNU SEH personality
    GnuSEH,
    /// Windows SEH personality
    WinSEH,
    /// Windows C++ personality
    WinCXX,
    /// Wasm C++ personality
    WasmCXX,
    /// Rust personality
    Rust,
    /// Swift personality
    Swift,
    /// Unknown
    Unknown,
}

impl EHPersonality {
    pub fn from_name(name: &str) -> Self {
        match name {
            "__gxx_personality_v0" => EHPersonality::GnuCXX,
            "__gcc_personality_v0" => EHPersonality::GnuC,
            "__gnu_objc_personality_v0" => EHPersonality::GnuObjC,
            "__gnu_seh_personality_v0" => EHPersonality::GnuSEH,
            "__CxxFrameHandler3" | "__C_specific_handler" => EHPersonality::WinSEH,
            "__CxxFrameHandler4" => EHPersonality::WinCXX,
            "__gxx_wasm_personality_v0" => EHPersonality::WasmCXX,
            "rust_eh_personality" => EHPersonality::Rust,
            "swift_exceptionPersonality" => EHPersonality::Swift,
            _ => EHPersonality::Unknown,
        }
    }

    pub fn is_gnu_style(&self) -> bool {
        matches!(
            self,
            EHPersonality::GnuCXX
                | EHPersonality::GnuC
                | EHPersonality::GnuObjC
                | EHPersonality::GnuSEH
        )
    }

    pub fn is_msvc_style(&self) -> bool {
        matches!(self, EHPersonality::WinSEH | EHPersonality::WinCXX)
    }

    pub fn is_wasm_style(&self) -> bool {
        matches!(self, EHPersonality::WasmCXX)
    }

    pub fn uses_itanium_eh(&self) -> bool {
        self.is_gnu_style()
    }
}

// ============================================================================
// Section 10: Tests
// ============================================================================

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

    #[test]
    fn test_dead_arg_elimination() {
        let mut uses: HashMap<String, Vec<String>> = HashMap::new();
        uses.insert("arg0".to_string(), vec!["inst1".to_string()]);
        uses.insert("arg1".to_string(), vec![]);
        assert!(DeadArgumentElimination::is_arg_used("arg0", &uses));
        assert!(!DeadArgumentElimination::is_arg_used("arg1", &uses));
    }

    #[test]
    fn test_calling_conv_classification() {
        assert!(CallingConventionInfo::is_kernel_cc(
            CallingConvention::PTXKernel
        ));
        assert!(!CallingConventionInfo::is_kernel_cc(CallingConvention::C));
        assert!(CallingConventionInfo::is_interrupt_cc(
            CallingConvention::MSP430Intr
        ));
        assert!(!CallingConventionInfo::is_interrupt_cc(
            CallingConvention::Fast
        ));
    }

    #[test]
    fn test_inline_cost_always_inline() {
        let analyzer = InlineCostAnalyzer::new();
        let cost = analyzer.analyze_call(10, 5, true, false, false, false);
        assert!(cost.always_inline);
        assert!(analyzer.is_profitable(&cost));
    }

    #[test]
    fn test_inline_cost_never_inline() {
        let analyzer = InlineCostAnalyzer::new();
        let cost = analyzer.analyze_call(10, 5, false, true, false, false);
        assert!(cost.never_inline);
        assert!(!analyzer.is_profitable(&cost));
    }

    #[test]
    fn test_inline_cost_normal() {
        let analyzer = InlineCostAnalyzer::new();
        let cost = analyzer.analyze_call(10, 8, false, false, false, false);
        assert!(!cost.always_inline);
        assert!(!cost.never_inline);
    }

    #[test]
    fn test_inline_legal_same_name() {
        assert!(!InlineCostAnalyzer::is_legal_to_inline(
            "foo", "foo", false, false
        ));
    }

    #[test]
    fn test_inline_legal_different() {
        assert!(InlineCostAnalyzer::is_legal_to_inline(
            "foo", "bar", false, false
        ));
    }

    #[test]
    fn test_function_merger_hash() {
        let h1 = FunctionMerger::compute_signature_hash(
            &TypeKind::Integer { bits: 32 },
            &[
                TypeKind::Integer { bits: 32 },
                TypeKind::Integer { bits: 64 },
            ],
            false,
        );
        let h2 = FunctionMerger::compute_signature_hash(
            &TypeKind::Integer { bits: 32 },
            &[
                TypeKind::Integer { bits: 32 },
                TypeKind::Integer { bits: 64 },
            ],
            false,
        );
        assert_eq!(h1, h2);
    }

    #[test]
    fn test_noreturn_detection() {
        assert!(FunctionClassifier::is_noreturn(true, false, false));
        assert!(!FunctionClassifier::is_noreturn(false, false, true));
    }

    #[test]
    fn test_willreturn_detection() {
        assert!(FunctionClassifier::is_willreturn(false, false, true));
        assert!(!FunctionClassifier::is_willreturn(true, false, true));
    }

    #[test]
    fn test_eh_personality() {
        assert_eq!(
            EHPersonality::from_name("__gxx_personality_v0"),
            EHPersonality::GnuCXX
        );
        assert!(EHPersonality::GnuCXX.is_gnu_style());
        assert!(!EHPersonality::WinCXX.is_gnu_style());
    }

    #[test]
    fn test_attribute_deduction_readnone() {
        let result = AttributeDeductionAnalyzer::analyze(
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            &[],
        );
        assert!(result.can_be_readnone);
        assert!(result.can_be_nounwind);
    }

    #[test]
    fn test_attribute_deduction_with_loads() {
        let result = AttributeDeductionAnalyzer::analyze(
            true,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            &[],
        );
        assert!(!result.can_be_readnone);
    }

    #[test]
    fn test_function_summary() {
        let summary =
            FunctionSummary::new("test".to_string(), Linkage::External, Visibility::Default);
        assert_eq!(summary.name, "test");
        assert!(summary.is_live());
    }

    #[test]
    fn test_specialization() {
        let mut spec = FunctionSpecializer::new();
        spec.analyze_argument_constancy("foo", &[Some(42), None], 80, 100);
        assert!(!spec.candidates.is_empty());
        assert!(spec.is_profitable(&spec.candidates[0], 0.5));
    }
}