llvm-bitcode 0.4.0

LLVM Bitcode parser in Rust
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
use crate::bits::Cursor;
use crate::bitstream::{Abbreviation, Operand, PayloadOperand, ScalarOperand};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::num::NonZero;
use std::ops::Range;
use std::sync::Arc;

use crate::read::{BitStreamReader, Error};
use crate::visitor::{BitStreamVisitor, CollectingVisitor};

const LLVM_BITCODE_WRAPPER_MAGIC: u32 = 0x0B17C0DE;

/// Represents the contents of a file encoded using the
/// [LLVM bitstream container format](https://llvm.org/docs/BitCodeFormat.html#bitstream-container-format)
#[derive(Debug, Clone)]
pub struct Bitcode {
    pub signature: Signature,
    pub elements: Vec<BitcodeElement>,
    pub block_info: HashMap<u32, BlockInfo>,
}

/// Blocks in a bitstream denote nested regions of the stream,
/// and are identified by a content-specific id number
///
/// Block IDs 0-7 are reserved for [standard blocks](https://llvm.org/docs/BitCodeFormat.html#standard-blocks)
/// whose meaning is defined by Bitcode;
/// block IDs 8 and greater are application specific.
#[derive(Debug, Clone)]
pub struct Block {
    /// Block ID
    pub id: u32,
    /// Block elements
    pub elements: Vec<BitcodeElement>,
}

#[derive(Debug, Clone)]
pub enum Payload {
    Array(Vec<u64>),
    Char6String(String),
    Blob(Vec<u8>),
}

/// Data records consist of a record code and a number of (up to) 64-bit integer values
///
/// The interpretation of the code and values is application specific and may vary between different block types.
#[derive(Debug, Clone)]
pub struct Record {
    /// Record code
    pub id: u64,
    /// An abbreviated record has a abbreviation id followed by a set of fields
    fields: Vec<u64>,
    /// Array and Blob encoding has payload
    payload: Option<Payload>,
}

impl Record {
    #[must_use]
    pub fn fields(&self) -> &[u64] {
        &self.fields
    }

    pub fn take_payload(&mut self) -> Option<Payload> {
        self.payload.take()
    }
}

#[derive(Debug, Clone)]
enum Ops {
    Abbrev {
        /// If under `abbrev.fields.len()`, then it's the next op to read
        /// If equals `abbrev.fields.len()`, then payload is next
        /// If greater than `abbrev.fields.len()`, then payload has been read
        state: usize,
        abbrev: Arc<Abbreviation>,
    },
    /// Num ops left
    Full(usize),
}

/// Data records consist of a record code and a number of (up to) 64-bit integer values
///
/// The interpretation of the code and values is application specific and may vary between different block types.
pub struct RecordIter<'cursor, 'input> {
    /// Record code
    pub id: u64,
    cursor: &'cursor mut Cursor<'input>,
    ops: Ops,
}

impl<'cursor, 'input> RecordIter<'cursor, 'input> {
    pub(crate) fn into_record(mut self) -> Result<Record, Error> {
        let mut fields = Vec::with_capacity(self.len());
        while let Some(f) = self.try_next()? {
            fields.push(f);
        }
        Ok(Record {
            id: self.id,
            fields,
            payload: self.payload().ok().flatten(),
        })
    }

    fn read_scalar_operand(cursor: &mut Cursor<'_>, operand: ScalarOperand) -> Result<u64, Error> {
        match operand {
            ScalarOperand::Char6 => {
                let value = cursor.read(6)? as u8;
                Ok(u64::from(match value {
                    0..=25 => value + b'a',
                    26..=51 => value + (b'A' - 26),
                    52..=61 => value - (52 - b'0'),
                    62 => b'.',
                    63 => b'_',
                    _ => return Err(Error::InvalidAbbrev),
                }))
            }
            ScalarOperand::Literal(value) => Ok(value),
            ScalarOperand::Fixed(width) => Ok(cursor.read(width)?),
            ScalarOperand::Vbr(width) => Ok(cursor.read_vbr(width)?),
        }
    }

    pub(crate) fn from_cursor_abbrev(
        cursor: &'cursor mut Cursor<'input>,
        abbrev: Arc<Abbreviation>,
    ) -> Result<Self, Error> {
        let id =
            Self::read_scalar_operand(cursor, *abbrev.fields.first().ok_or(Error::InvalidAbbrev)?)?;
        Ok(Self {
            id,
            cursor,
            ops: Ops::Abbrev { state: 1, abbrev },
        })
    }

    pub(crate) fn from_cursor(cursor: &'cursor mut Cursor<'input>) -> Result<Self, Error> {
        let id = cursor.read_vbr_fixed::<6>()?;
        let num_ops = cursor.read_vbr_fixed::<6>()? as usize;
        Ok(Self {
            id,
            cursor,
            ops: Ops::Full(num_ops),
        })
    }

    pub fn payload(&mut self) -> Result<Option<Payload>, Error> {
        match &mut self.ops {
            Ops::Abbrev { state, abbrev } => {
                if *state > abbrev.fields.len() {
                    return Ok(None);
                }
                Ok(match abbrev.payload {
                    Some(PayloadOperand::Blob) => Some(Payload::Blob(self.blob()?.to_vec())),
                    Some(PayloadOperand::Array(ScalarOperand::Char6)) => {
                        Some(Payload::Char6String(
                            String::from_utf8(self.string()?).map_err(|_| Error::InvalidAbbrev)?,
                        ))
                    }
                    Some(PayloadOperand::Array(_)) => Some(Payload::Array(self.array()?)),
                    None => None,
                })
            }
            Ops::Full(_) => Ok(None),
        }
    }

    /// Number of unread fields, excludes string/array/blob payload
    #[must_use]
    pub fn len(&self) -> usize {
        match &self.ops {
            Ops::Abbrev { state, abbrev } => abbrev.fields.len().saturating_sub(*state),
            Ops::Full(num_ops) => *num_ops,
        }
    }

    /// Matches len, excludes string/array/blob payload
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[doc(hidden)]
    #[deprecated(note = "renamed to `try_next()` to avoid confusion with `Iterator::next`")]
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> Result<Option<u64>, Error> {
        self.try_next()
    }

    /// Consume next record
    #[doc(alias = "next")]
    pub fn try_next(&mut self) -> Result<Option<u64>, Error> {
        match &mut self.ops {
            Ops::Abbrev { state, abbrev } => {
                let Some(&op) = abbrev.fields.get(*state) else {
                    return Ok(None);
                };
                *state += 1;
                Ok(Some(Self::read_scalar_operand(self.cursor, op)?))
            }
            Ops::Full(num_ops) => {
                if *num_ops == 0 {
                    return Ok(None);
                }
                *num_ops -= 1;
                Ok(Some(self.cursor.read_vbr_fixed::<6>()?))
            }
        }
    }

    #[cfg_attr(debug_assertions, track_caller)]
    pub fn u64(&mut self) -> Result<u64, Error> {
        match self.try_next()? {
            Some(v) => Ok(v),
            None => {
                debug_assert!(false, "unexpected end of record");
                Err(Error::EndOfRecord)
            }
        }
    }

    pub fn nzu64(&mut self) -> Result<Option<NonZero<u64>>, Error> {
        self.u64().map(NonZero::new)
    }

    pub fn i64(&mut self) -> Result<i64, Error> {
        let v = self.u64()?;
        let shifted = (v >> 1) as i64;
        Ok(if (v & 1) == 0 {
            shifted
        } else if v != 1 {
            -shifted
        } else {
            1 << 63
        })
    }

    #[cfg_attr(debug_assertions, track_caller)]
    pub fn u16(&mut self) -> Result<u16, Error> {
        let val = self.u64()?;
        match val.try_into() {
            Ok(v) => Ok(v),
            Err(_) => {
                debug_assert!(false, "{val} overflows u16");
                Err(Error::ValueOverflow)
            }
        }
    }

    #[cfg_attr(debug_assertions, track_caller)]
    pub fn u32(&mut self) -> Result<u32, Error> {
        let val = self.u64()?;
        match val.try_into() {
            Ok(v) => Ok(v),
            Err(_) => {
                debug_assert!(false, "{val} overflows u32");
                Err(Error::ValueOverflow)
            }
        }
    }

    pub fn nzu32(&mut self) -> Result<Option<NonZero<u32>>, Error> {
        self.u32().map(NonZero::new)
    }

    #[cfg_attr(debug_assertions, track_caller)]
    pub fn u8(&mut self) -> Result<u8, Error> {
        let val = self.u64()?;
        match val.try_into() {
            Ok(v) => Ok(v),
            Err(_) => {
                debug_assert!(false, "{val} overflows u8");
                Err(Error::ValueOverflow)
            }
        }
    }

    #[cfg_attr(debug_assertions, track_caller)]
    #[inline]
    pub fn try_from<U: TryFrom<u64>, T: TryFrom<U>>(&mut self) -> Result<T, Error> {
        self.try_next_from::<U, T>()?.ok_or(Error::EndOfRecord)
    }

    #[cfg_attr(debug_assertions, track_caller)]
    pub fn try_next_from<U: TryFrom<u64>, T: TryFrom<U>>(&mut self) -> Result<Option<T>, Error> {
        match self.try_next()? {
            Some(val) => {
                if let Some(val) = val.try_into().ok().and_then(|v| T::try_from(v).ok()) {
                    Ok(Some(val))
                } else {
                    debug_assert!(
                        false,
                        "{} can't be made from {val} as {}",
                        std::any::type_name::<T>(),
                        std::any::type_name::<U>()
                    );
                    Err(Error::ValueOverflow)
                }
            }
            None => Ok(None),
        }
    }

    pub fn nzu8(&mut self) -> Result<Option<NonZero<u8>>, Error> {
        self.u8().map(NonZero::new)
    }

    #[cfg_attr(debug_assertions, track_caller)]
    pub fn bool(&mut self) -> Result<bool, Error> {
        match self.u64()? {
            0 => Ok(false),
            1 => Ok(true),
            val => {
                debug_assert!(false, "{val} overflows bool");
                Err(Error::ValueOverflow)
            }
        }
    }

    /// Reads `start` and `len` into Rust's `start..end`
    pub fn range(&mut self) -> Result<Range<usize>, Error> {
        let start = self.u64()? as usize;
        Ok(Range {
            start,
            end: start
                .checked_add(self.u64()? as usize)
                .ok_or(Error::ValueOverflow)?,
        })
    }

    pub fn blob(&mut self) -> Result<&'input [u8], Error> {
        match &mut self.ops {
            Ops::Abbrev { state, abbrev } => match Self::take_payload_operand(state, abbrev)? {
                Some(PayloadOperand::Blob) => {
                    let length = self.cursor.read_vbr_fixed::<6>()? as usize;
                    self.cursor.align32()?;
                    let data = self.cursor.read_bytes(length)?;
                    self.cursor.align32()?;
                    Ok(data)
                }
                other => Err(Error::UnexpectedOperand(other.map(Operand::Payload))),
            },
            Ops::Full(_) => Err(Error::UnexpectedOperand(None)),
        }
    }

    pub fn array(&mut self) -> Result<Vec<u64>, Error> {
        match &mut self.ops {
            Ops::Abbrev { state, abbrev } => match Self::take_payload_operand(state, abbrev)? {
                Some(PayloadOperand::Array(op)) => {
                    let len = self.cursor.read_vbr_fixed::<6>()? as usize;
                    let mut out = Vec::with_capacity(len);
                    for _ in 0..len {
                        if out.len() == out.capacity() {
                            debug_assert!(false);
                            break;
                        }
                        out.push(Self::read_scalar_operand(self.cursor, op)?);
                    }
                    Ok(out)
                }
                other => Err(Error::UnexpectedOperand(other.map(Operand::Payload))),
            },
            // Not a proper array payload, but this fallback pattern is used by LLVM
            Ops::Full(num_ops) => {
                let len = *num_ops;
                *num_ops = 0;
                let mut out = Vec::with_capacity(len);
                for _ in 0..len {
                    if out.len() == out.capacity() {
                        debug_assert!(false);
                        break;
                    }
                    out.push(self.cursor.read_vbr_fixed::<6>()?);
                }
                Ok(out)
            }
        }
    }

    /// Mark payload as read, if there is one
    fn take_payload_operand(
        state: &mut usize,
        abbrev: &Abbreviation,
    ) -> Result<Option<PayloadOperand>, Error> {
        if *state == abbrev.fields.len() {
            if abbrev.payload.is_some() {
                *state += 1;
            }
            Ok(abbrev.payload)
        } else {
            Err(Error::UnexpectedOperand(
                abbrev.fields.get(*state).copied().map(Operand::Scalar),
            ))
        }
    }

    /// Read remainder of the fields as string chars.
    ///
    /// Interpret data as UTF-8.
    /// The string may contain NUL terminator, depending on context.
    pub fn string_utf8(&mut self) -> Result<String, Error> {
        String::from_utf8(self.string()?).map_err(Error::Encoding)
    }

    /// Read remainder of the fields as string chars
    ///
    /// The strings are just binary blobs. LLVM doesn't guarantee any encoding.
    /// The string may contain NUL terminator, depending on context.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn string(&mut self) -> Result<Vec<u8>, Error> {
        match &mut self.ops {
            Ops::Abbrev { state, abbrev } => match Self::take_payload_operand(state, abbrev)? {
                Some(PayloadOperand::Array(el)) => {
                    *state += 1;
                    let len = self.cursor.read_vbr_fixed::<6>()? as usize;
                    let mut out = Vec::with_capacity(len);

                    match el {
                        ScalarOperand::Char6 => {
                            for _ in 0..len {
                                if out.len() == out.capacity() {
                                    debug_assert!(false);
                                    break;
                                }
                                let ch = match self.cursor.read(6)? as u8 {
                                    value @ 0..=25 => value + b'a',
                                    value @ 26..=51 => value + (b'A' - 26),
                                    value @ 52..=61 => value - (52 - b'0'),
                                    62 => b'.',
                                    63 => b'_',
                                    _ => return Err(Error::InvalidAbbrev),
                                };
                                out.push(ch);
                            }
                        }
                        ScalarOperand::Fixed(width @ 6..=8) => {
                            for _ in 0..len {
                                if out.len() == out.capacity() {
                                    debug_assert!(false);
                                    break;
                                }
                                out.push(self.cursor.read(width)? as u8);
                            }
                        }
                        other => {
                            return Err(Error::UnexpectedOperand(Some(Operand::Scalar(other))));
                        }
                    }
                    Ok(out)
                }
                other => Err(Error::UnexpectedOperand(other.map(Operand::Payload))),
            },
            Ops::Full(num_ops) => {
                let len = std::mem::replace(num_ops, 0);
                let mut out = Vec::with_capacity(len);
                for _ in 0..len {
                    let ch = self.cursor.read_vbr_fixed::<6>()?;
                    out.push(match u8::try_from(ch) {
                        Ok(c) => c,
                        Err(_) => {
                            debug_assert!(false, "{ch} too big for char");
                            return Err(Error::ValueOverflow);
                        }
                    });
                }
                Ok(out)
            }
        }
    }

    /// Zero-terminated string, assumes latin1 encoding
    pub fn zstring(&mut self) -> Result<String, Error> {
        let mut s = String::new();
        while let Some(b) = self.nzu8()? {
            s.push(b.get() as char);
        }
        Ok(s)
    }

    /// Internal ID of this record's abbreviation, if any.
    ///
    /// This is intended only for debugging and data dumps.
    /// This isn't a stable identifier, and may be block-specific.
    #[must_use]
    pub fn debug_abbrev_id(&self) -> Option<u32> {
        match &self.ops {
            Ops::Abbrev { abbrev, .. } => Some(abbrev.id),
            Ops::Full(_) => None,
        }
    }

    /// For debug printing
    fn with_cloned_cursor<'new_cursor>(
        &self,
        cursor: &'new_cursor mut Cursor<'input>,
    ) -> RecordIter<'new_cursor, 'input> {
        RecordIter {
            id: self.id,
            ops: self.ops.clone(),
            cursor,
        }
    }
}

impl Iterator for RecordIter<'_, '_> {
    type Item = Result<u64, Error>;
    fn next(&mut self) -> Option<Self::Item> {
        self.try_next().transpose()
    }
}

impl Drop for RecordIter<'_, '_> {
    /// Must drain the remaining records to advance the cursor to the next record
    fn drop(&mut self) {
        while let Ok(Some(_)) = self.try_next() {}
        if let Ops::Abbrev { abbrev, .. } = &self.ops
            && abbrev.payload.is_some()
        {
            let _ = self.payload();
        }
    }
}

struct RecordIterDebugFields<'c, 'i>(RefCell<RecordIter<'c, 'i>>);
struct RecordIterDebugResult<T, E>(Result<T, E>);

impl fmt::Debug for RecordIter<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut c = self.cursor.clone();
        let fields = RecordIterDebugFields(RefCell::new(self.with_cloned_cursor(&mut c)));

        f.debug_struct("RecordIter")
            .field("id", &self.id)
            .field("fields", &fields)
            .field("ops", &self.ops)
            .field("cursor", &self.cursor)
            .finish()
    }
}

impl fmt::Debug for RecordIterDebugFields<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut iter = self.0.borrow_mut();
        let mut d = f.debug_list();
        d.entries(iter.by_ref().map(RecordIterDebugResult));
        if let Some(p) = iter.payload().transpose() {
            d.entries([RecordIterDebugResult(p)]);
        }
        d.finish()
    }
}

impl<T: fmt::Debug, E: fmt::Debug> fmt::Debug for RecordIterDebugResult<T, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            Ok(t) => t.fmt(f),
            Err(e) => e.fmt(f),
        }
    }
}

/// Bitcode element
#[derive(Debug, Clone)]
pub enum BitcodeElement {
    /// Block
    Block(Block),
    /// Data record
    Record(Record),
}

impl BitcodeElement {
    /// Returns true if it is a `Block`
    #[must_use]
    pub fn is_block(&self) -> bool {
        matches!(self, Self::Block(_))
    }

    /// If it is a `Block`, returns the associated block. Returns `None` otherwise.
    #[must_use]
    pub fn as_block(&self) -> Option<&Block> {
        match self {
            Self::Block(block) => Some(block),
            Self::Record(_) => None,
        }
    }

    /// If it is a `Block`, returns the associated mutable block. Returns `None` otherwise.
    pub fn as_block_mut(&mut self) -> Option<&mut Block> {
        match self {
            Self::Block(block) => Some(block),
            Self::Record(_) => None,
        }
    }

    /// Returns true if it is a `Record`
    #[must_use]
    pub fn is_record(&self) -> bool {
        matches!(self, Self::Record(_))
    }

    /// If it is a `Record`, returns the associated record. Returns `None` otherwise.
    #[must_use]
    pub fn as_record(&self) -> Option<&Record> {
        match self {
            Self::Block(_) => None,
            Self::Record(record) => Some(record),
        }
    }

    /// If it is a `Record`, returns the associated mutable record. Returns `None` otherwise.
    pub fn as_record_mut(&mut self) -> Option<&mut Record> {
        match self {
            Self::Block(_) => None,
            Self::Record(record) => Some(record),
        }
    }
}

/// Block information
#[derive(Debug, Clone, Default)]
pub struct BlockInfo {
    /// Block name
    pub name: String,
    /// Data record names
    pub record_names: HashMap<u64, String>,
}

/// aka. Magic number
#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq)]
pub struct Signature {
    pub magic: u32,
    pub magic2: u32,
    pub version: u32,
    pub offset: u32,
    pub size: u32,
    pub cpu_type: u32,
}

impl Signature {
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<(Self, &[u8])> {
        let (signature, remaining_data) = data.split_first_chunk::<4>()?;
        let magic = u32::from_le_bytes(*signature);
        if magic != LLVM_BITCODE_WRAPPER_MAGIC {
            Some((
                Self {
                    version: 0,
                    magic,
                    magic2: 0,
                    offset: 4,
                    size: remaining_data.len() as _,
                    cpu_type: 0,
                },
                remaining_data,
            ))
        } else {
            // It is a LLVM Bitcode wrapper, remove wrapper header
            if data.len() < 20 {
                return None;
            }
            let mut words = data
                .chunks_exact(4)
                .skip(1)
                .map(|w| u32::from_le_bytes(w.try_into().unwrap()));
            let version = words.next()?;
            let offset = words.next()?;
            let size = words.next()?;
            let cpu_id = words.next()?;
            let data = data.get(offset as usize..offset as usize + size as usize)?;
            let (magic2, remaining_data) = data.split_first_chunk::<4>()?;
            let magic2 = u32::from_le_bytes(*magic2);
            Some((
                Self {
                    version,
                    magic,
                    magic2,
                    offset,
                    size,
                    cpu_type: cpu_id,
                },
                remaining_data,
            ))
        }
    }
}

impl Bitcode {
    /// Parse bitcode from bytes
    ///
    /// Accepts both LLVM bitcode and bitcode wrapper formats
    pub fn new(data: &[u8]) -> Result<Self, Error> {
        let (signature, stream) = Signature::parse(data).ok_or(Error::InvalidSignature(0))?;
        let mut reader = BitStreamReader::new();
        let mut visitor = CollectingVisitor::new();
        reader.read_block(
            Cursor::new(stream),
            BitStreamReader::TOP_LEVEL_BLOCK_ID,
            2,
            &mut visitor,
        )?;
        Ok(Self {
            signature,
            elements: visitor.finalize_top_level_elements(),
            block_info: reader.block_info,
        })
    }

    /// Read bitcode from bytes with a visitor
    ///
    /// Accepts both LLVM bitcode and bitcode wrapper formats
    pub fn read<V>(data: &[u8], visitor: &mut V) -> Result<(), Error>
    where
        V: BitStreamVisitor,
    {
        let (header, stream) = Signature::parse(data).ok_or(Error::InvalidSignature(0))?;
        if !visitor.validate(header) {
            return Err(Error::InvalidSignature(header.magic));
        }
        let mut reader = BitStreamReader::new();
        reader.read_block(
            Cursor::new(stream),
            BitStreamReader::TOP_LEVEL_BLOCK_ID,
            2,
            visitor,
        )
    }
}