Skip to main content

rucc_ir/
module.rs

1//! The module: the target it is for, its functions, its globals, its aliases and its metadata.
2//!
3//! Design: `spec/08-ir.md` sections 8.1 and 8.8.
4//!
5//! A module is one translation unit, or after LTO the several that were linked into one. It
6//! owns the functions rather than pointing at them, so the whole of a compilation is one value
7//! that is dropped in one go, and a reference to anything in it is a four-byte index.
8//!
9//! # Globals are bytes, not values
10//!
11//! There are no aggregate types in the IR, so a global's initializer cannot be a typed
12//! constant the way it is in LLVM. It is a sized, aligned image described by a run of
13//! [`Datum`]s: zero bytes, literal bytes, a scalar of a given IR type, or the address of
14//! another symbol. That is what an object file wants anyway, it needs no type the type system
15//! does not have, and a large `static const` table costs one [`Datum`] rather than one per
16//! element.
17//!
18//! # What the module does not hold
19//!
20//! It does not hold an [`Interner`](rucc_base::Interner). Every name in here is a
21//! [`Symbol`], and resolving one back to text needs the interner it came from, which the
22//! printer takes as an argument the way `rucc_ast::print` does. A module that owned one could
23//! not be built from the same session as the AST it was lowered from.
24//!
25//! Function attributes are not here yet. They arrive with the printer, which is where their
26//! spelling has to be settled.
27
28use std::collections::HashMap;
29use std::fmt;
30use std::ops::{Index, IndexMut};
31
32use rucc_base::float::Format;
33use rucc_base::{Idx, IdxRange, Symbol};
34use rucc_target::{TargetInfo, Triple};
35
36use crate::func::Func;
37#[cfg(test)]
38use crate::inst::TbaaNode;
39use crate::inst::{Imm, Meta, MetaNode};
40use crate::ty::Type;
41
42/// A function in a module.
43pub type FuncId = Idx<Func>;
44
45/// A global variable in a module.
46pub type GlobalId = Idx<Global>;
47
48/// An alias in a module.
49pub type AliasId = Idx<Alias>;
50
51/// A run of [`Datum`]s in a module's data pool, which is what a global's initializer is.
52pub type DataList = IdxRange<Datum>;
53
54/// Marker for the byte pool, so that a range into it cannot be confused with any other range.
55#[derive(Debug)]
56pub struct Byte;
57
58/// A run of literal bytes in a module's byte pool.
59pub type ByteRange = IdxRange<Byte>;
60
61/// How a symbol is seen outside the object it is defined in.
62///
63/// The set is the one C needs and no more. C++ vague linkage and the ODR variants are not
64/// here because nothing produces them.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
66pub enum Linkage {
67    /// Defined here and visible to every other object. The default, and what a plain
68    /// definition at file scope gets.
69    #[default]
70    External,
71    /// Defined here and invisible outside it, which is what `static` at file scope means.
72    Internal,
73    /// Defined here, visible, and allowed to be replaced by a strong definition elsewhere.
74    /// `__attribute__((weak))`. A reference to one that nothing defines is a null address
75    /// rather than a link error.
76    Weak,
77    /// Defined here, visible, and allowed to be identical to a definition in another object,
78    /// with one of them kept and the rest discarded. What `extern inline` under the GNU
79    /// semantics and a compiler-generated helper get.
80    LinkOnce,
81    /// A tentative definition, which the linker merges with any other tentative definition of
82    /// the same name and any real definition. `int x;` at file scope under `-fcommon`.
83    Common,
84}
85
86impl Linkage {
87    /// The spelling in the textual form.
88    #[must_use]
89    pub const fn name(self) -> &'static str {
90        match self {
91            Self::External => "external",
92            Self::Internal => "internal",
93            Self::Weak => "weak",
94            Self::LinkOnce => "linkonce",
95            Self::Common => "common",
96        }
97    }
98
99    /// The linkage that spelling names.
100    #[must_use]
101    pub fn from_name(name: &str) -> Option<Self> {
102        Self::all().find(|linkage| linkage.name() == name)
103    }
104
105    /// Every linkage, in declaration order.
106    pub fn all() -> impl Iterator<Item = Self> {
107        [Self::External, Self::Internal, Self::Weak, Self::LinkOnce, Self::Common].into_iter()
108    }
109
110    /// Whether the symbol is invisible outside this object, so that a pass may rewrite every
111    /// use of it because it can see every use of it.
112    #[must_use]
113    pub const fn is_local(self) -> bool {
114        matches!(self, Self::Internal)
115    }
116
117    /// Whether the definition here may lose to one in another object at link time.
118    ///
119    /// The optimizer must not fold a use against the definition it can see when this is true,
120    /// because the definition that wins may be a different one.
121    #[must_use]
122    pub const fn may_be_replaced(self) -> bool {
123        matches!(self, Self::Weak | Self::LinkOnce | Self::Common)
124    }
125}
126
127/// What the dynamic linker is allowed to do with a symbol.
128///
129/// Orthogonal to [`Linkage`], which is about the static linker. A hidden symbol is still
130/// external as far as the object file is concerned; it just does not go in the dynamic symbol
131/// table, so nothing outside the shared object can interpose it.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
133pub enum Visibility {
134    /// Exported and interposable, which is what a symbol in a shared library gets unless
135    /// something says otherwise.
136    #[default]
137    Default,
138    /// Not in the dynamic symbol table at all. `__attribute__((visibility("hidden")))` and
139    /// `-fvisibility=hidden`.
140    Hidden,
141    /// In the dynamic symbol table, but a reference from inside this shared object always
142    /// binds to the definition inside it.
143    Protected,
144}
145
146impl Visibility {
147    /// The spelling in the textual form.
148    #[must_use]
149    pub const fn name(self) -> &'static str {
150        match self {
151            Self::Default => "default",
152            Self::Hidden => "hidden",
153            Self::Protected => "protected",
154        }
155    }
156
157    /// The visibility that spelling names.
158    #[must_use]
159    pub fn from_name(name: &str) -> Option<Self> {
160        Self::all().find(|visibility| visibility.name() == name)
161    }
162
163    /// Every visibility, in declaration order.
164    pub fn all() -> impl Iterator<Item = Self> {
165        [Self::Default, Self::Hidden, Self::Protected].into_iter()
166    }
167}
168
169/// How a thread-local variable is reached.
170///
171/// The models are ordered from the most general to the fastest, and a model may always be
172/// replaced by a more general one. The frontend picks from the storage class and the
173/// visibility, `-ftls-model=` overrides it, and the linker may relax a general one into a
174/// faster one when it turns out the definition is in the executable.
175#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
176pub enum TlsModel {
177    /// Works for any variable in any object, at the cost of a call to `__tls_get_addr`.
178    #[default]
179    GlobalDynamic,
180    /// One call to `__tls_get_addr` for several variables that are known to share a module.
181    LocalDynamic,
182    /// The offset is loaded from the GOT. Needs the variable to be in a module loaded at
183    /// program start rather than by `dlopen`.
184    InitialExec,
185    /// The offset is a link-time constant. Only for a variable in the executable itself.
186    LocalExec,
187}
188
189impl TlsModel {
190    /// The spelling in the textual form.
191    #[must_use]
192    pub const fn name(self) -> &'static str {
193        match self {
194            Self::GlobalDynamic => "global_dynamic",
195            Self::LocalDynamic => "local_dynamic",
196            Self::InitialExec => "initial_exec",
197            Self::LocalExec => "local_exec",
198        }
199    }
200
201    /// The model that spelling names.
202    #[must_use]
203    pub fn from_name(name: &str) -> Option<Self> {
204        Self::all().find(|model| model.name() == name)
205    }
206
207    /// Every model, from the most general to the fastest.
208    pub fn all() -> impl Iterator<Item = Self> {
209        [Self::GlobalDynamic, Self::LocalDynamic, Self::InitialExec, Self::LocalExec].into_iter()
210    }
211}
212
213/// One piece of a global's initial image.
214///
215/// Sixteen bytes, so an initializer built out of them is a flat array and a table of a
216/// million bytes is one of these rather than a million.
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum Datum {
219    /// That many zero bytes. What `.bss` is made of, and what the tail of a partly
220    /// initialized array is.
221    Zero(u64),
222    /// Those literal bytes, from the module's byte pool. String literals and anything the
223    /// frontend has already laid out.
224    Bytes(ByteRange),
225    /// One scalar of that IR type, from the module's immediate pool. An integer holds its
226    /// value and a float holds its bit pattern, both target-independently: which byte comes
227    /// first is decided by the datalayout when the object file is written, not here.
228    Scalar {
229        /// The type of the scalar, which gives its width.
230        ty: Type,
231        /// Its value, in the module's immediate pool.
232        value: Idx<Imm>,
233    },
234    /// The address of another symbol, from the module's relocation pool. `&x` in an
235    /// initializer, which the linker fills in.
236    Addr(Idx<Reloc>),
237}
238
239impl Datum {
240    /// How many bytes it contributes to the image.
241    ///
242    /// The module is an argument because three of the four kinds keep what they are made of in
243    /// one of its pools, and a datum on its own is four words that mean nothing without it.
244    #[must_use]
245    pub fn size(self, module: &Module) -> u64 {
246        match self {
247            Self::Zero(bytes) => bytes,
248            Self::Bytes(range) => range.len() as u64,
249            // Rounded up, so that an `i1` in an image is a byte and a `_BitInt(24)` is three.
250            Self::Scalar { ty, .. } => u64::from(ty.bits().div_ceil(8)) * u64::from(ty.lanes()),
251            Self::Addr(reloc) => u64::from(module[reloc].size),
252        }
253    }
254}
255
256/// The address of a symbol, written into a global's image by the linker.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub struct Reloc {
259    /// The symbol whose address this is.
260    pub symbol: Symbol,
261    /// What to add to that address. `&array[2]` is the address of `array` plus eight.
262    pub addend: i64,
263    /// How many bytes the address occupies, which is the pointer width except where a target
264    /// has a smaller relocation for it.
265    pub size: u32,
266}
267
268/// A global variable.
269///
270/// A size and an alignment and an image, which is what the object writer needs. `init` is
271/// `None` for a declaration of something defined in another object, which is the only thing
272/// that distinguishes the two.
273#[derive(Debug, Clone)]
274pub struct Global {
275    /// The name it is reached by.
276    pub name: Symbol,
277    /// Its size in bytes, which the image must add up to.
278    pub size: u64,
279    /// Its required alignment in bytes, always a power of two.
280    pub align: u32,
281    /// How the linker sees it.
282    pub linkage: Linkage,
283    /// How the dynamic linker sees it.
284    pub visibility: Visibility,
285    /// The model to reach it by if it is thread-local, and `None` if it is not.
286    pub tls: Option<TlsModel>,
287    /// Whether writing through a pointer to it is undefined, which is what puts it in
288    /// `.rodata` rather than `.data`.
289    pub constant: bool,
290    /// The section to put it in, from `__attribute__((section(...)))`, or `None` to let the
291    /// object writer choose from the other fields.
292    pub section: Option<Symbol>,
293    /// Its initial image, or `None` if it is only declared here.
294    pub init: Option<DataList>,
295}
296
297impl Global {
298    /// A definition-less global of that size and alignment, external and not thread-local.
299    #[must_use]
300    pub fn new(name: Symbol, size: u64, align: u32) -> Self {
301        Self {
302            name,
303            size,
304            align,
305            linkage: Linkage::External,
306            visibility: Visibility::Default,
307            tls: None,
308            constant: false,
309            section: None,
310            init: None,
311        }
312    }
313
314    /// Whether this only says the variable exists somewhere.
315    #[must_use]
316    pub fn is_declaration(&self) -> bool {
317        self.init.is_none()
318    }
319}
320
321/// What an alias resolves to at link time.
322#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
323pub enum AliasKind {
324    /// A second name for a symbol in this same object, resolved by the assembler.
325    /// `__attribute__((alias("real")))`.
326    #[default]
327    Alias,
328    /// A name resolved once at program start by calling a resolver function in this object,
329    /// which picks an implementation from what the processor turns out to support.
330    /// `__attribute__((ifunc("resolver")))`, which is how glibc dispatches `memcpy`.
331    IFunc,
332}
333
334impl AliasKind {
335    /// The spelling in the textual form.
336    #[must_use]
337    pub const fn name(self) -> &'static str {
338        match self {
339            Self::Alias => "alias",
340            Self::IFunc => "ifunc",
341        }
342    }
343
344    /// The kind that spelling names.
345    #[must_use]
346    pub fn from_name(name: &str) -> Option<Self> {
347        match name {
348            "alias" => Some(Self::Alias),
349            "ifunc" => Some(Self::IFunc),
350            _ => None,
351        }
352    }
353}
354
355/// A second name for something else.
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357pub struct Alias {
358    /// The name being defined.
359    pub name: Symbol,
360    /// What it resolves to: the aliased symbol, or for an ifunc the resolver to call.
361    pub target: Symbol,
362    /// Which of those two it is.
363    pub kind: AliasKind,
364    /// How the linker sees the new name.
365    pub linkage: Linkage,
366    /// How the dynamic linker sees the new name.
367    pub visibility: Visibility,
368}
369
370impl Alias {
371    /// An external alias of `target`.
372    #[must_use]
373    pub fn new(name: Symbol, target: Symbol) -> Self {
374        Self {
375            name,
376            target,
377            kind: AliasKind::Alias,
378            linkage: Linkage::External,
379            visibility: Visibility::Default,
380        }
381    }
382}
383
384/// What a name in a module refers to.
385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386pub enum SymbolRef {
387    /// A function, defined or declared.
388    Func(FuncId),
389    /// A global variable, defined or declared.
390    Global(GlobalId),
391    /// An alias or an ifunc.
392    Alias(AliasId),
393}
394
395/// The layout facts a printed module carries so it can be compiled without the command line
396/// that produced it.
397///
398/// A subset of the string LLVM writes, in the same syntax, because that syntax is what tools
399/// around the ecosystem already read. It says what the module was built assuming, and the
400/// verifier is what checks it against the target actually being compiled for: a module built
401/// for a 64-bit pointer cannot be finished for a 32-bit one, and finding that out here is
402/// better than finding it out as wrong output.
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404pub struct DataLayout {
405    /// Whether the low byte of a scalar is stored first.
406    pub little_endian: bool,
407    /// The width of a pointer in bits.
408    pub pointer_bits: u32,
409    /// The alignment of a pointer in bits.
410    pub pointer_align: u32,
411    /// The alignment of a 64-bit integer in bits, which is the one integer alignment that
412    /// varies across the targets anybody still builds for.
413    pub i64_align: u32,
414    /// The alignment of the x87 eighty bit format in bits, and `None` on a target that does
415    /// not have it.
416    pub f80_align: Option<u32>,
417    /// The alignment the stack is kept at in bits, which is 128 on every target here.
418    pub stack_align: u32,
419}
420
421impl DataLayout {
422    /// The layout of that target.
423    #[must_use]
424    pub fn for_target(target: &TargetInfo) -> Self {
425        Self {
426            little_endian: target.little_endian,
427            pointer_bits: target.pointer_width,
428            pointer_align: target.pointer_width,
429            // Every target here is one where a 64-bit integer is 64-bit aligned. The field
430            // exists because a 32-bit x86 target, if one is ever added, aligns it to 32 and
431            // that changes the layout of every struct with a `long long` in it.
432            i64_align: 64,
433            f80_align: match target.long_double_format {
434                Format::X87Extended => Some(128),
435                _ => None,
436            },
437            stack_align: 128,
438        }
439    }
440
441    /// The layout back from the string [`Display`](fmt::Display) wrote, or `None` if the
442    /// string is not one.
443    ///
444    /// The fields may come in any order, because a string written by hand will not have them
445    /// in ours. A string this crate printed round-trips byte for byte, which is what
446    /// `spec/03-architecture.md` asks of the textual form.
447    #[must_use]
448    pub fn parse(text: &str) -> Option<Self> {
449        let mut little_endian = None;
450        let mut pointer = None;
451        let mut i64_align = None;
452        let mut f80_align = None;
453        let mut stack_align = None;
454        for field in text.split('-') {
455            let seen = match field {
456                "e" => little_endian.replace(true).is_some(),
457                "E" => little_endian.replace(false).is_some(),
458                _ if field.starts_with("p:") => {
459                    let (bits, align) = field[2..].split_once(':')?;
460                    pointer.replace((number(bits)?, number(align)?)).is_some()
461                }
462                _ if field.starts_with("i64:") => i64_align.replace(number(&field[4..])?).is_some(),
463                _ if field.starts_with("f80:") => f80_align.replace(number(&field[4..])?).is_some(),
464                _ if field.starts_with('S') => stack_align.replace(number(&field[1..])?).is_some(),
465                _ => return None,
466            };
467            if seen {
468                return None;
469            }
470        }
471        let (pointer_bits, pointer_align) = pointer?;
472        Some(Self {
473            little_endian: little_endian?,
474            pointer_bits,
475            pointer_align,
476            i64_align: i64_align?,
477            f80_align,
478            stack_align: stack_align?,
479        })
480    }
481}
482
483impl fmt::Display for DataLayout {
484    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485        write!(f, "{}", if self.little_endian { "e" } else { "E" })?;
486        write!(f, "-p:{}:{}", self.pointer_bits, self.pointer_align)?;
487        write!(f, "-i64:{}", self.i64_align)?;
488        if let Some(align) = self.f80_align {
489            write!(f, "-f80:{align}")?;
490        }
491        write!(f, "-S{}", self.stack_align)
492    }
493}
494
495/// A number in the textual form: digits, no sign, and no leading zero.
496///
497/// `p:64:064` would otherwise parse and then print back as `p:64:64`, which breaks the
498/// round-trip for no benefit to anybody.
499fn number(text: &str) -> Option<u32> {
500    if text.is_empty() || (text.len() > 1 && text.starts_with('0')) {
501        return None;
502    }
503    if !text.bytes().all(|byte| byte.is_ascii_digit()) {
504        return None;
505    }
506    text.parse().ok()
507}
508
509/// One translation unit, or after LTO the several that were linked into one.
510#[derive(Debug)]
511pub struct Module {
512    /// What it is called, which is the source file name for a module from the frontend. It
513    /// appears in the textual form and in the debug info and nothing branches on it.
514    pub name: Symbol,
515    /// The target it is for.
516    pub triple: Triple,
517    /// The layout it was built assuming.
518    pub datalayout: DataLayout,
519
520    funcs: Vec<Func>,
521    globals: Vec<Global>,
522    aliases: Vec<Alias>,
523    metadata: Vec<MetaNode>,
524
525    data: Vec<Datum>,
526    bytes: Vec<u8>,
527    imms: Vec<Imm>,
528    relocs: Vec<Reloc>,
529
530    symbols: HashMap<Symbol, SymbolRef>,
531}
532
533impl Module {
534    /// An empty module for that target.
535    #[must_use]
536    pub fn new(name: Symbol, target: &TargetInfo) -> Self {
537        Self {
538            name,
539            triple: target.triple,
540            datalayout: DataLayout::for_target(target),
541            funcs: Vec::new(),
542            globals: Vec::new(),
543            aliases: Vec::new(),
544            metadata: Vec::new(),
545            data: Vec::new(),
546            bytes: Vec::new(),
547            imms: Vec::new(),
548            relocs: Vec::new(),
549            symbols: HashMap::new(),
550        }
551    }
552
553    // Symbols.
554
555    /// Adds a function, which is a declaration if it has no blocks.
556    ///
557    /// # Panics
558    ///
559    /// Panics if the module already has a symbol of that name. Merging a declaration with a
560    /// definition is the frontend's job and it has the declarations to do it with; by the time
561    /// something is in the IR a name means one thing.
562    pub fn add_func(&mut self, func: Func) -> FuncId {
563        let id = Idx::from_usize(self.funcs.len());
564        self.claim(func.name, SymbolRef::Func(id));
565        self.funcs.push(func);
566        id
567    }
568
569    /// Adds a global variable, which is a declaration if it has no image.
570    ///
571    /// # Panics
572    ///
573    /// Panics if the module already has a symbol of that name.
574    pub fn add_global(&mut self, global: Global) -> GlobalId {
575        let id = Idx::from_usize(self.globals.len());
576        self.claim(global.name, SymbolRef::Global(id));
577        self.globals.push(global);
578        id
579    }
580
581    /// Adds an alias.
582    ///
583    /// The target is not resolved here, and it need not be in this module: an alias of
584    /// something in another object is a thing people write.
585    ///
586    /// # Panics
587    ///
588    /// Panics if the module already has a symbol of that name.
589    pub fn add_alias(&mut self, alias: Alias) -> AliasId {
590        let id = Idx::from_usize(self.aliases.len());
591        self.claim(alias.name, SymbolRef::Alias(id));
592        self.aliases.push(alias);
593        id
594    }
595
596    /// What that name refers to, or `None` if this module does not define or declare it.
597    #[must_use]
598    pub fn lookup(&self, name: Symbol) -> Option<SymbolRef> {
599        self.symbols.get(&name).copied()
600    }
601
602    /// Every function, in the order they were added.
603    pub fn funcs(&self) -> impl Iterator<Item = FuncId> + use<> {
604        (0..self.funcs.len()).map(Idx::from_usize)
605    }
606
607    /// Every global variable, in the order they were added.
608    pub fn globals(&self) -> impl Iterator<Item = GlobalId> + use<> {
609        (0..self.globals.len()).map(Idx::from_usize)
610    }
611
612    /// Every alias, in the order they were added.
613    pub fn aliases(&self) -> impl Iterator<Item = AliasId> + use<> {
614        (0..self.aliases.len()).map(Idx::from_usize)
615    }
616
617    fn claim(&mut self, name: Symbol, what: SymbolRef) {
618        assert!(
619            self.symbols.insert(name, what).is_none(),
620            "a module cannot have two symbols with the same name"
621        );
622    }
623
624    // Metadata.
625
626    /// Adds a metadata node and gives back the reference an instruction holds.
627    ///
628    /// The nodes live here rather than in a function because a TBAA tree is shared by every
629    /// memory operation in the module and duplicating it per function would make two accesses
630    /// to the same type look unrelated.
631    pub fn add_meta(&mut self, node: MetaNode) -> Meta {
632        self.metadata.push(node);
633        Idx::from_usize(self.metadata.len() - 1)
634    }
635
636    /// Every metadata node, in the order they were added.
637    pub fn metadata(&self) -> impl Iterator<Item = Meta> + use<> {
638        (0..self.metadata.len()).map(Idx::from_usize)
639    }
640
641    // Pools.
642
643    /// Records a run of data and gives back the list a global holds.
644    pub fn push_data(&mut self, data: &[Datum]) -> DataList {
645        let start = self.data.len();
646        self.data.extend_from_slice(data);
647        DataList::new(Idx::from_usize(start), Idx::from_usize(self.data.len()))
648    }
649
650    /// Records literal bytes and gives back the range a [`Datum::Bytes`] holds.
651    pub fn push_bytes(&mut self, bytes: &[u8]) -> ByteRange {
652        let start = self.bytes.len();
653        self.bytes.extend_from_slice(bytes);
654        ByteRange::new(Idx::from_usize(start), Idx::from_usize(self.bytes.len()))
655    }
656
657    /// Records a scalar value and gives back the index a [`Datum::Scalar`] holds.
658    pub fn add_imm(&mut self, imm: Imm) -> Idx<Imm> {
659        self.imms.push(imm);
660        Idx::from_usize(self.imms.len() - 1)
661    }
662
663    /// Records a relocation and gives back the index a [`Datum::Addr`] holds.
664    pub fn add_reloc(&mut self, reloc: Reloc) -> Idx<Reloc> {
665        self.relocs.push(reloc);
666        Idx::from_usize(self.relocs.len() - 1)
667    }
668
669    /// How much is in it, for the `-fstats` output and for a test that wants to say a pass
670    /// deleted something without saying which.
671    #[must_use]
672    pub fn counts(&self) -> ModuleCounts {
673        ModuleCounts {
674            funcs: self.funcs.len(),
675            globals: self.globals.len(),
676            aliases: self.aliases.len(),
677            metadata: self.metadata.len(),
678            data_bytes: self.bytes.len(),
679        }
680    }
681}
682
683/// How much is in a module, from [`Module::counts`].
684#[derive(Debug, Clone, Copy, PartialEq, Eq)]
685pub struct ModuleCounts {
686    /// Functions, defined and declared.
687    pub funcs: usize,
688    /// Global variables, defined and declared.
689    pub globals: usize,
690    /// Aliases and ifuncs.
691    pub aliases: usize,
692    /// Metadata nodes.
693    pub metadata: usize,
694    /// Bytes in the byte pool, which is the bulk of what a module with large initializers
695    /// weighs.
696    pub data_bytes: usize,
697}
698
699impl Index<FuncId> for Module {
700    type Output = Func;
701
702    fn index(&self, id: FuncId) -> &Func {
703        &self.funcs[id.index()]
704    }
705}
706
707impl IndexMut<FuncId> for Module {
708    fn index_mut(&mut self, id: FuncId) -> &mut Func {
709        &mut self.funcs[id.index()]
710    }
711}
712
713impl Index<GlobalId> for Module {
714    type Output = Global;
715
716    fn index(&self, id: GlobalId) -> &Global {
717        &self.globals[id.index()]
718    }
719}
720
721impl IndexMut<GlobalId> for Module {
722    fn index_mut(&mut self, id: GlobalId) -> &mut Global {
723        &mut self.globals[id.index()]
724    }
725}
726
727impl Index<AliasId> for Module {
728    type Output = Alias;
729
730    fn index(&self, id: AliasId) -> &Alias {
731        &self.aliases[id.index()]
732    }
733}
734
735impl Index<Meta> for Module {
736    type Output = MetaNode;
737
738    fn index(&self, meta: Meta) -> &MetaNode {
739        &self.metadata[meta.index()]
740    }
741}
742
743impl Index<Idx<Imm>> for Module {
744    type Output = Imm;
745
746    fn index(&self, imm: Idx<Imm>) -> &Imm {
747        &self.imms[imm.index()]
748    }
749}
750
751impl Index<Idx<Reloc>> for Module {
752    type Output = Reloc;
753
754    fn index(&self, reloc: Idx<Reloc>) -> &Reloc {
755        &self.relocs[reloc.index()]
756    }
757}
758
759impl Index<DataList> for Module {
760    type Output = [Datum];
761
762    fn index(&self, list: DataList) -> &[Datum] {
763        &self.data[list.as_usize_range()]
764    }
765}
766
767impl Index<ByteRange> for Module {
768    type Output = [u8];
769
770    fn index(&self, range: ByteRange) -> &[u8] {
771        &self.bytes[range.as_usize_range()]
772    }
773}
774
775#[cfg(test)]
776mod tests {
777    use rucc_base::Interner;
778    use rucc_target::{Arch, Env, Os};
779
780    use super::*;
781    use crate::inst::Signature;
782
783    fn target(arch: Arch, os: Os, env: Env) -> TargetInfo {
784        TargetInfo::new(Triple::new(arch, os, env))
785    }
786
787    fn linux() -> TargetInfo {
788        target(Arch::X86_64, Os::Linux, Env::Gnu)
789    }
790
791    #[test]
792    fn a_datum_is_sixteen_bytes() {
793        // A global with a large initializer is a flat array of these, so this is the tripwire
794        // on somebody adding a field that doubles the weight of every one.
795        assert_eq!(size_of::<Datum>(), 16);
796    }
797
798    #[test]
799    fn the_layout_of_x86_64_linux_is_the_one_in_the_spec() {
800        let layout = DataLayout::for_target(&linux());
801        assert_eq!(layout.to_string(), "e-p:64:64-i64:64-f80:128-S128");
802    }
803
804    #[test]
805    fn only_x86_has_the_eighty_bit_format() {
806        assert_eq!(DataLayout::for_target(&linux()).f80_align, Some(128));
807        let arm = DataLayout::for_target(&target(Arch::Aarch64, Os::Linux, Env::Gnu));
808        assert_eq!(arm.f80_align, None);
809        assert_eq!(arm.to_string(), "e-p:64:64-i64:64-S128");
810    }
811
812    #[test]
813    fn a_layout_round_trips() {
814        for triple in [
815            Triple::new(Arch::X86_64, Os::Linux, Env::Gnu),
816            Triple::new(Arch::X86_64, Os::Darwin, Env::None),
817            Triple::new(Arch::Aarch64, Os::Darwin, Env::None),
818            Triple::new(Arch::Riscv64, Os::Linux, Env::Musl),
819        ] {
820            let layout = DataLayout::for_target(&TargetInfo::new(triple));
821            let text = layout.to_string();
822            assert_eq!(DataLayout::parse(&text), Some(layout), "{text}");
823        }
824    }
825
826    #[test]
827    fn a_layout_may_be_written_in_any_order() {
828        let text = "S128-i64:64-f80:128-p:64:64-e";
829        assert_eq!(DataLayout::parse(text), Some(DataLayout::for_target(&linux())));
830    }
831
832    #[test]
833    fn a_layout_needs_every_field_it_prints() {
834        for text in ["", "e", "e-p:64:64-S128", "e-i64:64-S128", "e-p:64:64-i64:64"] {
835            assert_eq!(DataLayout::parse(text), None, "{text}");
836        }
837    }
838
839    #[test]
840    fn a_layout_refuses_a_second_spelling() {
841        // Each of these would print back as something else, which breaks the round-trip.
842        for text in ["e-p:64:064-i64:64-S128", "e-e-p:64:64-i64:64-S128", "e-p:64:64-i64:64-S128-x"]
843        {
844            assert_eq!(DataLayout::parse(text), None, "{text}");
845        }
846    }
847
848    #[test]
849    fn a_module_finds_what_it_holds() {
850        let mut names = Interner::new();
851        let mut module = Module::new(names.intern("test.c"), &linux());
852
853        let counter = names.intern("counter");
854        let sum = names.intern("sum");
855        let total = names.intern("total");
856
857        let global = module.add_global(Global::new(counter, 4, 4));
858        let func = module.add_func(Func::new(sum, Signature::new()));
859        let alias = module.add_alias(Alias::new(total, counter));
860
861        assert_eq!(module.lookup(counter), Some(SymbolRef::Global(global)));
862        assert_eq!(module.lookup(sum), Some(SymbolRef::Func(func)));
863        assert_eq!(module.lookup(total), Some(SymbolRef::Alias(alias)));
864        assert_eq!(module.lookup(names.intern("nothing")), None);
865        assert_eq!(module[alias].target, counter);
866        assert!(module[global].is_declaration());
867        assert!(module[func].is_declaration());
868    }
869
870    #[test]
871    #[should_panic(expected = "two symbols with the same name")]
872    fn a_name_means_one_thing() {
873        let mut names = Interner::new();
874        let mut module = Module::new(names.intern("test.c"), &linux());
875        let name = names.intern("x");
876        module.add_global(Global::new(name, 4, 4));
877        module.add_func(Func::new(name, Signature::new()));
878    }
879
880    #[test]
881    fn an_initializer_adds_up_to_the_size() {
882        let mut names = Interner::new();
883        let mut module = Module::new(names.intern("test.c"), &linux());
884
885        // struct { int n; const char *name; char pad[6]; } = { 7, "hi", { 0 } };
886        let text = names.intern("hi.str");
887        let seven = module.add_imm(Imm::int(7, Type::int(32)));
888        let bytes = module.push_bytes(b"hi\0");
889        let addr = module.add_reloc(Reloc { symbol: text, addend: 0, size: 8 });
890        let init = module.push_data(&[
891            Datum::Scalar { ty: Type::int(32), value: seven },
892            Datum::Zero(4),
893            Datum::Addr(addr),
894            // The six bytes of `pad` and the two the struct is tailed out with. Padding is
895            // the frontend's arithmetic, and the image is what it came out as.
896            Datum::Zero(8),
897        ]);
898
899        let mut global = Global::new(names.intern("entry"), 24, 8);
900        global.init = Some(init);
901        global.constant = true;
902        let id = module.add_global(global);
903
904        assert!(!module[id].is_declaration());
905        let size: u64 = module[init].iter().map(|datum| datum.size(&module)).sum();
906        assert_eq!(size, module[id].size);
907        assert_eq!(&module[bytes], b"hi\0");
908        assert_eq!(module[seven].unsigned(), 7);
909        assert_eq!(module.counts().data_bytes, 3);
910    }
911
912    #[test]
913    fn a_scalar_datum_is_as_wide_as_its_type() {
914        let mut names = Interner::new();
915        let mut module = Module::new(names.intern("test.c"), &linux());
916        let value = module.add_imm(Imm::int(0, Type::int(32)));
917        assert_eq!(Datum::Scalar { ty: Type::int(32), value }.size(&module), 4);
918        // Rounded up to whole bytes, one lane at a time.
919        assert_eq!(Datum::Scalar { ty: Type::I1, value }.size(&module), 1);
920        assert_eq!(Datum::Scalar { ty: Type::int(24), value }.size(&module), 3);
921        assert_eq!(Datum::Scalar { ty: Type::vector(Type::int(8), 16), value }.size(&module), 16);
922    }
923
924    #[test]
925    fn the_names_round_trip() {
926        for linkage in Linkage::all() {
927            assert_eq!(Linkage::from_name(linkage.name()), Some(linkage));
928        }
929        for visibility in Visibility::all() {
930            assert_eq!(Visibility::from_name(visibility.name()), Some(visibility));
931        }
932        for model in TlsModel::all() {
933            assert_eq!(TlsModel::from_name(model.name()), Some(model));
934        }
935        for kind in [AliasKind::Alias, AliasKind::IFunc] {
936            assert_eq!(AliasKind::from_name(kind.name()), Some(kind));
937        }
938        assert_eq!(Linkage::from_name("static"), None);
939        assert_eq!(Visibility::from_name("internal"), None);
940    }
941
942    #[test]
943    fn only_internal_linkage_is_local() {
944        for linkage in Linkage::all() {
945            assert_eq!(linkage.is_local(), linkage == Linkage::Internal);
946            assert_eq!(
947                linkage.may_be_replaced(),
948                !matches!(linkage, Linkage::External | Linkage::Internal)
949            );
950        }
951    }
952
953    #[test]
954    fn metadata_is_shared_by_the_whole_module() {
955        let mut names = Interner::new();
956        let mut module = Module::new(names.intern("test.c"), &linux());
957        let char_node = module.add_meta(MetaNode::Tbaa(TbaaNode {
958            name: names.intern("omnipotent char"),
959            parent: None,
960            offset: 0,
961        }));
962        let int_node = module.add_meta(MetaNode::Tbaa(TbaaNode {
963            name: names.intern("int"),
964            parent: Some(char_node),
965            offset: 0,
966        }));
967        assert_eq!(module[int_node].parent(), Some(char_node));
968        assert_eq!(module.metadata().count(), 2);
969    }
970}