llvm-in-rust-bitcode 0.1.0

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

use crate::error::BitcodeError;
use llvm_ir::value::Argument;
use llvm_ir::{
    ArgId, BasicBlock, BlockId, ConstId, ConstantData, Context, FastMathFlags, FloatKind,
    FloatPredicate, Function, GlobalId, InstrId, InstrKind, Instruction, IntArithFlags,
    IntPredicate, Linkage, Module, TailCallKind, TypeData, TypeId, ValueRef,
};

/// Magic bytes for the LRIR format.
const MAGIC: &[u8; 4] = b"LRIR";

/// Parse a LRIR binary blob and reconstruct `(Context, Module)`.
pub fn read_bitcode(bytes: &[u8]) -> Result<(Context, Module), BitcodeError> {
    let mut r = Reader::new(bytes);

    // ── header ────────────────────────────────────────────────────────────
    let magic = r.read_bytes(4)?;
    if magic != MAGIC {
        return Err(BitcodeError::InvalidMagic);
    }
    let version = r.u32()?;
    if version != 1 {
        return Err(BitcodeError::ParseError(format!(
            "unsupported version {}",
            version
        )));
    }

    // ── type table ────────────────────────────────────────────────────────
    let mut ctx = Context::new();
    let type_count = r.u32()? as usize;
    // We'll collect the types as raw TypeData first; the Context will
    // intern them in order.  We need a mapping from serialized TypeId → interned TypeId.
    let mut type_id_map: Vec<TypeId> = Vec::with_capacity(type_count);

    for _ in 0..type_count {
        let td = decode_type(&mut r, &type_id_map)?;
        // Intern the type and record the mapping.
        let interned = intern_type(&mut ctx, td);
        type_id_map.push(interned);
    }

    // ── constant table ─────────────────────────────────────────────────────
    let const_count = r.u32()? as usize;
    let mut const_id_map: Vec<ConstId> = Vec::with_capacity(const_count);

    for _ in 0..const_count {
        let cd = decode_const(&mut r, &type_id_map, &const_id_map)?;
        let cid = ctx.push_const(cd);
        const_id_map.push(cid);
    }

    // ── module header ──────────────────────────────────────────────────────
    let module_name = r.string()?;
    let mut module = Module::new(module_name);

    // ── functions ──────────────────────────────────────────────────────────
    let func_count = r.u32()? as usize;
    for _ in 0..func_count {
        let func = decode_function(&mut r, &type_id_map, &const_id_map)?;
        module.add_function(func);
    }

    Ok((ctx, module))
}

// ── type decoding ──────────────────────────────────────────────────────────

mod type_tag {
    /// Public API for `VOID`.
    pub const VOID: u8 = 0;
    /// Public API for `INTEGER`.
    pub const INTEGER: u8 = 1;
    /// Public API for `FLOAT`.
    pub const FLOAT: u8 = 2;
    /// Public API for `POINTER`.
    pub const POINTER: u8 = 3;
    /// Public API for `ARRAY`.
    pub const ARRAY: u8 = 4;
    /// Public API for `VECTOR`.
    pub const VECTOR: u8 = 5;
    /// Public API for `STRUCT`.
    pub const STRUCT: u8 = 6;
    /// Public API for `FUNCTION`.
    pub const FUNCTION: u8 = 7;
    /// Public API for `LABEL`.
    pub const LABEL: u8 = 8;
    /// Public API for `METADATA`.
    pub const METADATA: u8 = 9;
}

mod float_tag {
    /// Public API for `HALF`.
    pub const HALF: u8 = 0;
    /// Public API for `BFLOAT`.
    pub const BFLOAT: u8 = 1;
    /// Public API for `SINGLE`.
    pub const SINGLE: u8 = 2;
    /// Public API for `DOUBLE`.
    pub const DOUBLE: u8 = 3;
    /// Public API for `FP128`.
    pub const FP128: u8 = 4;
    /// Public API for `X86FP80`.
    pub const X86FP80: u8 = 5;
}

/// Decode a TypeData from the stream, resolving type IDs via `type_id_map`.
fn decode_type(r: &mut Reader, type_id_map: &[TypeId]) -> Result<TypeData, BitcodeError> {
    let tag = r.u8()?;
    match tag {
        type_tag::VOID => Ok(TypeData::Void),
        type_tag::INTEGER => {
            let bits = r.u32()?;
            Ok(TypeData::Integer(bits))
        }
        type_tag::FLOAT => {
            let ftag = r.u8()?;
            let kind = match ftag {
                float_tag::HALF => FloatKind::Half,
                float_tag::BFLOAT => FloatKind::BFloat,
                float_tag::SINGLE => FloatKind::Single,
                float_tag::DOUBLE => FloatKind::Double,
                float_tag::FP128 => FloatKind::Fp128,
                float_tag::X86FP80 => FloatKind::X86Fp80,
                _ => return Err(BitcodeError::InvalidType),
            };
            Ok(TypeData::Float(kind))
        }
        type_tag::POINTER => Ok(TypeData::Pointer),
        type_tag::ARRAY => {
            let elem_raw = r.u32()? as usize;
            let len = r.u64()?;
            let element = map_type_id(type_id_map, elem_raw)?;
            Ok(TypeData::Array { element, len })
        }
        type_tag::VECTOR => {
            let elem_raw = r.u32()? as usize;
            let len = r.u32()?;
            let scalable = r.u8()? != 0;
            let element = map_type_id(type_id_map, elem_raw)?;
            Ok(TypeData::Vector {
                element,
                len,
                scalable,
            })
        }
        type_tag::STRUCT => {
            let name = r.opt_string()?;
            let packed = r.u8()? != 0;
            let field_count = r.u32()? as usize;
            let mut fields = Vec::with_capacity(field_count);
            for _ in 0..field_count {
                let fid_raw = r.u32()? as usize;
                fields.push(map_type_id(type_id_map, fid_raw)?);
            }
            Ok(TypeData::Struct(llvm_ir::StructType {
                name,
                fields,
                packed,
            }))
        }
        type_tag::FUNCTION => {
            let ret_raw = r.u32()? as usize;
            let variadic = r.u8()? != 0;
            let param_count = r.u32()? as usize;
            let mut params = Vec::with_capacity(param_count);
            for _ in 0..param_count {
                let pid_raw = r.u32()? as usize;
                params.push(map_type_id(type_id_map, pid_raw)?);
            }
            let ret = map_type_id(type_id_map, ret_raw)?;
            Ok(TypeData::Function(llvm_ir::FunctionType {
                ret,
                params,
                variadic,
            }))
        }
        type_tag::LABEL => Ok(TypeData::Label),
        type_tag::METADATA => Ok(TypeData::Metadata),
        _ => Err(BitcodeError::InvalidType),
    }
}

fn map_type_id(type_id_map: &[TypeId], raw: usize) -> Result<TypeId, BitcodeError> {
    type_id_map.get(raw).copied().ok_or_else(|| {
        BitcodeError::ParseError(format!(
            "type id {} out of range (table size {})",
            raw,
            type_id_map.len()
        ))
    })
}

fn map_const_id(const_id_map: &[ConstId], raw: usize) -> Result<ConstId, BitcodeError> {
    const_id_map
        .get(raw)
        .copied()
        .ok_or_else(|| BitcodeError::ParseError(format!("const id {} out of range", raw)))
}

/// Intern a TypeData into the Context and return the TypeId.
fn intern_type(ctx: &mut Context, td: TypeData) -> TypeId {
    match td {
        TypeData::Void => ctx.void_ty,
        TypeData::Integer(b) => ctx.mk_int(b),
        TypeData::Float(k) => ctx.mk_float(k),
        TypeData::Pointer => ctx.mk_ptr(),
        TypeData::Label => ctx.mk_label(),
        TypeData::Metadata => ctx.mk_metadata(),
        TypeData::Array { element, len } => ctx.mk_array(element, len),
        TypeData::Vector {
            element,
            len,
            scalable,
        } => ctx.mk_vector(element, len, scalable),
        TypeData::Struct(st) => {
            if let Some(ref name) = st.name {
                let id = ctx.mk_struct_named(name.clone());
                ctx.define_struct_body(id, st.fields, st.packed);
                id
            } else {
                ctx.mk_struct_anon(st.fields, st.packed)
            }
        }
        TypeData::Function(ft) => ctx.mk_fn_type(ft.ret, ft.params, ft.variadic),
    }
}

// ── constant decoding ─────────────────────────────────────────────────────

mod const_tag {
    /// Public API for `INT`.
    pub const INT: u8 = 0;
    /// Public API for `INT_WIDE`.
    pub const INT_WIDE: u8 = 1;
    /// Public API for `FLOAT`.
    pub const FLOAT: u8 = 2;
    /// Public API for `NULL`.
    pub const NULL: u8 = 3;
    /// Public API for `UNDEF`.
    pub const UNDEF: u8 = 4;
    /// Public API for `POISON`.
    pub const POISON: u8 = 5;
    /// Public API for `ZERO_INIT`.
    pub const ZERO_INIT: u8 = 6;
    /// Public API for `ARRAY`.
    pub const ARRAY: u8 = 7;
    /// Public API for `STRUCT`.
    pub const STRUCT: u8 = 8;
    /// Public API for `VECTOR`.
    pub const VECTOR: u8 = 9;
    /// Public API for `GLOBAL_REF`.
    pub const GLOBAL_REF: u8 = 10;
}

fn decode_const(
    r: &mut Reader,
    type_id_map: &[TypeId],
    const_id_map: &[ConstId],
) -> Result<ConstantData, BitcodeError> {
    let tag = r.u8()?;
    match tag {
        const_tag::INT => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let val = r.u64()?;
            Ok(ConstantData::Int { ty, val })
        }
        const_tag::INT_WIDE => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let word_count = r.u32()? as usize;
            let mut words = Vec::with_capacity(word_count);
            for _ in 0..word_count {
                words.push(r.u64()?);
            }
            Ok(ConstantData::IntWide { ty, words })
        }
        const_tag::FLOAT => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let bits = r.u64()?;
            Ok(ConstantData::Float { ty, bits })
        }
        const_tag::NULL => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            Ok(ConstantData::Null(ty))
        }
        const_tag::UNDEF => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            Ok(ConstantData::Undef(ty))
        }
        const_tag::POISON => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            Ok(ConstantData::Poison(ty))
        }
        const_tag::ZERO_INIT => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            Ok(ConstantData::ZeroInitializer(ty))
        }
        const_tag::ARRAY => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let n = r.u32()? as usize;
            let mut elems = Vec::with_capacity(n);
            for _ in 0..n {
                elems.push(map_const_id(const_id_map, r.u32()? as usize)?);
            }
            Ok(ConstantData::Array {
                ty,
                elements: elems,
            })
        }
        const_tag::STRUCT => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let n = r.u32()? as usize;
            let mut fields = Vec::with_capacity(n);
            for _ in 0..n {
                fields.push(map_const_id(const_id_map, r.u32()? as usize)?);
            }
            Ok(ConstantData::Struct { ty, fields })
        }
        const_tag::VECTOR => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let n = r.u32()? as usize;
            let mut elems = Vec::with_capacity(n);
            for _ in 0..n {
                elems.push(map_const_id(const_id_map, r.u32()? as usize)?);
            }
            Ok(ConstantData::Vector {
                ty,
                elements: elems,
            })
        }
        const_tag::GLOBAL_REF => {
            let ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let id_raw = r.u32()?;
            let name = r.string()?;
            Ok(ConstantData::GlobalRef {
                ty,
                id: GlobalId(id_raw),
                name,
            })
        }
        other => Err(BitcodeError::UnsupportedRecord(other as u32)),
    }
}

// ── function decoding ─────────────────────────────────────────────────────

mod linkage_tag {
    /// Public API for `PRIVATE`.
    pub const PRIVATE: u8 = 0;
    /// Public API for `INTERNAL`.
    pub const INTERNAL: u8 = 1;
    /// Public API for `EXTERNAL`.
    pub const EXTERNAL: u8 = 2;
    /// Public API for `WEAK`.
    pub const WEAK: u8 = 3;
    /// Public API for `WEAK_ODR`.
    pub const WEAK_ODR: u8 = 4;
    /// Public API for `LINK_ONCE`.
    pub const LINK_ONCE: u8 = 5;
    /// Public API for `LINK_ONCE_ODR`.
    pub const LINK_ONCE_ODR: u8 = 6;
    /// Public API for `COMMON`.
    pub const COMMON: u8 = 7;
    /// Public API for `AVAILABLE_EXTERNALLY`.
    pub const AVAILABLE_EXTERNALLY: u8 = 8;
}

fn decode_linkage(tag: u8) -> Result<Linkage, BitcodeError> {
    match tag {
        linkage_tag::PRIVATE => Ok(Linkage::Private),
        linkage_tag::INTERNAL => Ok(Linkage::Internal),
        linkage_tag::EXTERNAL => Ok(Linkage::External),
        linkage_tag::WEAK => Ok(Linkage::Weak),
        linkage_tag::WEAK_ODR => Ok(Linkage::WeakOdr),
        linkage_tag::LINK_ONCE => Ok(Linkage::LinkOnce),
        linkage_tag::LINK_ONCE_ODR => Ok(Linkage::LinkOnceOdr),
        linkage_tag::COMMON => Ok(Linkage::Common),
        linkage_tag::AVAILABLE_EXTERNALLY => Ok(Linkage::AvailableExternally),
        other => Err(BitcodeError::UnsupportedRecord(other as u32)),
    }
}

fn decode_function(
    r: &mut Reader,
    type_id_map: &[TypeId],
    const_id_map: &[ConstId],
) -> Result<Function, BitcodeError> {
    let name = r.string()?;
    let ty_raw = r.u32()? as usize;
    let ty = map_type_id(type_id_map, ty_raw)?;
    let linkage = decode_linkage(r.u8()?)?;
    let is_declaration = r.u8()? != 0;

    // Arguments.
    let arg_count = r.u32()? as usize;
    let mut args = Vec::with_capacity(arg_count);
    for _ in 0..arg_count {
        let aname = r.string()?;
        let aty_raw = r.u32()? as usize;
        let aty = map_type_id(type_id_map, aty_raw)?;
        let index = r.u32()?;
        args.push(Argument {
            name: aname,
            ty: aty,
            index,
        });
    }

    let mut func = if is_declaration {
        Function::new_declaration(name, ty, args, linkage)
    } else {
        Function::new(name, ty, args, linkage)
    };
    func.is_declaration = is_declaration;

    // Read flat instruction pool first (needed for block body references).
    let block_count = r.u32()? as usize;
    // Save block records for later (after we read the instruction pool).
    let mut block_records: Vec<(String, Vec<u32>, u32)> = Vec::with_capacity(block_count);
    for _ in 0..block_count {
        let bname = r.string()?;
        let body_count = r.u32()? as usize;
        let mut body = Vec::with_capacity(body_count);
        for _ in 0..body_count {
            body.push(r.u32()?);
        }
        let term = r.u32()?;
        block_records.push((bname, body, term));
    }

    // Flat instruction pool.
    let instr_count = r.u32()? as usize;
    for _ in 0..instr_count {
        let instr = decode_instr(r, type_id_map, const_id_map)?;
        func.alloc_instr(instr);
    }

    // Reconstruct basic blocks.
    for (bname, body_ids, term_raw) in block_records {
        let mut bb = BasicBlock::new(bname);
        for id in body_ids {
            bb.body.push(InstrId(id));
        }
        bb.terminator = if term_raw == 0xFFFF_FFFF {
            None
        } else {
            Some(InstrId(term_raw))
        };
        func.blocks.push(bb);
    }

    Ok(func)
}

// ── instruction decoding ──────────────────────────────────────────────────

mod instr_tag {
    /// Public API for `ADD`.
    pub const ADD: u32 = 0;
    /// Public API for `SUB`.
    pub const SUB: u32 = 1;
    /// Public API for `MUL`.
    pub const MUL: u32 = 2;
    /// Public API for `UDIV`.
    pub const UDIV: u32 = 3;
    /// Public API for `SDIV`.
    pub const SDIV: u32 = 4;
    /// Public API for `UREM`.
    pub const UREM: u32 = 5;
    /// Public API for `SREM`.
    pub const SREM: u32 = 6;
    /// Public API for `AND`.
    pub const AND: u32 = 10;
    /// Public API for `OR`.
    pub const OR: u32 = 11;
    /// Public API for `XOR`.
    pub const XOR: u32 = 12;
    /// Public API for `SHL`.
    pub const SHL: u32 = 13;
    /// Public API for `LSHR`.
    pub const LSHR: u32 = 14;
    /// Public API for `ASHR`.
    pub const ASHR: u32 = 15;
    /// Public API for `FADD`.
    pub const FADD: u32 = 20;
    /// Public API for `FSUB`.
    pub const FSUB: u32 = 21;
    /// Public API for `FMUL`.
    pub const FMUL: u32 = 22;
    /// Public API for `FDIV`.
    pub const FDIV: u32 = 23;
    /// Public API for `FREM`.
    pub const FREM: u32 = 24;
    /// Public API for `FNEG`.
    pub const FNEG: u32 = 25;
    /// Public API for `ICMP`.
    pub const ICMP: u32 = 30;
    /// Public API for `FCMP`.
    pub const FCMP: u32 = 31;
    /// Public API for `ALLOCA`.
    pub const ALLOCA: u32 = 40;
    /// Public API for `LOAD`.
    pub const LOAD: u32 = 41;
    /// Public API for `STORE`.
    pub const STORE: u32 = 42;
    /// Public API for `GEP`.
    pub const GEP: u32 = 43;
    /// Public API for `TRUNC`.
    pub const TRUNC: u32 = 50;
    /// Public API for `ZEXT`.
    pub const ZEXT: u32 = 51;
    /// Public API for `SEXT`.
    pub const SEXT: u32 = 52;
    /// Public API for `FPTRUNC`.
    pub const FPTRUNC: u32 = 53;
    /// Public API for `FPEXT`.
    pub const FPEXT: u32 = 54;
    /// Public API for `FPTOUI`.
    pub const FPTOUI: u32 = 55;
    /// Public API for `FPTOSI`.
    pub const FPTOSI: u32 = 56;
    /// Public API for `UITOFP`.
    pub const UITOFP: u32 = 57;
    /// Public API for `SITOFP`.
    pub const SITOFP: u32 = 58;
    /// Public API for `PTRTOINT`.
    pub const PTRTOINT: u32 = 59;
    /// Public API for `INTTOPTR`.
    pub const INTTOPTR: u32 = 60;
    /// Public API for `BITCAST`.
    pub const BITCAST: u32 = 61;
    /// Public API for `ADDRSPACECAST`.
    pub const ADDRSPACECAST: u32 = 62;
    /// Public API for `FREEZE`.
    pub const FREEZE: u32 = 63;
    /// Public API for `SELECT`.
    pub const SELECT: u32 = 70;
    /// Public API for `PHI`.
    pub const PHI: u32 = 71;
    /// Public API for `EXTRACTVALUE`.
    pub const EXTRACTVALUE: u32 = 72;
    /// Public API for `INSERTVALUE`.
    pub const INSERTVALUE: u32 = 73;
    /// Public API for `EXTRACTELEM`.
    pub const EXTRACTELEM: u32 = 74;
    /// Public API for `INSERTELEM`.
    pub const INSERTELEM: u32 = 75;
    /// Public API for `SHUFFLEVEC`.
    pub const SHUFFLEVEC: u32 = 76;
    /// Public API for `CALL`.
    pub const CALL: u32 = 80;
    /// Public API for `RET`.
    pub const RET: u32 = 90;
    /// Public API for `BR`.
    pub const BR: u32 = 91;
    /// Public API for `CONDBR`.
    pub const CONDBR: u32 = 92;
    /// Public API for `SWITCH`.
    pub const SWITCH: u32 = 93;
    /// Public API for `UNREACHABLE`.
    pub const UNREACHABLE: u32 = 94;
}

fn decode_vref(r: &mut Reader) -> Result<ValueRef, BitcodeError> {
    let tag = r.u8()?;
    let id = r.u32()?;
    match tag {
        0 => Ok(ValueRef::Instruction(InstrId(id))),
        1 => Ok(ValueRef::Argument(ArgId(id))),
        2 => Ok(ValueRef::Constant(ConstId(id))),
        3 => Ok(ValueRef::Global(GlobalId(id))),
        other => Err(BitcodeError::UnsupportedRecord(other as u32)),
    }
}

fn decode_opt_vref(r: &mut Reader) -> Result<Option<ValueRef>, BitcodeError> {
    let present = r.u8()?;
    if present != 0 {
        Ok(Some(decode_vref(r)?))
    } else {
        Ok(None)
    }
}

fn decode_opt_u32(r: &mut Reader) -> Result<Option<u32>, BitcodeError> {
    let present = r.u8()?;
    if present != 0 {
        Ok(Some(r.u32()?))
    } else {
        Ok(None)
    }
}

fn decode_int_pred(tag: u8) -> Result<IntPredicate, BitcodeError> {
    match tag {
        0 => Ok(IntPredicate::Eq),
        1 => Ok(IntPredicate::Ne),
        2 => Ok(IntPredicate::Ugt),
        3 => Ok(IntPredicate::Uge),
        4 => Ok(IntPredicate::Ult),
        5 => Ok(IntPredicate::Ule),
        6 => Ok(IntPredicate::Sgt),
        7 => Ok(IntPredicate::Sge),
        8 => Ok(IntPredicate::Slt),
        9 => Ok(IntPredicate::Sle),
        other => Err(BitcodeError::UnsupportedRecord(other as u32)),
    }
}

fn decode_float_pred(tag: u8) -> Result<FloatPredicate, BitcodeError> {
    match tag {
        0 => Ok(FloatPredicate::False),
        1 => Ok(FloatPredicate::Oeq),
        2 => Ok(FloatPredicate::Ogt),
        3 => Ok(FloatPredicate::Oge),
        4 => Ok(FloatPredicate::Olt),
        5 => Ok(FloatPredicate::Ole),
        6 => Ok(FloatPredicate::One),
        7 => Ok(FloatPredicate::Ord),
        8 => Ok(FloatPredicate::Uno),
        9 => Ok(FloatPredicate::Ueq),
        10 => Ok(FloatPredicate::Ugt),
        11 => Ok(FloatPredicate::Uge),
        12 => Ok(FloatPredicate::Ult),
        13 => Ok(FloatPredicate::Ule),
        14 => Ok(FloatPredicate::Une),
        15 => Ok(FloatPredicate::True),
        other => Err(BitcodeError::UnsupportedRecord(other as u32)),
    }
}

fn decode_instr(
    r: &mut Reader,
    type_id_map: &[TypeId],
    _const_id_map: &[ConstId],
) -> Result<Instruction, BitcodeError> {
    // Name: 0-length = None.
    let name = r.opt_string()?;
    let ty_raw = r.u32()? as usize;
    let ty = map_type_id(type_id_map, ty_raw)?;
    let tag = r.u32()?;

    let kind = match tag {
        instr_tag::ADD => {
            let nuw = r.u8()? != 0;
            let nsw = r.u8()? != 0;
            let flags = IntArithFlags { nuw, nsw };
            InstrKind::Add {
                flags,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::SUB => {
            let nuw = r.u8()? != 0;
            let nsw = r.u8()? != 0;
            let flags = IntArithFlags { nuw, nsw };
            InstrKind::Sub {
                flags,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::MUL => {
            let nuw = r.u8()? != 0;
            let nsw = r.u8()? != 0;
            let flags = IntArithFlags { nuw, nsw };
            InstrKind::Mul {
                flags,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::UDIV => {
            let exact = r.u8()? != 0;
            InstrKind::UDiv {
                exact,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::SDIV => {
            let exact = r.u8()? != 0;
            InstrKind::SDiv {
                exact,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::UREM => InstrKind::URem {
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::SREM => InstrKind::SRem {
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::AND => InstrKind::And {
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::OR => InstrKind::Or {
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::XOR => InstrKind::Xor {
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::SHL => {
            let nuw = r.u8()? != 0;
            let nsw = r.u8()? != 0;
            let flags = IntArithFlags { nuw, nsw };
            InstrKind::Shl {
                flags,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::LSHR => {
            let exact = r.u8()? != 0;
            InstrKind::LShr {
                exact,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::ASHR => {
            let exact = r.u8()? != 0;
            InstrKind::AShr {
                exact,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::FADD => InstrKind::FAdd {
            flags: FastMathFlags::default(),
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::FSUB => InstrKind::FSub {
            flags: FastMathFlags::default(),
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::FMUL => InstrKind::FMul {
            flags: FastMathFlags::default(),
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::FDIV => InstrKind::FDiv {
            flags: FastMathFlags::default(),
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::FREM => InstrKind::FRem {
            flags: FastMathFlags::default(),
            lhs: decode_vref(r)?,
            rhs: decode_vref(r)?,
        },
        instr_tag::FNEG => InstrKind::FNeg {
            flags: FastMathFlags::default(),
            operand: decode_vref(r)?,
        },
        instr_tag::ICMP => {
            let pred = decode_int_pred(r.u8()?)?;
            InstrKind::ICmp {
                pred,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::FCMP => {
            let pred = decode_float_pred(r.u8()?)?;
            InstrKind::FCmp {
                flags: FastMathFlags::default(),
                pred,
                lhs: decode_vref(r)?,
                rhs: decode_vref(r)?,
            }
        }
        instr_tag::ALLOCA => {
            let alloc_ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let num_elements = decode_opt_vref(r)?;
            let align = decode_opt_u32(r)?;
            InstrKind::Alloca {
                alloc_ty,
                num_elements,
                align,
            }
        }
        instr_tag::LOAD => {
            let lty = map_type_id(type_id_map, r.u32()? as usize)?;
            let ptr = decode_vref(r)?;
            let align = decode_opt_u32(r)?;
            let volatile = r.u8()? != 0;
            InstrKind::Load {
                ty: lty,
                ptr,
                align,
                volatile,
            }
        }
        instr_tag::STORE => {
            let val = decode_vref(r)?;
            let ptr = decode_vref(r)?;
            let align = decode_opt_u32(r)?;
            let volatile = r.u8()? != 0;
            InstrKind::Store {
                val,
                ptr,
                align,
                volatile,
            }
        }
        instr_tag::GEP => {
            let inbounds = r.u8()? != 0;
            let base_ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let ptr = decode_vref(r)?;
            let idx_count = r.u32()? as usize;
            let mut indices = Vec::with_capacity(idx_count);
            for _ in 0..idx_count {
                indices.push(decode_vref(r)?);
            }
            InstrKind::GetElementPtr {
                inbounds,
                base_ty,
                ptr,
                indices,
            }
        }
        instr_tag::TRUNC => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::Trunc { val, to }
        }
        instr_tag::ZEXT => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::ZExt { val, to }
        }
        instr_tag::SEXT => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::SExt { val, to }
        }
        instr_tag::FPTRUNC => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::FPTrunc { val, to }
        }
        instr_tag::FPEXT => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::FPExt { val, to }
        }
        instr_tag::FPTOUI => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::FPToUI { val, to }
        }
        instr_tag::FPTOSI => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::FPToSI { val, to }
        }
        instr_tag::UITOFP => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::UIToFP { val, to }
        }
        instr_tag::SITOFP => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::SIToFP { val, to }
        }
        instr_tag::PTRTOINT => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::PtrToInt { val, to }
        }
        instr_tag::INTTOPTR => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::IntToPtr { val, to }
        }
        instr_tag::BITCAST => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::BitCast { val, to }
        }
        instr_tag::ADDRSPACECAST => {
            let val = decode_vref(r)?;
            let to = map_type_id(type_id_map, r.u32()? as usize)?;
            InstrKind::AddrSpaceCast { val, to }
        }
        instr_tag::FREEZE => InstrKind::Freeze {
            val: decode_vref(r)?,
        },
        instr_tag::SELECT => InstrKind::Select {
            cond: decode_vref(r)?,
            then_val: decode_vref(r)?,
            else_val: decode_vref(r)?,
        },
        instr_tag::PHI => {
            let phi_ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let in_count = r.u32()? as usize;
            let mut incoming = Vec::with_capacity(in_count);
            for _ in 0..in_count {
                let vr = decode_vref(r)?;
                let bid = BlockId(r.u32()?);
                incoming.push((vr, bid));
            }
            InstrKind::Phi {
                ty: phi_ty,
                incoming,
            }
        }
        instr_tag::EXTRACTVALUE => {
            let agg = decode_vref(r)?;
            let idx_count = r.u32()? as usize;
            let mut indices = Vec::with_capacity(idx_count);
            for _ in 0..idx_count {
                indices.push(r.u32()?);
            }
            InstrKind::ExtractValue {
                aggregate: agg,
                indices,
            }
        }
        instr_tag::INSERTVALUE => {
            let agg = decode_vref(r)?;
            let val = decode_vref(r)?;
            let idx_count = r.u32()? as usize;
            let mut indices = Vec::with_capacity(idx_count);
            for _ in 0..idx_count {
                indices.push(r.u32()?);
            }
            InstrKind::InsertValue {
                aggregate: agg,
                val,
                indices,
            }
        }
        instr_tag::EXTRACTELEM => InstrKind::ExtractElement {
            vec: decode_vref(r)?,
            idx: decode_vref(r)?,
        },
        instr_tag::INSERTELEM => InstrKind::InsertElement {
            vec: decode_vref(r)?,
            val: decode_vref(r)?,
            idx: decode_vref(r)?,
        },
        instr_tag::SHUFFLEVEC => {
            let v1 = decode_vref(r)?;
            let v2 = decode_vref(r)?;
            let n = r.u32()? as usize;
            let mut mask = Vec::with_capacity(n);
            for _ in 0..n {
                mask.push(r.i32()?);
            }
            InstrKind::ShuffleVector { v1, v2, mask }
        }
        instr_tag::CALL => {
            let tail_tag = r.u8()?;
            let tail = match tail_tag {
                0 => TailCallKind::None,
                1 => TailCallKind::Tail,
                2 => TailCallKind::MustTail,
                _ => TailCallKind::NoTail,
            };
            let callee_ty = map_type_id(type_id_map, r.u32()? as usize)?;
            let callee = decode_vref(r)?;
            let arg_count = r.u32()? as usize;
            let mut args = Vec::with_capacity(arg_count);
            for _ in 0..arg_count {
                args.push(decode_vref(r)?);
            }
            InstrKind::Call {
                tail,
                callee_ty,
                callee,
                args,
            }
        }
        instr_tag::RET => InstrKind::Ret {
            val: decode_opt_vref(r)?,
        },
        instr_tag::BR => InstrKind::Br {
            dest: BlockId(r.u32()?),
        },
        instr_tag::CONDBR => {
            let cond = decode_vref(r)?;
            let then_dest = BlockId(r.u32()?);
            let else_dest = BlockId(r.u32()?);
            InstrKind::CondBr {
                cond,
                then_dest,
                else_dest,
            }
        }
        instr_tag::SWITCH => {
            let val = decode_vref(r)?;
            let default = BlockId(r.u32()?);
            let case_count = r.u32()? as usize;
            let mut cases = Vec::with_capacity(case_count);
            for _ in 0..case_count {
                let cv = decode_vref(r)?;
                let bd = BlockId(r.u32()?);
                cases.push((cv, bd));
            }
            InstrKind::Switch {
                val,
                default,
                cases,
            }
        }
        instr_tag::UNREACHABLE => InstrKind::Unreachable,
        other => return Err(BitcodeError::UnsupportedRecord(other)),
    };

    Ok(Instruction::new(name, ty, kind))
}

// ── reader helper ─────────────────────────────────────────────────────────

struct Reader<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Reader { data, pos: 0 }
    }

    fn read_bytes(&mut self, n: usize) -> Result<&[u8], BitcodeError> {
        if self.pos + n > self.data.len() {
            return Err(BitcodeError::TruncatedInput);
        }
        let slice = &self.data[self.pos..self.pos + n];
        self.pos += n;
        Ok(slice)
    }

    fn u8(&mut self) -> Result<u8, BitcodeError> {
        let b = self.read_bytes(1)?;
        Ok(b[0])
    }

    fn u32(&mut self) -> Result<u32, BitcodeError> {
        let b = self.read_bytes(4)?;
        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
    }

    fn i32(&mut self) -> Result<i32, BitcodeError> {
        let b = self.read_bytes(4)?;
        Ok(i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
    }

    fn u64(&mut self) -> Result<u64, BitcodeError> {
        let b = self.read_bytes(8)?;
        Ok(u64::from_le_bytes([
            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
        ]))
    }

    /// Read a length-prefixed string (u32 len + UTF-8 bytes).
    /// Returns `None` if len == 0.
    fn opt_string(&mut self) -> Result<Option<String>, BitcodeError> {
        let len = self.u32()? as usize;
        if len == 0 {
            return Ok(None);
        }
        let bytes = self.read_bytes(len)?;
        String::from_utf8(bytes.to_vec())
            .map(Some)
            .map_err(|e| BitcodeError::ParseError(format!("invalid UTF-8: {}", e)))
    }

    /// Read a length-prefixed string.  Returns an empty `String` if len == 0.
    fn string(&mut self) -> Result<String, BitcodeError> {
        let len = self.u32()? as usize;
        if len == 0 {
            return Ok(String::new());
        }
        let bytes = self.read_bytes(len)?;
        String::from_utf8(bytes.to_vec())
            .map_err(|e| BitcodeError::ParseError(format!("invalid UTF-8: {}", e)))
    }
}