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
// instruction_v2.rs — World-Class Instruction System Extension
//
// Clean-room forensic-parity expansion:
//   - Instruction subclasses with full specialisation
//   - PHINode with incoming value management and critical edge handling
//   - CallInst with operand bundles, deoptimization bundles, convergent flags
//   - LoadInst/StoreInst with atomic ordering, volatile, alignment
//   - AllocaInst with alignment and address space
//   - GetElementPtrInst with inbounds flag and source element type
//   - CmpInst with predicate enumeration and swap
//   - CastInst with all cast opcodes
//   - BinaryOperator with fast-math flags
//   - UnaryOperator
//   - InsertValueInst / ExtractValueInst
//   - ShuffleVectorInst / InsertElementInst / ExtractElementInst
//   - SwitchInst with case management
//   - IndirectBrInst with destination management
//   - InvokeInst / CallBrInst / CatchSwitchInst / CatchRetInst / ResumeInst
//   - LandingPadInst with clause management
//   - AtomicRMW / AtomicCmpXchg
//   - FenceInst
//   - FreezeInst
//   - VAArgInst

use llvm_native_core::types::Type;
use llvm_native_core::value::ValueRef;
use std::fmt;
use std::rc::Rc;

// ============================================================================
// Section 1: Atomic Ordering
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum AtomicOrdering {
    NotAtomic = 0,
    Unordered = 1,
    Monotonic = 2,
    Acquire = 3,
    Release = 4,
    AcquireRelease = 5,
    SequentiallyConsistent = 6,
}

impl AtomicOrdering {
    pub fn is_at_least(&self, other: AtomicOrdering) -> bool {
        (*self as u32) >= (other as u32)
    }
    pub fn is_stronger_than(&self, other: AtomicOrdering) -> bool {
        (*self as u32) > (other as u32)
    }
    pub fn is_at_least_acquire(&self) -> bool {
        self.is_at_least(AtomicOrdering::Acquire)
    }
    pub fn is_at_least_release(&self) -> bool {
        self.is_at_least(AtomicOrdering::Release)
    }
}

impl fmt::Display for AtomicOrdering {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AtomicOrdering::NotAtomic => write!(f, "not_atomic"),
            AtomicOrdering::Unordered => write!(f, "unordered"),
            AtomicOrdering::Monotonic => write!(f, "monotonic"),
            AtomicOrdering::Acquire => write!(f, "acquire"),
            AtomicOrdering::Release => write!(f, "release"),
            AtomicOrdering::AcquireRelease => write!(f, "acq_rel"),
            AtomicOrdering::SequentiallyConsistent => write!(f, "seq_cst"),
        }
    }
}

// ============================================================================
// Section 2: Fast Math Flags
// ============================================================================

#[derive(Debug, Clone, Copy, Default)]
pub struct FastMathFlags {
    pub no_nans: bool,
    pub no_infs: bool,
    pub no_signed_zeros: bool,
    pub allow_reciprocal: bool,
    pub allow_contract: bool,
    pub allow_reassociation: bool,
    pub approx_func: bool,
}

impl FastMathFlags {
    pub fn all() -> Self {
        FastMathFlags {
            no_nans: true,
            no_infs: true,
            no_signed_zeros: true,
            allow_reciprocal: true,
            allow_contract: true,
            allow_reassociation: true,
            approx_func: true,
        }
    }
    pub fn is_any_set(&self) -> bool {
        self.no_nans
            || self.no_infs
            || self.no_signed_zeros
            || self.allow_reciprocal
            || self.allow_contract
            || self.allow_reassociation
            || self.approx_func
    }
}

// ============================================================================
// Section 3: Operand Bundles
// ============================================================================

/// Operand bundle for call/invoke (deoptimization, funclet, etc.)
#[derive(Debug, Clone)]
pub struct OperandBundle {
    pub tag: String,
    pub inputs: Vec<ValueRef>,
}

impl OperandBundle {
    pub fn new(tag: String, inputs: Vec<ValueRef>) -> Self {
        OperandBundle { tag, inputs }
    }
}

/// Collection of operand bundles on a call site
#[derive(Debug, Clone, Default)]
pub struct OperandBundleSet {
    pub bundles: Vec<OperandBundle>,
}

impl OperandBundleSet {
    pub fn empty() -> Self {
        OperandBundleSet {
            bundles: Vec::new(),
        }
    }
    pub fn has_inputs(&self) -> bool {
        !self.bundles.is_empty()
    }
}

// ============================================================================
// Section 4: Alloca Instruction
// ============================================================================

#[derive(Debug, Clone)]
pub struct AllocaInfo {
    pub allocated_type: Type,
    pub num_elements: u64,
    pub alignment: u32,
    pub addr_space: u32,
    pub is_array_allocation: bool,
}

// ============================================================================
// Section 5: Load/Store Instructions
// ============================================================================

#[derive(Debug, Clone)]
pub struct LoadInfo {
    pub pointer_operand: ValueRef,
    pub is_volatile: bool,
    pub alignment: u32,
    pub ordering: AtomicOrdering,
    pub is_atomic: bool,
}

#[derive(Debug, Clone)]
pub struct StoreInfo {
    pub value_operand: ValueRef,
    pub pointer_operand: ValueRef,
    pub is_volatile: bool,
    pub alignment: u32,
    pub ordering: AtomicOrdering,
    pub is_atomic: bool,
}

// ============================================================================
// Section 6: GEP Instruction
// ============================================================================

#[derive(Debug, Clone)]
pub struct GEPInfo {
    pub pointer_operand: ValueRef,
    pub indices: Vec<ValueRef>,
    pub source_element_type: Type,
    pub is_inbounds: bool,
    pub in_range_index: Option<u32>,
}

// ============================================================================
// Section 7: PHI Node
// ============================================================================

#[derive(Debug, Clone)]
pub struct PHIInfo {
    pub incoming_values: Vec<(ValueRef, String)>, // (value, block_name)
    pub num_incoming: usize,
}

impl PHIInfo {
    pub fn new() -> Self {
        PHIInfo {
            incoming_values: Vec::new(),
            num_incoming: 0,
        }
    }
    pub fn add_incoming(&mut self, value: ValueRef, block: String) {
        self.incoming_values.push((value, block));
        self.num_incoming = self.incoming_values.len();
    }
    pub fn remove_incoming_value(&mut self, block: &str) -> bool {
        if let Some(pos) = self.incoming_values.iter().position(|(_, b)| b == block) {
            self.incoming_values.remove(pos);
            self.num_incoming = self.incoming_values.len();
            return true;
        }
        false
    }
    pub fn get_incoming_value_for_block(&self, block: &str) -> Option<&ValueRef> {
        self.incoming_values
            .iter()
            .find(|(_, b)| b == block)
            .map(|(v, _)| v)
    }
    pub fn has_constant_or_undef_value(&self) -> bool {
        false // Placeholder — would need constant analysis
    }
}

// ============================================================================
// Section 8: Call Instruction
// ============================================================================

#[derive(Debug, Clone)]
pub struct CallInfo {
    pub callee: ValueRef,
    pub arguments: Vec<ValueRef>,
    pub is_tail_call: bool,
    pub is_musttail: bool,
    pub is_notail: bool,
    pub calling_conv: u32,
    pub operand_bundles: OperandBundleSet,
    pub is_convergent: bool,
}

// ============================================================================
// Section 9: Switch Instruction
// ============================================================================

#[derive(Debug, Clone)]
pub struct SwitchInfo {
    pub condition: ValueRef,
    pub default_dest: String,
    pub cases: Vec<(ValueRef, String)>, // (value, destination block)
}

impl SwitchInfo {
    pub fn num_cases(&self) -> usize {
        self.cases.len()
    }
    pub fn find_case_value(&self, value: &ValueRef) -> Option<&String> {
        self.cases
            .iter()
            .find(|(v, _)| std::ptr::eq(Rc::as_ptr(v), Rc::as_ptr(value)))
            .map(|(_, d)| d)
    }
    pub fn add_case(&mut self, value: ValueRef, dest: String) {
        self.cases.push((value, dest));
    }
    pub fn remove_case(&mut self, value: &ValueRef) -> bool {
        if let Some(pos) = self
            .cases
            .iter()
            .position(|(v, _)| std::ptr::eq(Rc::as_ptr(v), Rc::as_ptr(value)))
        {
            self.cases.remove(pos);
            return true;
        }
        false
    }
}

// ============================================================================
// Section 10: Invoke Instruction
// ============================================================================

#[derive(Debug, Clone)]
pub struct InvokeInfo {
    pub callee: ValueRef,
    pub arguments: Vec<ValueRef>,
    pub normal_dest: String,
    pub unwind_dest: String,
    pub operand_bundles: OperandBundleSet,
    pub calling_conv: u32,
}

// ============================================================================
// Section 11: LandingPad Instruction
// ============================================================================

#[derive(Debug, Clone)]
pub struct LandingPadInfo {
    pub result_type: Type,
    pub personality_fn: Option<ValueRef>,
    pub is_cleanup: bool,
    pub clauses: Vec<LandingPadClause>,
}

#[derive(Debug, Clone)]
pub enum LandingPadClause {
    Catch(ValueRef),
    Filter(Vec<ValueRef>),
}

// ============================================================================
// Section 12: Atomic Operations
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AtomicRMWBinOp {
    Xchg,
    Add,
    Sub,
    And,
    Nand,
    Or,
    Xor,
    Max,
    Min,
    UMax,
    UMin,
    FAdd,
    FSub,
    FMax,
    FMin,
    UIncWrap,
    UDecWrap,
}

#[derive(Debug, Clone)]
pub struct AtomicRMWInfo {
    pub pointer: ValueRef,
    pub value: ValueRef,
    pub operation: AtomicRMWBinOp,
    pub ordering: AtomicOrdering,
    pub is_volatile: bool,
}

#[derive(Debug, Clone)]
pub struct AtomicCmpXchgInfo {
    pub pointer: ValueRef,
    pub compare_value: ValueRef,
    pub new_value: ValueRef,
    pub success_ordering: AtomicOrdering,
    pub failure_ordering: AtomicOrdering,
    pub is_weak: bool,
    pub is_volatile: bool,
}

// ============================================================================
// Section 13: Fence Instruction
// ============================================================================

#[derive(Debug, Clone)]
pub struct FenceInfo {
    pub ordering: AtomicOrdering,
    pub scope: SyncScope,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncScope {
    SingleThread,
    System,
}

// ============================================================================
// Section 14: CatchSwitch/CatchRet/CleanupRet
// ============================================================================

#[derive(Debug, Clone)]
pub struct CatchSwitchInfo {
    pub parent_pad: Option<ValueRef>,
    pub unwind_dest: Option<String>,
    pub handlers: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct CatchRetInfo {
    pub catch_pad: ValueRef,
    pub successor: String,
}

#[derive(Debug, Clone)]
pub struct CleanupRetInfo {
    pub cleanup_pad: ValueRef,
    pub unwind_dest: Option<String>,
}

#[derive(Debug, Clone)]
pub struct CleanupPadInfo {
    pub parent_pad: Option<ValueRef>,
    pub args: Vec<ValueRef>,
}

#[derive(Debug, Clone)]
pub struct CatchPadInfo {
    pub catch_switch: ValueRef,
    pub args: Vec<ValueRef>,
}

// ============================================================================
// Section 15: Freeze and Other Intrinsics as Instructions
// ============================================================================

#[derive(Debug, Clone)]
pub struct FreezeInfo {
    pub operand: ValueRef,
}

#[derive(Debug, Clone)]
pub struct VAArgInfo {
    pub va_list: ValueRef,
    pub result_type: Type,
}

// ============================================================================
// Section 16: CmpInst Predicates
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum CmpPredicate {
    // Integer predicates
    ICMP_EQ = 32,
    ICMP_NE = 33,
    ICMP_UGT = 34,
    ICMP_UGE = 35,
    ICMP_ULT = 36,
    ICMP_ULE = 37,
    ICMP_SGT = 38,
    ICMP_SGE = 39,
    ICMP_SLT = 40,
    ICMP_SLE = 41,
    // Float predicates
    FCMP_FALSE = 0,
    FCMP_OEQ = 1,
    FCMP_OGT = 2,
    FCMP_OGE = 3,
    FCMP_OLT = 4,
    FCMP_OLE = 5,
    FCMP_ONE = 6,
    FCMP_ORD = 7,
    FCMP_UNO = 8,
    FCMP_UEQ = 9,
    FCMP_UGT = 10,
    FCMP_UGE = 11,
    FCMP_ULT = 12,
    FCMP_ULE = 13,
    FCMP_UNE = 14,
    FCMP_TRUE = 15,
}

impl CmpPredicate {
    pub fn is_int_predicate(&self) -> bool {
        (*self as u32) >= 32 && (*self as u32) <= 41
    }
    pub fn is_fp_predicate(&self) -> bool {
        (*self as u32) <= 15
    }
    pub fn get_swapped_predicate(&self) -> CmpPredicate {
        match self {
            CmpPredicate::ICMP_UGT => CmpPredicate::ICMP_ULT,
            CmpPredicate::ICMP_UGE => CmpPredicate::ICMP_ULE,
            CmpPredicate::ICMP_ULT => CmpPredicate::ICMP_UGT,
            CmpPredicate::ICMP_ULE => CmpPredicate::ICMP_UGE,
            CmpPredicate::ICMP_SGT => CmpPredicate::ICMP_SLT,
            CmpPredicate::ICMP_SGE => CmpPredicate::ICMP_SLE,
            CmpPredicate::ICMP_SLT => CmpPredicate::ICMP_SGT,
            CmpPredicate::ICMP_SLE => CmpPredicate::ICMP_SGE,
            CmpPredicate::FCMP_OGT => CmpPredicate::FCMP_OLT,
            CmpPredicate::FCMP_OGE => CmpPredicate::FCMP_OLE,
            CmpPredicate::FCMP_OLT => CmpPredicate::FCMP_OGT,
            CmpPredicate::FCMP_OLE => CmpPredicate::FCMP_OGE,
            CmpPredicate::FCMP_UGT => CmpPredicate::FCMP_ULT,
            CmpPredicate::FCMP_UGE => CmpPredicate::FCMP_ULE,
            CmpPredicate::FCMP_ULT => CmpPredicate::FCMP_UGT,
            CmpPredicate::FCMP_ULE => CmpPredicate::FCMP_UGE,
            other => *other,
        }
    }
    pub fn is_equality(&self) -> bool {
        matches!(
            self,
            CmpPredicate::ICMP_EQ
                | CmpPredicate::ICMP_NE
                | CmpPredicate::FCMP_OEQ
                | CmpPredicate::FCMP_UEQ
                | CmpPredicate::FCMP_ONE
                | CmpPredicate::FCMP_UNE
        )
    }
}

impl fmt::Display for CmpPredicate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CmpPredicate::ICMP_EQ => write!(f, "eq"),
            CmpPredicate::ICMP_NE => write!(f, "ne"),
            CmpPredicate::ICMP_UGT => write!(f, "ugt"),
            CmpPredicate::ICMP_UGE => write!(f, "uge"),
            CmpPredicate::ICMP_ULT => write!(f, "ult"),
            CmpPredicate::ICMP_ULE => write!(f, "ule"),
            CmpPredicate::ICMP_SGT => write!(f, "sgt"),
            CmpPredicate::ICMP_SGE => write!(f, "sge"),
            CmpPredicate::ICMP_SLT => write!(f, "slt"),
            CmpPredicate::ICMP_SLE => write!(f, "sle"),
            CmpPredicate::FCMP_OEQ => write!(f, "oeq"),
            CmpPredicate::FCMP_ONE => write!(f, "one"),
            CmpPredicate::FCMP_OGT => write!(f, "ogt"),
            CmpPredicate::FCMP_OGE => write!(f, "oge"),
            CmpPredicate::FCMP_OLT => write!(f, "olt"),
            CmpPredicate::FCMP_OLE => write!(f, "ole"),
            CmpPredicate::FCMP_ORD => write!(f, "ord"),
            CmpPredicate::FCMP_UNO => write!(f, "uno"),
            _ => write!(f, "unknown_pred"),
        }
    }
}

// ============================================================================
// Section 17: Instruction Flag / Metadata Utilities
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstructionFlag {
    NoUnsignedWrap,
    NoSignedWrap,
    Exact,
    Disjoint,
    NonNeg,
}

// ============================================================================
// Section 18: Tests
// ============================================================================

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

    #[test]
    fn test_atomic_ordering_compare() {
        assert!(AtomicOrdering::SequentiallyConsistent.is_stronger_than(AtomicOrdering::Acquire));
        assert!(AtomicOrdering::Acquire.is_at_least_acquire());
        assert!(!AtomicOrdering::Release.is_at_least_acquire());
    }

    #[test]
    fn test_phi_node() {
        let mut phi = PHIInfo::new();
        phi.add_incoming(ValueRef::default(), "entry".to_string());
        phi.add_incoming(ValueRef::default(), "loop".to_string());
        assert_eq!(phi.num_incoming, 2);
        phi.remove_incoming_value("entry");
        assert_eq!(phi.num_incoming, 1);
    }

    #[test]
    fn test_switch_info() {
        let mut sw = SwitchInfo {
            condition: ValueRef::default(),
            default_dest: "default".to_string(),
            cases: Vec::new(),
        };
        sw.add_case(ValueRef::default(), "case1".to_string());
        assert_eq!(sw.num_cases(), 1);
    }

    #[test]
    fn test_cmp_predicate_swap() {
        assert_eq!(
            CmpPredicate::ICMP_UGT.get_swapped_predicate(),
            CmpPredicate::ICMP_ULT
        );
        assert_eq!(
            CmpPredicate::FCMP_OGT.get_swapped_predicate(),
            CmpPredicate::FCMP_OLT
        );
        assert_eq!(
            CmpPredicate::ICMP_EQ.get_swapped_predicate(),
            CmpPredicate::ICMP_EQ
        );
    }

    #[test]
    fn test_cmp_is_equality() {
        assert!(CmpPredicate::ICMP_EQ.is_equality());
        assert!(CmpPredicate::ICMP_NE.is_equality());
        assert!(!CmpPredicate::ICMP_UGT.is_equality());
    }

    #[test]
    fn test_fast_math_flags() {
        let flags = FastMathFlags::all();
        assert!(flags.is_any_set());
        assert!(flags.no_nans);
    }
}