Skip to main content

rucc_lower/
unit.rs

1//! The module level of the walk: what a translation unit's declarations become.
2//!
3//! Design: `spec/08-ir.md` section 8.9.
4//!
5//! One typed tree becomes one [`Module`]. A file-scope object becomes a global with an image
6//! built from its initializer, a function becomes a [`Func`] whose body is built by
7//! [`body`](mod@crate::body), and a string literal becomes an unnamed constant global that
8//! whatever mentioned it points at.
9//!
10//! # What an image is
11//!
12//! An initializer arrives here already flattened: one entry per scalar that is stored, each
13//! with the byte offset it goes at, with every designator and every nested brace already
14//! resolved. So building the image is a walk over the entries in offset order, filling the gaps
15//! between them with zeros, and the only thing that has to be worked out per entry is whether
16//! the value is a number, a run of bytes from a string literal, or the address of something the
17//! linker has to place.
18//!
19//! # Names
20//!
21//! An object with linkage is known by the name it was written with, and there is nothing to
22//! invent. A `static` inside a function has no linkage and still needs a name in the object
23//! file, so it gets `name.N`, which is what gcc does and is why two functions may each have a
24//! `static int count;` without colliding. A string literal has no name at all and gets
25//! `.Lstr.N`, whose leading dot keeps it out of the symbol table on every target that has the
26//! convention.
27
28use std::cmp::Ordering;
29use std::collections::{BTreeMap, HashMap, HashSet};
30use std::fmt;
31
32use rucc_base::{Interner, Symbol};
33use rucc_diag::{Diagnostic, Span};
34use rucc_ir::{
35    Alias, AttrSet, DataList, Datum, FpContract, Func, Global, Imm, Linkage as IrLinkage, Meta,
36    Module, Reloc, SymbolRef, TlsModel, Type, Visibility as IrVisibility,
37};
38use rucc_sema::{
39    Address, Base, Const, Conversion, DeclFlags, DeclId, DeclKind, Definition, Effects, Emission,
40    Eval, ExprId, ExprKind, InitEntry, InitList, LabelId, Linkage, Priority, StorageDuration,
41    StrId, Tast, Visibility,
42};
43use rucc_target::{ObjectFormat, TargetInfo};
44use rucc_types::{TypeId, TypeKind, Types, compatible, is_complex, is_scalar};
45
46use crate::abi::{self, Plan};
47use crate::aliasing;
48use crate::body;
49use crate::directives;
50use crate::reach;
51use crate::repr;
52
53/// Which functions get a stack protector, which is what the `-fstack-protector` family decides.
54///
55/// The question is about the locals a function has, so it is answered here and not in the back
56/// end: by the time a frame is laid out the types are gone and every local is a size and an
57/// alignment. What the back end then does about the answer is its own business, and it is carried
58/// to it as [`rucc_ir::AttrSet::STACK_PROTECT`] on the function.
59///
60/// The names are gcc's, and so are the rules. A build that has been compiled with one of these for
61/// twenty years is entitled to the same set of protected functions from a compiler claiming to be
62/// compatible, because the ones left out are the ones an exploit goes looking for.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub enum Protector {
65    /// None of them, which is `-fno-stack-protector` and what a command line that says nothing
66    /// gets.
67    #[default]
68    None,
69    /// A function with a local array of at least eight bytes, or one whose stack grows while it
70    /// runs. `-fstack-protector`, which is the original and the narrowest.
71    Buffers,
72    /// Any of those, and any function with a local array at all, a local holding one, or a local
73    /// whose address is taken. `-fstack-protector-strong`, which is what every distribution builds
74    /// its packages with and therefore the one a real build line carries.
75    Strong,
76    /// Every function that has a frame at all. `-fstack-protector-all`.
77    All,
78}
79
80/// What overflows rather than being undefined, which is `-fwrapv` and its relatives.
81///
82/// Every licence the walk grants the optimizer about overflow is one flag on one instruction, and
83/// withdrawing a licence is not setting it. So this is read where the flags are chosen and nowhere
84/// else, and a unit built with either of these is a unit whose IR carries less rather than a unit
85/// the passes are told something extra about. That is also what makes it correct across link time
86/// optimization: a body from a unit that wraps and a body from one that does not keep their own
87/// answers when they end up in the same module.
88///
89/// `-ftrapv` is the exception and is the reason this is not simply two flags. It is the other
90/// answer to the question `-fwrapv` answers, and it is the only one of the three that asks for
91/// something to be generated rather than for something to be left out.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
93pub struct Wrapping {
94    /// Whether signed arithmetic wraps, from `-fwrapv`. Set, and an add, a subtract, a multiply, a
95    /// shift and a negation in a signed type stop saying they do not wrap.
96    pub signed: bool,
97    /// Whether pointer arithmetic wraps, from `-fwrapv-pointer`. Set, and the multiply that turns
98    /// an index into a number of bytes stops saying so.
99    ///
100    /// That multiply is the whole of it here, because the addition itself never claimed anything: a
101    /// `ptradd` carries no flags in this IR and no pass reads one off it.
102    pub pointer: bool,
103    /// Whether a signed overflow stops the program, from `-ftrapv`. Set, and an add, a subtract, a
104    /// multiply and a negation in a signed type become calls to the routine in the runtime that
105    /// does the arithmetic and checks it.
106    ///
107    /// Never set at the same time as [`Wrapping::signed`], because a program cannot both wrap and
108    /// stop. The driver is what keeps that true.
109    pub trap: bool,
110}
111
112/// Everything the walk reads, which is a checked translation unit and the target it is for.
113///
114/// The interner is mutable because the walk invents names the program never wrote: the label a
115/// string literal is emitted under, and the mangled name of a function-scope `static`.
116pub struct Context<'a> {
117    /// The typed tree.
118    pub tast: &'a Tast,
119    /// The types it points into.
120    pub types: &'a Types,
121    /// What is being compiled for, which is where every width and every alignment comes from.
122    pub target: &'a TargetInfo,
123    /// The name table.
124    pub names: &'a mut Interner,
125    /// What a name that no declaration of it said anything about gets, which is `-fvisibility=`.
126    ///
127    /// A fact about the compilation rather than about any declaration, which is why it arrives
128    /// here rather than on the tree: the checker knows what was written and this knows what the
129    /// command line asked for, and the answer is the first of those where there is one.
130    pub visibility: IrVisibility,
131    /// Which functions get a stack protector, which is `-fstack-protector` and its relatives.
132    pub protector: Protector,
133    /// What overflows rather than being undefined, which is `-fwrapv` and its relatives.
134    ///
135    /// A fact about the compilation for the same reason the two above it are: what was written is
136    /// on the tree and what was asked for is on the command line.
137    pub wrapping: Wrapping,
138    /// Whether an access carries the node for the type it goes through, which is
139    /// `-fstrict-aliasing` and is on unless `-fno-strict-aliasing` cleared it.
140    ///
141    /// Clearing it here rather than in the optimizer is what makes the flag one condition in one
142    /// place: an access with no node conflicts with every other access, so a unit built with the
143    /// flag off is a unit whose IR says less rather than a unit the passes are told something
144    /// extra about. That is also what keeps it right across link time optimization, the way
145    /// [`Context::wrapping`] is: a body from a unit that named its types and a body from one that
146    /// did not keep their own answers when they end up in the same module.
147    pub aliasing: bool,
148    /// Whether an access says how far the padding after it reaches, which is
149    /// `-fsafety-init=nopadding` and is what a build with no safety tier gets too, since nothing
150    /// reads the number then.
151    ///
152    /// Here rather than in the safety pass for the reason [`Context::aliasing`] is here: what the
153    /// number is takes a record's layout, and the layout is a thing the walk has in hand and the
154    /// pass over the IR does not. The pass reads it and does not decide anything, which keeps the
155    /// flag one condition in one place and keeps it right across link time optimization.
156    pub padding: bool,
157    /// How far a multiply and an addition may be fused into one rounding, which is
158    /// `-ffp-contract=`.
159    ///
160    /// A fact about the compilation like the ones above it, and the one of them that is written
161    /// down rather than acted on: it goes onto every function with a body as
162    /// [`rucc_ir::Attrs::fp_contract`], because the place that would fuse anything is the code
163    /// generator and by the time it runs the command line is gone and the two operations it might
164    /// fuse may have come from different statements.
165    pub contract: FpContract,
166    /// What every function in the unit is aligned to unless it asked for more itself, which is
167    /// `-falign-functions` and is `None` for the alignment the target gives anyway.
168    ///
169    /// A fact about the compilation like the ones above it, and it meets a fact about a
170    /// declaration here rather than further down: `__attribute__((aligned(N)))` is a statement
171    /// about one function and this is a preference about all of them, so the function takes the
172    /// larger of the two and everything below reads one number.
173    pub align: Option<u32>,
174    /// How a file named by a `.incbin` in an `asm` at file scope is read, given the name as the
175    /// template wrote it and handing back either the bytes or what went wrong.
176    ///
177    /// Passed in rather than reached for, because the walk has no business opening files and
178    /// because a caller that put its sources somewhere other than a disk has put this file there
179    /// too. The name is resolved the way an assembler resolves it, which is against the directory
180    /// the compiler was run in and not against the directory the source was found in.
181    pub read: &'a mut dyn FnMut(&str) -> Result<Vec<u8>, String>,
182}
183
184// Written out rather than derived because a closure has no `Debug`, and printing one would say
185// nothing anyway. What is worth reading here is the settings, so those are what this prints.
186impl fmt::Debug for Context<'_> {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.debug_struct("Context")
189            .field("visibility", &self.visibility)
190            .field("protector", &self.protector)
191            .field("wrapping", &self.wrapping)
192            .field("aliasing", &self.aliasing)
193            .field("padding", &self.padding)
194            .field("contract", &self.contract)
195            .field("align", &self.align)
196            .finish_non_exhaustive()
197    }
198}
199
200/// One function that runs without anything calling it, waiting for the section it goes in.
201///
202/// Held back rather than written where the definition is met, because the order they go in is not
203/// always the order the file defined them: a format with one section for all of them is a format
204/// where the only record of the priority is the position in that section, so they have to be
205/// sorted, and sorting means having all of them.
206#[derive(Debug, Clone, Copy)]
207struct Start {
208    /// The function the entry is the address of.
209    func: Symbol,
210    /// Whether it runs in the run-up to `main` rather than in the run-down after it.
211    before: bool,
212    /// Where in the order the attribute asked for it to go.
213    priority: Priority,
214    /// The definition it came from, for the diagnostic a format with no way to say it needs.
215    span: Span,
216}
217
218impl Start {
219    /// Where this goes among the others, which is the order the entries are written in.
220    ///
221    /// A lower number first, and the unnumbered ones after every numbered one, which is the order
222    /// an ELF linker puts the sections in and therefore the order every format has to come out in
223    /// for the three of them to agree. The sort is stable, so two at the same priority stay in the
224    /// order the file defined them, which is all that decides between them.
225    fn order(&self) -> (u8, u16) {
226        match self.priority {
227            Priority::Numbered(number) => (0, number),
228            Priority::Unnumbered => (1, 0),
229        }
230    }
231}
232
233/// What the walk produced.
234#[derive(Debug)]
235pub struct Lowered {
236    /// The module, which is complete even when something was reported: a construct that is not
237    /// supported yet leaves the rest of the function around it intact.
238    pub module: Module,
239    /// What was reported, in the order it was found.
240    pub diagnostics: Vec<Diagnostic>,
241}
242
243/// Walks a checked translation unit and builds the IR for it.
244///
245/// `name` is the module's name, which is the file the tree came from.
246#[must_use]
247pub fn lower(name: &str, cx: Context<'_>) -> Lowered {
248    let Context {
249        tast,
250        types,
251        target,
252        names,
253        visibility,
254        protector,
255        wrapping,
256        aliasing,
257        padding,
258        contract,
259        align,
260        read,
261    } = cx;
262    let module = Module::new(names.intern(name), target);
263    let reachable = reach::reachable(reach::Decide::new(tast, types, target, names));
264    let mut unit = Unit {
265        tast,
266        types,
267        target,
268        names,
269        visibility,
270        protector,
271        wrapping,
272        aliasing,
273        padding,
274        cliques: 0,
275        tree: aliasing::Tree::default(),
276        contract,
277        align,
278        read,
279        module,
280        diagnostics: Vec::new(),
281        strings: HashMap::new(),
282        anonymous: 0,
283        statics: HashMap::new(),
284        labels: HashMap::new(),
285        done: HashSet::new(),
286        aliases: Vec::new(),
287        sets: Vec::new(),
288        aliased: HashSet::new(),
289        starts: Vec::new(),
290        renamed: HashMap::new(),
291        reachable,
292    };
293    unit.run();
294    Lowered { module: unit.module, diagnostics: unit.diagnostics }
295}
296
297/// The walk over one translation unit, and everything it has built so far.
298pub(crate) struct Unit<'a> {
299    pub(crate) tast: &'a Tast,
300    pub(crate) types: &'a Types,
301    pub(crate) target: &'a TargetInfo,
302    pub(crate) names: &'a mut Interner,
303    /// What a name no declaration said anything about gets. See [`Context::visibility`].
304    visibility: IrVisibility,
305    /// Which functions get a stack protector. See [`Context::protector`].
306    pub(crate) protector: Protector,
307    /// What wraps rather than being undefined. See [`Context::wrapping`].
308    pub(crate) wrapping: Wrapping,
309    /// Whether an access names the type it goes through. See [`Context::aliasing`].
310    aliasing: bool,
311    /// Whether an access says how far the padding after it reaches. See [`Context::padding`].
312    pub(crate) padding: bool,
313    /// How many `restrict` scopes have been handed out, which is a number the whole module shares
314    /// so that no two functions promise different things with the same one. See
315    /// [`restrict`](mod@crate::restrict) for why that matters before there is an inliner.
316    pub(crate) cliques: u16,
317    /// The type based aliasing tree built so far, which is one per module.
318    tree: aliasing::Tree,
319    /// How far a multiply and an addition may be fused. See [`Context::contract`].
320    pub(crate) contract: FpContract,
321    /// What every function is aligned to unless it asked for more. See [`Context::align`].
322    align: Option<u32>,
323    /// How a file a `.incbin` names is read. See [`Context::read`].
324    read: &'a mut dyn FnMut(&str) -> Result<Vec<u8>, String>,
325    pub(crate) module: Module,
326    pub(crate) diagnostics: Vec<Diagnostic>,
327    /// The global each string literal was emitted as, so that two mentions of one literal are
328    /// one object.
329    strings: HashMap<StrId, Symbol>,
330    /// How many runs of bytes written under no label in an `asm` at file scope have been given a
331    /// name, which is what keeps the next one from being given the same one.
332    anonymous: usize,
333    /// The name each object with no linkage was given.
334    statics: HashMap<DeclId, Symbol>,
335    /// The name each label an image holds the address of was given.
336    ///
337    /// A label is a place inside a function and has no name in the object file, because a jump to
338    /// one is a distance the assembler works out and never a symbol. An image is the one thing
339    /// that cannot do that: it is in another section, so what it holds is a relocation, and a
340    /// relocation names a symbol. So a label an image points at gets one, minted here because the
341    /// image is lowered before the body is walked and the block the label starts does not exist
342    /// yet when the name is first asked for.
343    labels: HashMap<LabelId, Symbol>,
344    /// What has been emitted, because a redeclaration is the same declaration seen twice.
345    done: HashSet<DeclId>,
346    /// The declarations that are a second name for something rather than a thing of their own,
347    /// in the order the file made them.
348    ///
349    /// Held back rather than emitted where they are met, because what an alias points at may be
350    /// written below it and whether anything defines it is a question only the whole file
351    /// answers.
352    aliases: Vec<DeclId>,
353    /// The names a `.set` in an `asm` at file scope gave to something else, with the block each
354    /// one was written in, in the order the file wrote them.
355    ///
356    /// Held back for the reason above and written out beside the aliases, since the two are the
357    /// same thing said two ways: a second symbol at an address this object already has.
358    sets: Vec<(directives::Set, Span)>,
359    /// The symbols something in the file is a second name for.
360    ///
361    /// A `static` function nothing calls is not emitted, and being what an alias points at is a
362    /// reason to emit one that no reference in the file says: the string an alias names is not a
363    /// use of anything as far as the walk over the tree is concerned.
364    aliased: HashSet<Symbol>,
365    /// The functions the file asked to have run without anything calling them, in the order it
366    /// defined them.
367    ///
368    /// Held back rather than emitted where they are met, because the entries go in the order the
369    /// priorities put them and a function written at the top of the file may have asked to run
370    /// last. Only the whole file settles that order.
371    starts: Vec<Start>,
372    /// The assembler name the file gave to a name with linkage, kept by the name that was
373    /// written rather than by the declaration that wrote it.
374    ///
375    /// For [`Unit::library_name`], which knows what the C library calls a function and not what
376    /// this file has said about it. The declaration that renames `memcpy` is a different
377    /// declaration from the implicit one the checker made for `__builtin_memcpy`, so the label
378    /// on the first is never reached from the second, and a program that renames a function and
379    /// then calls the builtin means the call to go to the new name.
380    renamed: HashMap<Symbol, Symbol>,
381    /// What something in the file reaches, which is what decides whether a function with
382    /// internal linkage is emitted at all.
383    reachable: HashSet<DeclId>,
384}
385
386// The debug is by hand and short: a translation unit is not something anybody wants printed as
387// a `{:?}`, and the module has a printer of its own for when they do.
388impl fmt::Debug for Unit<'_> {
389    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390        f.debug_struct("Unit")
391            .field("module", &self.module.counts())
392            .field("diagnostics", &self.diagnostics.len())
393            .finish()
394    }
395}
396
397impl Unit<'_> {
398    /// The aliasing node an access through `ty` carries, and [`None`] when it carries none.
399    ///
400    /// [`None`] is also every answer under `-fno-strict-aliasing`, which is the whole of what that
401    /// flag does here. See [`aliasing`](mod@crate::aliasing) for which types have a node.
402    pub(crate) fn alias_node(&mut self, ty: TypeId) -> Option<Meta> {
403        if !self.aliasing {
404            return None;
405        }
406        self.tree.node(&mut self.module, self.names, self.types, ty)
407    }
408
409    /// The root of the aliasing tree, which is the node an access that may be punned carries.
410    ///
411    /// The root is `char` and it conflicts with everything, so an access carrying it is an access
412    /// nothing may be reordered across and, in the type plane, a byte nothing has settled the type
413    /// of. `crate::body` says which accesses those are.
414    pub(crate) fn alias_root(&mut self) -> Option<Meta> {
415        if !self.aliasing {
416            return None;
417        }
418        Some(self.tree.root(&mut self.module, self.names))
419    }
420
421    /// Every declaration the file made, in the order it made them.
422    fn run(&mut self) {
423        self.file_asms();
424        self.find_aliased();
425        self.find_renamed();
426        for index in 0..self.tast.top_level().len() {
427            let decl = self.tast.top_level()[index];
428            if !self.done.insert(decl) {
429                continue;
430            }
431            match self.tast[decl].kind {
432                DeclKind::Function => self.function(decl),
433                DeclKind::Object => self.object(decl),
434                // A name for a type is only in the tree at block scope and nothing is emitted
435                // for one.
436                DeclKind::Type => {}
437            }
438        }
439        for index in 0..self.aliases.len() {
440            self.alias(self.aliases[index]);
441        }
442        for index in 0..self.sets.len() {
443            let (set, span) = self.sets[index].clone();
444            self.equated(&set, span);
445        }
446        self.startups();
447    }
448
449    /// The `asm` written at file scope, read into the globals they define.
450    ///
451    /// Ahead of the declarations rather than among them. A block usually names more than one
452    /// thing and means them to be next to each other, the object writer lays globals out in the
453    /// order the module holds them, and adding a block's globals together is what makes them a
454    /// run. A declaration of one of those names below the block then finds a definition already
455    /// there and leaves it alone, which is the division the program wrote: the template says what
456    /// the bytes are and the C declaration says what they are to be read as.
457    fn file_asms(&mut self) {
458        for index in 0..self.tast.file_asms().len() {
459            let asm = self.tast.file_asms()[index];
460            let template = self.spelled(asm.template);
461            let read = match directives::assemble(&template, &mut *self.read) {
462                Ok(read) => read,
463                Err(directives::Failed::Unsupported(what)) => {
464                    self.unsupported(&format!("{what} in an `asm` at file scope"), asm.span);
465                    continue;
466                }
467                Err(directives::Failed::Missing(name, why)) => {
468                    let message = format!("cannot open '{name}' for reading: {why}");
469                    self.diagnostics.push(Diagnostic::error(message, asm.span).with_code("E0702"));
470                    continue;
471                }
472            };
473            // The name of every global of the block first, because a distance one of them writes
474            // is measured to a place in another of them and a relocation names a symbol, so the
475            // name has to be to hand before the bytes that refer to it are built.
476            let symbols: Vec<Symbol> = read
477                .pieces
478                .iter()
479                .map(|piece| match &piece.name {
480                    Some(name) => self.names.intern(name),
481                    None => {
482                        let name = format!(".Lasm.{}", self.anonymous);
483                        self.anonymous += 1;
484                        self.names.intern(&name)
485                    }
486                })
487                .collect();
488            for (index, piece) in read.pieces.into_iter().enumerate() {
489                self.piece(piece, symbols[index], &symbols);
490            }
491            // Held back until the file has been walked, because a name a block equates may be
492            // defined below the block, and remembered as a name something points at, because a
493            // `static` function an equate is the only reference to is one that has to be emitted.
494            for set in read.sets {
495                let target = self.names.intern(&set.target);
496                self.aliased.insert(target);
497                self.sets.push((set, asm.span));
498            }
499        }
500    }
501
502    /// One global an `asm` at file scope defined, under the name minted for it and with the names
503    /// of the whole block to hand.
504    ///
505    /// The bytes a template writes before it writes any label are a global like the rest and a
506    /// global has to have a name, so one is minted for them. Nothing refers to it by that name, so
507    /// the only thing it has to be is one nothing else takes, and the leading dot keeps it out of
508    /// the symbol table the way the name of a string literal does.
509    fn piece(&mut self, piece: directives::Piece, symbol: Symbol, symbols: &[Symbol]) {
510        let mut global = Global::new(symbol, piece.size, piece.align.max(1));
511        global.linkage = piece.linkage;
512        global.visibility = piece.visibility;
513        let bss = matches!(piece.section, directives::Section::Bss);
514        match piece.section {
515            // Which of the sections the object writer has an answer of its own for. Asking for
516            // `.rodata` by name would produce a second section with that spelling and with the
517            // flags of a writable one, so what is said here is what the global is instead.
518            directives::Section::ReadOnly => global.constant = true,
519            directives::Section::Data | directives::Section::Bss => {}
520            directives::Section::Named(name) => global.section = Some(self.names.intern(&name)),
521            // Refused where the template was read, since what goes in that section is
522            // instructions and there is nothing here that makes one.
523            directives::Section::Text => return,
524        }
525        let mut data = Vec::with_capacity(piece.items.len());
526        if piece.items.is_empty() && bss {
527            // A label at the end of the zero filled section, which has nothing under it and
528            // still has to land there rather than in the section of written bytes. An image of
529            // no zeros is what says so, since being all zeros is how a global asks for that
530            // section and an empty image asks for nothing.
531            data.push(Datum::Zero(0));
532        }
533        for item in piece.items {
534            data.push(match item {
535                directives::Item::Bytes(bytes) => Datum::Bytes(self.module.push_bytes(&bytes)),
536                directives::Item::Int { width, value } => {
537                    let ty = Type::int(u32::from(width) * 8);
538                    Datum::Scalar {
539                        ty,
540                        value: self.module.add_imm(Imm::int(i128::from(value), ty)),
541                    }
542                }
543                directives::Item::Zero(bytes) => Datum::Zero(bytes),
544                // Four bytes holding how far that global is from these bytes, which the reader
545                // said in globals of this block rather than in names because the place it
546                // measures to is usually a label the object file holds no name for.
547                directives::Item::Away { piece, addend } => {
548                    let reloc = Reloc { symbol: symbols[piece], addend, size: 4 };
549                    Datum::Away(self.module.add_reloc(reloc))
550                }
551            });
552        }
553        global.init = Some(self.module.push_data(&data));
554        self.place_global(global);
555    }
556
557    /// Which symbols the file gives a second name to, before anything is emitted.
558    ///
559    /// Ahead of the walk rather than during it, because a `static` function is emitted or not on
560    /// the strength of what reaches it and the alias that reaches one may be written below it.
561    fn find_aliased(&mut self) {
562        for index in 0..self.tast.top_level().len() {
563            let decl = self.tast.top_level()[index];
564            let Some(target) = self.tast[decl].alias else { continue };
565            let spelling = self.spelled(target);
566            let symbol = self.names.intern(&spelling);
567            self.aliased.insert(symbol);
568        }
569    }
570
571    /// Which names the file gave an assembler name of their own, before anything is emitted.
572    ///
573    /// Ahead of the walk for the reason [`Unit::find_aliased`] is: the call to
574    /// `__builtin_memcpy` may be written above the declaration of `memcpy` that renames it, and
575    /// the two spellings are one function.
576    fn find_renamed(&mut self) {
577        for index in 0..self.tast.top_level().len() {
578            let decl = self.tast.top_level()[index];
579            let node = &self.tast[decl];
580            let (linkage, name, label) = (node.linkage, node.name, node.asm_label);
581            if linkage == Linkage::None {
582                continue;
583            }
584            let (Some(name), Some(label)) = (name, label) else { continue };
585            let spelling = self.spelled(label);
586            let symbol = self.names.intern(&spelling);
587            self.renamed.insert(name, symbol);
588        }
589    }
590
591    /// The bytes of a string literal as a name, which is what a symbol in an attribute is.
592    fn spelled(&self, id: StrId) -> String {
593        self.tast[id].elements.iter().filter_map(|&unit| char::from_u32(unit)).collect()
594    }
595
596    /// One object with static storage duration.
597    fn object(&mut self, decl: DeclId) {
598        let tast = self.tast;
599        let node = &tast[decl];
600        let (ty, state, init) = (node.ty, node.state, node.init);
601        let (linkage, duration, alignment) = (node.linkage, node.duration, node.alignment);
602        let span = tast.decl_span(decl);
603        if duration == StorageDuration::Automatic {
604            // A block-scope object with automatic storage is a slot or a value in the function
605            // that declares it, and the body is what makes it. Nothing is emitted here.
606            return;
607        }
608        // A second name for something else is not an object of its own, so nothing is laid out
609        // and no image is built. It is held back until the rest of the file has been walked,
610        // because what it points at may be below it.
611        if node.alias.is_some() {
612            self.aliases.push(decl);
613            return;
614        }
615
616        let symbol = self.symbol_of(decl);
617        let size = repr::size_of(self.types, self.target, ty);
618        let align = alignment.unwrap_or_else(|| repr::align_of(self.types, self.target, ty));
619        let mut global = Global::new(symbol, size, align);
620        global.linkage = self.told(decl, linkage);
621        // A tentative definition counts as one, because it is one: `int x;` at file scope puts a
622        // symbol in this object and the linker never has to look anywhere else for it.
623        global.visibility = self.seen(decl, state != Definition::Declared);
624        global.tls = (duration == StorageDuration::Thread).then_some(TlsModel::GlobalDynamic);
625        global.constant = repr::is_read_only(self.types, ty);
626        global.init = match state {
627            // `extern int x;` and nothing else names an object another translation unit
628            // defines. The global is here so that a reference to it has something to resolve
629            // against, and it has no image, which is what makes it a declaration.
630            Definition::Declared => None,
631            Definition::Tentative => Some(self.zeros(size)),
632            Definition::Defined => {
633                let (data, covered) = self.image(init, size, span);
634                // The object is as large as its image when the image is the larger of the two.
635                // A structure whose last member is a flexible array is the only way that
636                // happens: `sizeof` answers without the array and an initializer that fills it
637                // makes an object big enough to hold what was written. C 6.7.2.1p18 leaves the
638                // size to the implementation, gcc grows the object, and this does the same
639                // rather than hand the linker a size the image does not fit in.
640                global.size = size.max(covered);
641                Some(data)
642            }
643        };
644        self.place_global(global);
645    }
646
647    /// One function, with its body when it has one.
648    fn function(&mut self, decl: DeclId) {
649        let tast = self.tast;
650        let node = &tast[decl];
651        let (ty, linkage, body, align) = (node.ty, node.linkage, node.body, node.alignment);
652        let noreturn = node.flags.contains(DeclFlags::NORETURN);
653        let naked = node.flags.contains(DeclFlags::NAKED);
654        let effects = node.effects;
655        let startup = node.startup;
656        let span = tast.decl_span(decl);
657        if node.name.is_none() {
658            return;
659        }
660        // The same as for an object: a second name is not a function of its own, and it is held
661        // back until what it points at has been emitted.
662        if node.alias.is_some() {
663            self.aliases.push(decl);
664            return;
665        }
666        // Which asks the one question the reference to it asks, so that a declaration that
667        // renamed the symbol renames the definition as well and the two still meet.
668        let name = self.symbol_of(decl);
669        if self.is_dropped(decl, name) {
670            return;
671        }
672        let Some(plan) = self.plan(ty, &[], span) else { return };
673
674        let mut func = Func::new(name, plan.signature.clone());
675        // The name the source spelled, where an assembler name says the symbol is not it. A
676        // declaration of `strstr` renamed to `my_strstr` is a declaration of `strstr` still, and
677        // once the symbol is the only name left there is nothing to find that out again from.
678        if node.asm_label.is_some() {
679            func.spelled = node.name.filter(|&spelled| spelled != name);
680        }
681        // Where the body begins, which is the line a debugger names over the prologue. gcc says the
682        // line the opening brace is on rather than the line the declarator is on, and the two
683        // differ in the style that puts the brace underneath. No instruction in a prologue has a
684        // span of its own, so this is the only place the fact can come from. A declaration has no
685        // body and produces no prologue, so it falls back to the declarator and nothing reads it.
686        func.declared = body.map_or(span, |body| tast.stmt_span(body));
687        // The larger of what this function asked for and what the command line asked of all of
688        // them, since the attribute is a requirement and the flag is a preference, and a
689        // preference does not get to move a function off a boundary its own source named.
690        func.align = match (align, self.align) {
691            (Some(mine), Some(everyones)) => Some(mine.max(everyones)),
692            (mine, everyones) => mine.or(everyones),
693        };
694        // The one thing a declaration says that nobody downstream can work out for themselves.
695        // What `abort` does belongs to `abort`, and a translation unit that only declares it has
696        // nothing to look at, so the claim has to travel on the declaration or not at all.
697        if noreturn {
698            func.attrs.set |= AttrSet::NORETURN;
699        }
700        // Which is not a claim about what a call to it does but a fact about how the function
701        // itself is written, so unlike the two around it there is nothing here for a declaration
702        // alone to be useful for. It travels the same way because the attribute is written in the
703        // same places. See [`rucc_codegen`] for what reads it, which is the frame.
704        if naked {
705            func.attrs.set |= AttrSet::NAKED;
706        }
707        // And the other one, for the same reason. What a call to `strtol` reads belongs to
708        // `strtol`, and the purity analysis answers opaque for everything it cannot see a body
709        // for, so a unit that only declares the function gets nothing out of it unless the
710        // promise arrives here. `const` says the result comes from the arguments alone, which
711        // is `readnone`, and `pure` says it may read memory, which is `readonly`. The two are
712        // an incompatible pair in the IR and only one of them is ever set.
713        func.attrs.set |= match effects {
714            Effects::Any => AttrSet::NONE,
715            Effects::Pure => AttrSet::READONLY,
716            Effects::Const => AttrSet::READNONE,
717        };
718        // An inline definition this unit calls, which this unit has to put a copy of out of line
719        // because it has no inliner to make the call go away. See [`Self::out_of_line`].
720        let copied = body.is_some() && self.out_of_line(decl, node.inline);
721        func.linkage = if copied { IrLinkage::LinkOnce } else { self.told(decl, linkage) };
722        // The same question as for an object, and the same answer, with one wrinkle: an inline
723        // definition this unit neither emits nor calls is a declaration here, since C 6.7.4p7
724        // sends the calls to whatever unit holds the external definition, so it is not this
725        // file's to describe. That is the condition the body is lowered under, a few lines below.
726        func.visibility = self.seen(decl, body.is_some() && (node.inline.emits() || copied));
727        // An inline definition is not an external definition, so what goes in the module is the
728        // declaration and not the body. C 6.7.4p7 says the calls in this unit go to the definition
729        // some other unit holds, which is what the declaration gives them, and glibc's headers
730        // rely on it: every one of their inline definitions would otherwise be a second definition
731        // of a name the library already defines. Unless this unit is one of the callers, which is
732        // the case [`Self::out_of_line`] is about.
733        if body.is_some() && (node.inline.emits() || copied) {
734            body::lower(self, decl, &mut func, &plan);
735            // Only for a definition, because an entry is an address and a declaration of something
736            // another file defines has none to put there. gcc reads the attribute off whichever
737            // declaration carried it and then waits for the definition in the same way, which is
738            // why writing `__attribute__((constructor)) void f(void);` in a header costs every
739            // file that includes it nothing.
740            if let Some(priority) = startup.before {
741                self.starts.push(Start { func: name, before: true, priority, span });
742            }
743            if let Some(priority) = startup.after {
744                self.starts.push(Start { func: name, before: false, priority, span });
745            }
746        }
747        self.place_func(func);
748    }
749
750    /// Puts a function in the module under a name something may already be under.
751    ///
752    /// Two declarations of one identifier were merged before this, so the only way one name
753    /// arrives twice is an assembler name that renames one identifier onto another: a
754    /// declaration of `f` renamed to `g` beside a definition of `g` is one symbol written two
755    /// ways, which is what the program asked for and what the linker is going to see. The
756    /// definition wins wherever there is one, since what the declaration is here for is to give
757    /// the calls something to resolve against and the definition does that as well.
758    ///
759    /// A name already carrying a definition keeps it. That is the program defining one symbol
760    /// twice, and the assembler says so with the name in front of it, which is a better message
761    /// than anything available here.
762    fn place_func(&mut self, func: Func) {
763        match self.module.lookup(func.name) {
764            None => {
765                self.module.add_func(func);
766            }
767            Some(SymbolRef::Func(id))
768                if self.module[id].is_declaration() && !func.is_declaration() =>
769            {
770                self.module[id] = func;
771            }
772            Some(_) => {}
773        }
774    }
775
776    /// One declaration that is a second name for something the same file defines.
777    ///
778    /// Emitted after everything else, so the target is looked up in a module that already holds
779    /// whatever the file defines whether it was written above the alias or below it.
780    ///
781    /// The target has to be defined here and not merely declared, which is gcc's rule and is
782    /// what the object format can express: an alias is a symbol at another symbol's address, and
783    /// a name this file does not define has no address for one to be at. A program that writes
784    /// an alias of something in another object wants a reference rather than a definition, and
785    /// what it gets from gcc is this same error rather than a name the linker cannot resolve.
786    fn alias(&mut self, decl: DeclId) {
787        let Some(written) = self.tast[decl].alias else { return };
788        let span = self.tast.decl_span(decl);
789        let name = self.symbol_of(decl);
790        let spelling = self.spelled(written);
791        let target = self.names.intern(&spelling);
792        if self.no_address(name, target, span) {
793            return;
794        }
795        // Something already under this name, which is the program defining one symbol twice. The
796        // definition that is there stands, the way it does for a function and for an object.
797        if self.module.lookup(name).is_some() {
798            return;
799        }
800        let mut alias = Alias::new(name, target);
801        alias.linkage = self.told(decl, self.tast[decl].linkage);
802        // Its own answer, because the attribute is written on the alias and an alias is a symbol
803        // of its own. `weak, alias, visibility("hidden")` is a name a library keeps to itself
804        // while the thing it points at stays exported, which is how glibc writes half of them.
805        // Always a definition. An alias is a symbol this object puts at an address in this object,
806        // and one whose target is merely declared was refused a few lines above.
807        alias.visibility = self.seen(decl, true);
808        self.module.add_alias(alias);
809    }
810
811    /// One name a `.set` in an `asm` at file scope gave to something else.
812    ///
813    /// The same thing as the alias above it and written out the same way, with the two answers
814    /// about the name coming from the directives around the `.set` rather than from an attribute:
815    /// `.globl` and `.weak` say how the linker sees it, `.hidden` and `.protected` say how far it
816    /// reaches, and a name no directive spoke about is local, which is what an assembler does with
817    /// one. A name the file also defines keeps its own definition, which is the rule everything
818    /// else here follows and is what gcc's output shows for a `.set` written above a definition of
819    /// the same name.
820    fn equated(&mut self, set: &directives::Set, span: Span) {
821        let name = self.names.intern(&set.name);
822        let target = self.names.intern(&set.target);
823        if self.no_address(name, target, span) {
824            return;
825        }
826        // A name the file only declared is one the `.set` gives an address to, and tcc's test
827        // calls a function declared `extern` in C and defined by `.set` in a file-scope `asm`.
828        let declared = match self.module.lookup(name) {
829            None => true,
830            Some(SymbolRef::Func(id)) => self.module[id].is_declaration(),
831            Some(SymbolRef::Global(id)) => self.module[id].is_declaration(),
832            Some(SymbolRef::Alias(_)) => false,
833        };
834        if !declared {
835            return;
836        }
837        let mut alias = Alias::new(name, target);
838        alias.linkage = set.linkage;
839        alias.visibility = set.visibility;
840        self.module.add_alias_over(alias);
841    }
842
843    /// Whether there is no address for a second name to be at, reporting why when there is not.
844    ///
845    /// The target has to be defined here and not merely declared, because an alias is a symbol at
846    /// another symbol's address and a name this file does not define has no address in it. A
847    /// program that writes one of these about something in another object wants a reference rather
848    /// than a definition, and gcc turns that down as well.
849    fn no_address(&mut self, name: Symbol, target: Symbol, span: Span) -> bool {
850        let spelled = self.names.resolve(name).to_owned();
851        if name == target {
852            let what = format!("'{spelled}' is aliased to itself");
853            self.diagnostics.push(Diagnostic::error(what, span).with_code("E0697"));
854            return true;
855        }
856        let defined = match self.module.lookup(target) {
857            Some(SymbolRef::Func(id)) => !self.module[id].is_declaration(),
858            Some(SymbolRef::Global(id)) => self.module[id].init.is_some(),
859            // A chain of them is a thing gcc takes and this does not yet, because resolving one
860            // wants the aliases put in an order that the file they were written in need not be
861            // in. It is reported rather than written out as a name pointing at a name.
862            Some(SymbolRef::Alias(_)) | None => false,
863        };
864        if !defined {
865            let spelling = self.names.resolve(target).to_owned();
866            let what = format!("'{spelled}' is aliased to undefined symbol '{spelling}'");
867            let note = "the target of an alias has to be defined in this same file, since an \
868                        alias is a second name for an address and not a reference to one";
869            let refused = Diagnostic::error(what, span).with_code("E0697");
870            self.diagnostics.push(refused.note(note, span));
871            return true;
872        }
873        false
874    }
875
876    /// The list of functions to run around `main`, written out as the entries that run them.
877    ///
878    /// In priority order rather than in the order the file defined them, because two of the three
879    /// formats get their order from the order the entries are in and only ELF sorts anything at
880    /// link time.
881    fn startups(&mut self) {
882        let mut starts = std::mem::take(&mut self.starts);
883        starts.sort_by_key(Start::order);
884        for start in starts {
885            self.start_entry(&start);
886        }
887    }
888
889    /// One entry, which is a pointer wide object in the section the format runs.
890    ///
891    /// A relocation against the function rather than a value, since the address is not known until
892    /// the link. The object has internal linkage and a name nothing refers to: the only thing that
893    /// reads it is the CRT walking the section, which finds it by where it is and not by what it is
894    /// called. gcc emits no symbol at all for one, and a name with a dot in it is the nearest thing
895    /// to that here, being one no C program can write and therefore one no program collides with.
896    fn start_entry(&mut self, start: &Start) {
897        let Some(section) = self.start_section(start) else {
898            self.no_start(start);
899            return;
900        };
901        let size = u64::from(self.target.pointer_width / 8);
902        let align = u32::try_from(size).unwrap_or(1);
903        let called = self.names.resolve(start.func).to_owned();
904        let which = if start.before { "ctor" } else { "dtor" };
905        let name = self.names.intern(&format!("__rucc_{which}.{called}"));
906        let section = self.names.intern(&section);
907        let mut global = Global::new(name, size, align);
908        global.linkage = IrLinkage::Internal;
909        global.section = Some(section);
910        let size = u32::try_from(size).unwrap_or(0);
911        let reloc = self.module.add_reloc(Reloc { symbol: start.func, addend: 0, size });
912        global.init = Some(self.module.push_data(&[Datum::Addr(reloc)]));
913        self.place_global(global);
914    }
915
916    /// The section an entry goes in, and [`None`] for a format with no way to ask for one.
917    ///
918    /// ELF has both halves and the linker sorts the numbered sections ahead of the plain one, so
919    /// the number goes in the name and the order comes out right however the files were linked.
920    ///
921    /// COFF has the run-up only. The name is sorted by what follows the `$` and the CRT walks
922    /// everything between the `.CRT$XCA` and `.CRT$XCZ` markers, so a numbered entry goes just
923    /// after the first marker and an unnumbered one at `U`, which keeps the numbered ones first.
924    ///
925    /// Mach-O has the run-up only as well, and it has no sorting at all: the entries run in the
926    /// order the section holds them, which is the order [`Self::startups`] put them in.
927    fn start_section(&self, start: &Start) -> Option<String> {
928        match self.target.object_format {
929            ObjectFormat::Elf => {
930                let base = if start.before { ".init_array" } else { ".fini_array" };
931                Some(match start.priority {
932                    Priority::Numbered(number) => format!("{base}.{number:05}"),
933                    Priority::Unnumbered => base.to_owned(),
934                })
935            }
936            ObjectFormat::Coff if start.before => Some(match start.priority {
937                Priority::Numbered(number) => format!(".CRT$XCA{number:05}"),
938                Priority::Unnumbered => ".CRT$XCU".to_owned(),
939            }),
940            ObjectFormat::MachO if start.before => {
941                Some("__DATA,__mod_init_func,mod_init_funcs".to_owned())
942            }
943            ObjectFormat::Coff | ObjectFormat::MachO | ObjectFormat::Wasm => None,
944        }
945    }
946
947    /// Reports an attribute this format has nowhere to put.
948    ///
949    /// Refused rather than dropped, because the whole point of the attribute is that something
950    /// else calls the function and a program that quietly does not get its call has no way of
951    /// noticing until whatever the function set up is missing.
952    ///
953    /// The run-down is what is missing on the two formats that have a run-up. Mach-O used to have
954    /// a terminator list and dyld stopped running it, so clang registers the call with
955    /// `__cxa_atexit` from a constructor it writes for the purpose, and nothing in the CRT a COFF
956    /// target links against has been confirmed to walk one either. Doing the same here is a
957    /// feature rather than a section name, which is why this is a message and not a branch above.
958    fn no_start(&mut self, start: &Start) {
959        let which = if start.before { "constructor" } else { "destructor" };
960        let format = self.target.object_format.as_str();
961        let what = format!("the '{which}' attribute on a {format} target");
962        self.unsupported(&what, start.span);
963    }
964
965    /// How far a name reaches outside a shared library, which is what a declaration of it said
966    /// where one said anything and what the command line asked for where none did.
967    ///
968    /// gcc's `-fvisibility=` is written as the default rather than as an override, so the
969    /// attribute wins wherever it was written, and that is the whole reason a library compiled
970    /// with `-fvisibility=hidden` can still export the dozen names it means to export.
971    ///
972    /// The default reaches what this unit defines and stops there, which is the `defined`
973    /// argument and is the whole of tamnd/rucc#1234. `-fvisibility=hidden` is a claim about the
974    /// names this file puts into the library, and a name it only mentions is one it knows nothing
975    /// about: `stderr` is in libc however the file that reads it was compiled, and calling it
976    /// hidden tells the linker to resolve it inside this object, which it cannot do. The attribute
977    /// on a declaration is a different thing and still counts, because a program that writes it
978    /// has said where the definition is going to come from.
979    ///
980    /// Measured against gcc 16.2.0 rather than read off the manual, since the manual says the flag
981    /// applies to declarations and does not say which ones. For `extern int plain;` beside
982    /// `__attribute__((visibility("hidden"))) extern int marked;` at `-fPIC -fvisibility=hidden`,
983    /// gcc writes `plain` as `GLOBAL DEFAULT UND` and reaches it through the global offset table,
984    /// and writes `marked` as `GLOBAL HIDDEN UND` and reaches it from the instruction pointer.
985    fn seen(&self, decl: DeclId, defined: bool) -> IrVisibility {
986        match self.tast[decl].visibility {
987            Some(Visibility::Default) => IrVisibility::Default,
988            Some(Visibility::Hidden) => IrVisibility::Hidden,
989            Some(Visibility::Protected) => IrVisibility::Protected,
990            None if defined => self.visibility,
991            None => IrVisibility::Default,
992        }
993    }
994
995    /// What the linker is told about a name, which is its C linkage unless a declaration of it
996    /// wrote `weak`.
997    ///
998    /// The attribute is refused on internal linkage where it is read, so external is the only
999    /// thing it can change, and the two things a program means by it are one thing to the linker.
1000    /// On a definition it says another object's definition of the name beats this one, which is
1001    /// how a library ships a default. On a reference to something this file does not define it
1002    /// says the link may leave the name undefined and hand the reference a zero address, which is
1003    /// how a library offers a hook and why zstd's thirty files link at all.
1004    fn told(&self, decl: DeclId, linkage: Linkage) -> IrLinkage {
1005        match linkage {
1006            Linkage::External if self.tast[decl].flags.contains(DeclFlags::WEAK) => IrLinkage::Weak,
1007            Linkage::External => IrLinkage::External,
1008            Linkage::Internal | Linkage::None => IrLinkage::Internal,
1009        }
1010    }
1011
1012    /// Whether a body this unit is not meant to emit has to be emitted anyway, because this unit
1013    /// calls it and has nothing else to send the call to.
1014    ///
1015    /// C 6.7.4p7 says an inline definition is not an external definition, and the bargain it
1016    /// offers is that the call is replaced by the body, so nobody ever has to resolve the name.
1017    /// A compiler that inlines keeps its end of it. This one does not inline, so a call left
1018    /// standing is a call to a name no object file defines, and the program fails at the link on
1019    /// a function it can see the body of. micropython is a program that does exactly that:
1020    /// `py/misc.h` writes `MP_COMPRESSED_ROM_TEXT` as `inline __attribute__((always_inline))`,
1021    /// nothing anywhere defines it out of line, and every file that reports an error calls it.
1022    ///
1023    /// So a copy goes out of line, under [`IrLinkage::LinkOnce`]. Every unit that calls one emits
1024    /// its own copy of the same body, the linker keeps one and the rest are discarded, and a unit
1025    /// that holds the real external definition beats all of them because a strong definition
1026    /// beats a weak one. What that costs is object size in the units that call one. What it buys
1027    /// is that the address of the function is the same everywhere and that the program links,
1028    /// which is the whole of what the program was asking for.
1029    ///
1030    /// Only when this unit names it, which is why [`reach`] stopped treating one of these as a
1031    /// root. An unreferenced inline definition is still emitted as nothing at all, which is what
1032    /// keeps a file that includes `stdio.h` from carrying its own `vprintf`, `putchar`, `getchar`
1033    /// and the dozen more glibc writes beside them.
1034    fn out_of_line(&self, decl: DeclId, emission: Emission) -> bool {
1035        !emission.emits() && self.reachable.contains(&decl)
1036    }
1037
1038    /// The same for an object, where a global with no image is the declaration.
1039    fn place_global(&mut self, global: Global) {
1040        match self.module.lookup(global.name) {
1041            None => {
1042                self.module.add_global(global);
1043            }
1044            Some(SymbolRef::Global(id))
1045                if self.module[id].init.is_none() && global.init.is_some() =>
1046            {
1047                self.module[id] = global;
1048            }
1049            Some(_) => {}
1050        }
1051    }
1052
1053    /// Whether this function is one nothing can call, which is the set that is not emitted.
1054    ///
1055    /// A name with internal linkage is not visible to another translation unit, so a definition
1056    /// of one that nothing here refers to is a definition of something that can never run.
1057    /// [`reach`](mod@crate::reach) is what worked out which those are, and an attribute that asks
1058    /// for the definition to be kept has already been read into the answer.
1059    ///
1060    /// A second name for it is the one reason to keep it that the walk over the tree cannot see,
1061    /// since what an alias points at is a string and not a reference to anything. So the symbol
1062    /// is what is asked about here rather than the declaration: an alias names what the linker
1063    /// will look for, which is what a declaration that renamed itself with `__asm__` is under.
1064    ///
1065    /// Nothing is said about it. gcc has `-Wunused-function` for a `static` function nobody
1066    /// wrote a call to, which is a warning about the program, and this is not that: the header
1067    /// that defines six of them is not the file being compiled and its author is not the person
1068    /// reading the output.
1069    fn is_dropped(&self, decl: DeclId, symbol: Symbol) -> bool {
1070        self.tast[decl].linkage != Linkage::External
1071            && !self.reachable.contains(&decl)
1072            && !self.aliased.contains(&symbol)
1073    }
1074
1075    /// How everything a call to this function type hands over travels, and [`None`] for one the
1076    /// walk cannot make.
1077    ///
1078    /// `actual` is the types of the arguments at a call site, which matter only past the end of
1079    /// the prototype: what a variadic argument does is decided from what was written there, and
1080    /// there is no parameter to decide it from. A definition passes nothing for it.
1081    pub(crate) fn plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
1082        self.plan_with(ty, actual, false, span)
1083    }
1084
1085    /// The same, as the call site sees it rather than as the function does.
1086    ///
1087    /// The two differ for a type that is not a prototype. An old style definition is the one of
1088    /// those that knows what its parameters are, and 6.5.2.2p6 checks a call against a prototype
1089    /// and against nothing at all otherwise, so a parameter it disagrees with does not make the
1090    /// call wrong and cannot be what the argument travels as either: the value at the call is
1091    /// the argument's own type and nothing converted it. So a parameter the argument facing it
1092    /// is compatible with is used, which is the usual case and is what makes the call go to the
1093    /// name, and one it is not compatible with gives way to what was actually written. A call
1094    /// like that is undefined behaviour if control reaches it and the file still has to
1095    /// translate, which is the same position [`Body::direct`](crate::body) already takes.
1096    pub(crate) fn call_plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
1097        self.plan_with(ty, actual, true, span)
1098    }
1099
1100    fn plan_with(
1101        &mut self,
1102        ty: TypeId,
1103        actual: &[TypeId],
1104        at_call: bool,
1105        span: Span,
1106    ) -> Option<Plan> {
1107        let canonical = self.types.canonical(ty);
1108        let canonical = match self.types.kind(canonical) {
1109            // A call goes through a pointer to a function, and the type in hand may be either.
1110            TypeKind::Pointer(pointee) => self.types.canonical(pointee),
1111            _ => canonical,
1112        };
1113        let TypeKind::Function(id) = self.types.kind(canonical) else {
1114            self.unsupported("a call through something that is not a function", span);
1115            return None;
1116        };
1117        let signature = self.types.signature(id);
1118        let ret = signature.ret;
1119        // A function declared without a prototype takes what it is given, which is what a
1120        // signature with no parameters and no end to them says. C23 removed these and this is
1121        // what `int f();` means in every dialect before it.
1122        let variadic = signature.variadic || !signature.prototyped;
1123        let params = if at_call && !signature.prototyped {
1124            // An argument past the end of the list has no parameter to travel as, which is what
1125            // a call to an unprototyped function with more arguments than the definition takes
1126            // is, so the list ends where the arguments do.
1127            signature
1128                .params
1129                .iter()
1130                .zip(actual)
1131                .map(|(&param, &arg)| if compatible(self.types, param, arg) { param } else { arg })
1132                .collect()
1133        } else {
1134            signature.params.clone()
1135        };
1136
1137        match abi::plan(self.types, self.target, ret, &params, actual, variadic) {
1138            Ok(plan) => Some(plan),
1139            Err(what) => {
1140                self.unsupported(what, span);
1141                None
1142            }
1143        }
1144    }
1145
1146    /// The image of an initializer: the entries in ascending order, with the gaps zeroed, and
1147    /// how many bytes it covers.
1148    ///
1149    /// The count is the size that was asked for except when a flexible array member was given
1150    /// something to hold, which is the one case where an image is larger than the type it is an
1151    /// image of.
1152    pub(crate) fn image(
1153        &mut self,
1154        init: Option<InitList>,
1155        size: u64,
1156        span: Span,
1157    ) -> (DataList, u64) {
1158        let Some(init) = init else { return (self.zeros(size), size) };
1159        let (data, at) = self.pieces(init, size, span);
1160        (self.module.push_data(&data), at)
1161    }
1162
1163    /// The data an image is made of, before it becomes a [`DataList`].
1164    ///
1165    /// This is apart from [`Self::image`] so that an image can be built inside another one,
1166    /// which is what a compound literal used as a value in an initializer needs.
1167    fn pieces(&mut self, init: InitList, size: u64, span: Span) -> (Vec<Datum>, u64) {
1168        let entries = self.in_image_order(&self.tast[init]);
1169        let mut packed = self.packed(&entries, size);
1170        let mut data: Vec<Datum> = Vec::with_capacity(entries.len());
1171        let mut at = 0;
1172        for entry in entries {
1173            let piece = self.entry(entry, &mut packed, size);
1174            if piece.is_empty() {
1175                continue;
1176            }
1177            let covered: u64 = piece.iter().map(|datum| datum.size(&self.module)).sum();
1178            match entry.offset.cmp(&at) {
1179                Ordering::Greater => data.push(Datum::Zero(entry.offset - at)),
1180                // An entry that begins inside the one before it, which is neither the same
1181                // place nor a later one. A union whose members are initialized through two
1182                // designators is the way to write it. The earlier bytes are already in the
1183                // list and the image cannot take them out again, so this is refused, and
1184                // nothing here is wrong enough to drop the rest of the image.
1185                Ordering::Less => {
1186                    self.unsupported("an initializer that writes over an earlier one", span);
1187                    continue;
1188                }
1189                Ordering::Equal => {}
1190            }
1191            at = entry.offset + covered;
1192            data.extend(piece);
1193        }
1194        if at < size {
1195            // The tail of a partly initialized object, which C says is zero. So is the tail of
1196            // an array the initializer did not fill, and so is every byte of padding.
1197            data.push(Datum::Zero(size - at));
1198            at = size;
1199        }
1200        (data, at)
1201    }
1202
1203    /// The entries an image is written from, which is not the order they were written in.
1204    ///
1205    /// A designator names a place, and the places may be named in any order at all:
1206    /// `{ .b = 2, .a = 1 }` is the same object as `{ .a = 1, .b = 2 }` and C says so in as many
1207    /// words. An image is bytes in ascending order, so the entries are put in that order here.
1208    /// The sort is stable, which is what makes the rest of the rule work: naming one place
1209    /// twice is legal and the last of them is the one that stands, so among the entries at one
1210    /// offset the written order is kept and all but the last are dropped.
1211    ///
1212    /// A bit-field is never dropped, because several of them share one offset without writing
1213    /// over anything. Which bytes they came to is settled by [`Self::packed`] before this runs
1214    /// and the whole run goes in under the first entry that has a bit in it.
1215    fn in_image_order(&self, entries: &[InitEntry]) -> Vec<InitEntry> {
1216        let mut sorted = entries.to_vec();
1217        sorted.sort_by_key(|entry| entry.offset);
1218        let mut kept: Vec<InitEntry> = Vec::with_capacity(sorted.len());
1219        for entry in sorted {
1220            if !entry.is_bit_field() {
1221                let over = |last: &InitEntry| last.offset == entry.offset && !last.is_bit_field();
1222                while kept.last().is_some_and(over) {
1223                    kept.pop();
1224                }
1225            }
1226            kept.push(entry);
1227        }
1228        kept
1229    }
1230
1231    /// What one entry of an initializer puts in the image.
1232    ///
1233    /// A bit-field is not a datum of its own, because two of them can live in one byte and an
1234    /// image is written in bytes. They were put together into their bytes by [`Self::packed`]
1235    /// before this ran, and the whole run of bytes goes in under the first entry that lies in
1236    /// it, which is why a later one in the same run answers with nothing.
1237    ///
1238    /// The zeroes at the end of a run are left off it, and a run that is nothing but zeroes
1239    /// answers with nothing at all. Either way the gap before the next entry covers them, which
1240    /// is the same image and is a smaller one to carry, and it is what keeps an object whose
1241    /// bit-fields are all zero in `.bss`. A zero at the front of a run or inside one stays, since
1242    /// that is where the run starts and what makes it one run. The run comes out of the map
1243    /// whatever is in it, so a later entry lying in it answers with nothing for the usual reason
1244    /// rather than writing the run a second time.
1245    ///
1246    /// An entry is usually one datum and a compound literal read is the reason the answer is a
1247    /// list: that entry is a whole object and puts as many data in as the object it is.
1248    fn entry(&mut self, entry: InitEntry, packed: &mut BTreeMap<u64, u8>, size: u64) -> Vec<Datum> {
1249        if entry.is_bit_field() {
1250            let Some(bytes) = take_run(packed, entry.offset) else { return Vec::new() };
1251            let Some(last) = bytes.iter().rposition(|&byte| byte != 0) else { return Vec::new() };
1252            return vec![Datum::Bytes(self.module.push_bytes(&bytes[..=last]))];
1253        }
1254        if let Some(literal) = self.literal_read(entry.value) {
1255            return self.literal_image(literal, self.tast.expr_span(entry.value));
1256        }
1257        if entry.reverse {
1258            if let Some(reversed) = self.reversed_datum(entry) {
1259                return reversed;
1260            }
1261        }
1262        // How much room is left in the object, which is what a string literal longer than the
1263        // array it initializes is cut down to. An entry that begins where the object ends is the
1264        // initializer of a flexible array member, and there the object grows to hold what was
1265        // written rather than the value being cut to fit, so nothing is taken off it.
1266        let room = if entry.offset < size { size - entry.offset } else { u64::MAX };
1267        if let Some(halves) = self.complex_image(entry.value) {
1268            return halves;
1269        }
1270        self.datum(entry.value, room).into_iter().collect()
1271    }
1272
1273    /// A complex constant as the two data an image holds it in, and [`None`] for anything else.
1274    ///
1275    /// A complex value is two real ones and an image is bytes, so `1.0 + 2.0i` goes in as the two
1276    /// halves one after the other, which is the layout every ABI here already reads it as. It is
1277    /// two data rather than one because a datum is one scalar, and it is here rather than in
1278    /// [`Self::datum`] for the same reason.
1279    fn complex_image(&mut self, value: ExprId) -> Option<Vec<Datum>> {
1280        let ty = self.tast[value].ty;
1281        let part = rucc_types::real_part(self.types, ty)?;
1282        let span = self.tast.expr_span(value);
1283        // Everything below this point answers with something, because the folding reports its own
1284        // failure and asking for the value a second time would report it twice.
1285        let folded = match self.fold(value) {
1286            Some(folded) => folded,
1287            None => return Some(Vec::new()),
1288        };
1289        let Some(ty) = repr::value_type(self.types, self.target, part) else {
1290            self.unsupported("this complex initializer", span);
1291            return Some(Vec::new());
1292        };
1293        // Each half goes in as the half's own type would, which is the bits of a floating value
1294        // and the number of an integer one.
1295        let halves = match folded {
1296            Const::Complex { real, imag } => {
1297                [real, imag].map(|half| Imm::from_bits(half.to_bits()))
1298            }
1299            Const::ComplexInt { real, imag } => [real, imag].map(|half| Imm::int(half, ty)),
1300            _ => {
1301                self.unsupported("this complex initializer", span);
1302                return Some(Vec::new());
1303            }
1304        };
1305        let data = halves
1306            .into_iter()
1307            .map(|half| {
1308                let imm = self.module.add_imm(half);
1309                Datum::Scalar { ty, value: imm }
1310            })
1311            .collect();
1312        Some(data)
1313    }
1314
1315    /// The compound literal an entry reads, if that is what the entry is.
1316    ///
1317    /// Reading an object is a node of its own, so a literal used as a value comes through as a
1318    /// read of a literal. A literal whose address is taken is not a read and is not this: that
1319    /// one folds to an address and goes in as a relocation, with the object it points at emitted
1320    /// on its own.
1321    fn literal_read(&self, value: ExprId) -> Option<DeclId> {
1322        let ExprKind::Convert { kind: Conversion::Lvalue, operand } = self.tast[value].kind else {
1323            return None;
1324        };
1325        match self.tast[operand].kind {
1326            ExprKind::CompoundLiteral(decl) => Some(decl),
1327            _ => None,
1328        }
1329    }
1330
1331    /// The bytes a compound literal contributes where it is read, which are its own image.
1332    ///
1333    /// The literal has static storage duration here, since a file-scope initializer is the only
1334    /// place this is reached from, and C 6.7.11p4 is what lets it stand as a constant element.
1335    /// Its own initializer is built at the offset the entry is at, so the parent image ends up
1336    /// with the literal's bytes laid into it rather than a name pointing at a second object.
1337    fn literal_image(&mut self, literal: DeclId, span: Span) -> Vec<Datum> {
1338        let size = repr::size_of(self.types, self.target, self.tast[literal].ty);
1339        let Some(init) = self.tast[literal].init else {
1340            return if size == 0 { Vec::new() } else { vec![Datum::Zero(size)] };
1341        };
1342        self.pieces(init, size, span).0
1343    }
1344
1345    /// The bit-fields of an initializer, put together into the bytes they lie in.
1346    ///
1347    /// Every byte a field lies in is in the map, whatever the bits it put there are. It is
1348    /// tempting to leave a zero byte out, on the grounds that what an image does not say is zero
1349    /// anyway, and it is wrong: the run a field's bytes make is taken out of the map from the
1350    /// byte the field starts at, so a field whose first byte happens to be zero would have its
1351    /// whole run left behind and `struct { unsigned f : 20; } x = { 0x12300 };` would read as
1352    /// zero. A run that is all zeroes is written as zeroes by [`Self::entry`], so an object that
1353    /// really is zero still costs nothing in the image.
1354    ///
1355    /// A field named twice takes only the bits of the field, so the last of them stands and does
1356    /// not read as the two values together.
1357    fn packed(&mut self, entries: &[InitEntry], size: u64) -> BTreeMap<u64, u8> {
1358        let mut bytes = BTreeMap::new();
1359        for entry in entries.iter().filter(|entry| entry.is_bit_field()) {
1360            let Some(folded) = self.fold(entry.value) else { continue };
1361            let Const::Int(number) = folded else {
1362                let span = self.tast.expr_span(entry.value);
1363                let what = "a bit-field initialized by something that is not an integer";
1364                self.unsupported(what, span);
1365                continue;
1366            };
1367            let width = entry.bit_width;
1368            let ones = if width >= 128 { u128::MAX } else { (1u128 << width) - 1 };
1369            // Which bytes the field lies in and where in them it sits. A reversed field lies in
1370            // the same bytes and is counted from the top of them, and the byte at its address is
1371            // then the most significant of the ones the value is assembled in rather than the
1372            // least, which is why the walk below runs the other way as well.
1373            let span = u64::from((entry.bit_offset + width).div_ceil(8));
1374            let start = if entry.reverse {
1375                u32::try_from(span * 8).unwrap_or(u32::MAX) - entry.bit_offset - width
1376            } else {
1377                entry.bit_offset
1378            };
1379            let mut mask = ones << start;
1380            let mut placed = ((number as u128) & ones) << start;
1381            let mut step = 0;
1382            while mask != 0 && step < span {
1383                let at = if entry.reverse {
1384                    entry.offset + span - 1 - step
1385                } else {
1386                    entry.offset + step
1387                };
1388                if at < size {
1389                    let (bits, keep) = ((placed & 0xff) as u8, !((mask & 0xff) as u8));
1390                    let byte = bytes.entry(at).or_insert(0);
1391                    *byte = (*byte & keep) | bits;
1392                }
1393                mask >>= 8;
1394                placed >>= 8;
1395                step += 1;
1396            }
1397        }
1398        bytes
1399    }
1400
1401    /// What one entry of a record whose scalars are stored the other way round puts in the image.
1402    ///
1403    /// The bytes of the value, written in the order opposite to the target's, which is the whole of
1404    /// what the attribute asks for. It answers with nothing where the ordinary path is already
1405    /// right: a value one byte wide has only one order, and an aggregate is bytes its own members
1406    /// put there in whatever order each of them is stored in.
1407    ///
1408    /// Two things are refused rather than written the wrong way. A complex value is two scalars and
1409    /// this is one, and an address is a number the linker fills in later and there is nowhere to
1410    /// say it goes in backwards. Both are worth an answer one day and neither is worth a wrong one.
1411    fn reversed_datum(&mut self, entry: InitEntry) -> Option<Vec<Datum>> {
1412        let ty = self.tast[entry.value].ty;
1413        let span = self.tast.expr_span(entry.value);
1414        if is_complex(self.types, ty) {
1415            let what = "a complex member of a record whose scalars are stored the other way round";
1416            self.unsupported(what, span);
1417            return Some(Vec::new());
1418        }
1419        let size = repr::size_of(self.types, self.target, ty);
1420        if size < 2 || !is_scalar(self.types, ty) {
1421            return None;
1422        }
1423        let bits = match self.fold(entry.value) {
1424            Some(Const::Int(number)) => number as u128,
1425            Some(Const::Float(number)) => number.to_bits(),
1426            Some(Const::Address(Address { base: Base::Absolute, offset })) => offset as u128,
1427            Some(_) => {
1428                let what = "an address in a record whose scalars are stored the other way round";
1429                self.unsupported(what, span);
1430                return Some(Vec::new());
1431            }
1432            None => return Some(Vec::new()),
1433        };
1434        let take = cap(size).min(16);
1435        let mut bytes = bits.to_le_bytes()[..take].to_vec();
1436        if self.target.little_endian {
1437            bytes.reverse();
1438        }
1439        Some(vec![Datum::Bytes(self.module.push_bytes(&bytes))])
1440    }
1441
1442    /// One entry of an image, given how many bytes are left in the object it goes in.
1443    fn datum(&mut self, value: ExprId, room: u64) -> Option<Datum> {
1444        let tast = self.tast;
1445        let ty = tast[value].ty;
1446        let span = tast.expr_span(value);
1447        if let TypeKind::Array { .. } = self.types.kind(self.types.canonical(ty)) {
1448            // An array in an initializer is a string literal initializing it, because that is
1449            // the only way an array is ever a value. `char s[2] = "hi";` drops the terminator,
1450            // which is the one case where the literal is longer than what it initializes, and
1451            // the front end has already given the value the type of the array it is filling, so
1452            // the type is what says how many of the literal's bytes are part of it. `room` is
1453            // still consulted because a flexible array member is filled by a literal that keeps
1454            // its own type and there is no size in the object for it to be cut to.
1455            let ExprKind::Str(id) = tast[value].kind else {
1456                self.unsupported("this initializer", span);
1457                return None;
1458            };
1459            let bytes = tast[id].bytes(self.target);
1460            let holds = repr::size_of(self.types, self.target, ty);
1461            let take = bytes.len().min(cap(holds)).min(cap(room));
1462            return Some(Datum::Bytes(self.module.push_bytes(&bytes[..take])));
1463        }
1464
1465        let size = repr::size_of(self.types, self.target, ty);
1466        match self.fold(value)? {
1467            Const::Int(number) => {
1468                let ty = repr::value_type(self.types, self.target, ty)?;
1469                // An integer constant of pointer type is a null pointer constant, which is what
1470                // `NULL` is, or an address the program wrote as a number. An image is bytes and
1471                // `ptr` says nothing about how many, so it goes in as the integer it is at the
1472                // width the target's addresses have. An address the linker has to fill in is
1473                // the arm below, and is the only one that stays a pointer.
1474                let ty = if ty.is_ptr() { Type::int(self.target.pointer_width) } else { ty };
1475                let imm = self.module.add_imm(Imm::int(number, ty));
1476                Some(Datum::Scalar { ty, value: imm })
1477            }
1478            Const::Float(number) => {
1479                let ty = repr::value_type(self.types, self.target, ty)?;
1480                let imm = self.module.add_imm(Imm::from_bits(number.to_bits()));
1481                Some(Datum::Scalar { ty, value: imm })
1482            }
1483            // A complex constant is two scalars and this answers with one, so it is not one of
1484            // these. [`Self::complex_image`] puts one in before this is reached.
1485            Const::Complex { .. } | Const::ComplexInt { .. } => None,
1486            // An address into nothing is a number, so it goes into the image as one and there is
1487            // no relocation for the linker to fill in. `static char *p = &((struct S *)0)->f;` is
1488            // a pointer whose value is known here, and the walk that folded it already said so.
1489            Const::Address(Address { base: Base::Absolute, offset }) => {
1490                let ty = repr::value_type(self.types, self.target, ty)?;
1491                let ty = if ty.is_ptr() { Type::int(self.target.pointer_width) } else { ty };
1492                let imm = self.module.add_imm(Imm::int(offset, ty));
1493                Some(Datum::Scalar { ty, value: imm })
1494            }
1495            // Two labels, both named for the image the way one is for `&&l`, and the width is
1496            // the type's since the distance is a number and not an address.
1497            Const::Apart { to, from } => {
1498                let to = self.label_name(to);
1499                let from = self.label_name(from);
1500                let size = u32::try_from(size).unwrap_or(0);
1501                let to = self.module.add_reloc(Reloc { symbol: to, addend: 0, size });
1502                Some(Datum::Apart { to, from })
1503            }
1504            Const::Address(address) => {
1505                let symbol = match address.base {
1506                    Base::Decl(decl) => {
1507                        // A compound literal is an object nothing declares, so the address of
1508                        // one is also the only thing that asks for it to be emitted. Without
1509                        // this the image names a symbol the module never defines and the link
1510                        // is what finds out. Anything with a name of its own is left alone,
1511                        // since the walk over the unit reaches those on its own.
1512                        if self.tast[decl].name.is_none() {
1513                            self.local_static(decl);
1514                        }
1515                        self.symbol_of(decl)
1516                    }
1517                    Base::Str(id) => self.string(id),
1518                    Base::Label(label) => self.label_name(label),
1519                    // Answered above, where it becomes a number rather than a reference.
1520                    Base::Absolute => return None,
1521                };
1522                let addend = i64::try_from(address.offset).unwrap_or(0);
1523                let size = u32::try_from(size).unwrap_or(0);
1524                Some(Datum::Addr(self.module.add_reloc(Reloc { symbol, addend, size })))
1525            }
1526        }
1527    }
1528
1529    /// An image of nothing but zeros, which is what a tentative definition has.
1530    fn zeros(&mut self, size: u64) -> DataList {
1531        if size == 0 {
1532            return DataList::EMPTY;
1533        }
1534        self.module.push_data(&[Datum::Zero(size)])
1535    }
1536
1537    /// The global a string literal is emitted as, making it the first time it is asked for.
1538    pub(crate) fn string(&mut self, id: StrId) -> Symbol {
1539        if let Some(&symbol) = self.strings.get(&id) {
1540            return symbol;
1541        }
1542        let literal = &self.tast[id];
1543        let bytes = literal.bytes(self.target);
1544        let align = literal.encoding.element_width(self.target) / 8;
1545        let symbol = self.names.intern(&format!(".Lstr.{}", self.strings.len()));
1546
1547        let mut global = Global::new(symbol, bytes.len() as u64, align.max(1));
1548        global.linkage = IrLinkage::Internal;
1549        // Not because the type says so, since a literal is an array of `char` and not of
1550        // `const char`, but because writing to one is undefined and every target puts them
1551        // somewhere read-only.
1552        global.constant = true;
1553        let range = self.module.push_bytes(&bytes);
1554        global.init = Some(self.module.push_data(&[Datum::Bytes(range)]));
1555        self.module.add_global(global);
1556        self.strings.insert(id, symbol);
1557        symbol
1558    }
1559
1560    /// The name a label an image holds the address of is known by, minting one the first time.
1561    ///
1562    /// The number is what makes two labels in two functions two names, the same way it does for a
1563    /// `static` inside a function. Nothing but the relocation and the definition the back end
1564    /// writes for it ever reads this, so the spelling only has to be one the object format lets a
1565    /// local symbol have, and the leading dot is what keeps it out of the symbol table on the
1566    /// formats that have the convention.
1567    pub(crate) fn label_name(&mut self, label: LabelId) -> Symbol {
1568        if let Some(&symbol) = self.labels.get(&label) {
1569            return symbol;
1570        }
1571        let symbol = self.names.intern(&format!(".Llbl.{}", self.labels.len()));
1572        self.labels.insert(label, symbol);
1573        symbol
1574    }
1575
1576    /// The name a label was given, or `None` for a label no image points at.
1577    pub(crate) fn named_label(&self, label: LabelId) -> Option<Symbol> {
1578        self.labels.get(&label).copied()
1579    }
1580
1581    /// The name the C library gives a function the program named with the `__builtin_` prefix,
1582    /// and nothing for every other name.
1583    ///
1584    /// `__builtin_abort` is a call to `abort`: the prefix is how a program reaches the function
1585    /// the library promises where a macro or a definition of its own has taken the plain name,
1586    /// so the two spellings are one function and the one the linker will look for is the short
1587    /// one. Which names those are is [`rucc_sema::library_name`]'s to say, since it is the same
1588    /// answer the front end declared them out of.
1589    fn library_name(&mut self, name: Symbol) -> Option<Symbol> {
1590        let library = rucc_sema::library_name(self.names.resolve(name))?;
1591        let symbol = self.names.intern(library);
1592        // And then whatever the file said that name is called in the object file. A program is
1593        // allowed to declare `memcpy` with an assembler name of its own and go on calling
1594        // `__builtin_memcpy`, and what it means by that is the renamed one: the prefix picks the
1595        // function out of the library, it does not ask for a symbol the file has renamed away.
1596        Some(self.renamed.get(&symbol).copied().unwrap_or(symbol))
1597    }
1598
1599    /// The name an object or a function is known by in the object file.
1600    pub(crate) fn symbol_of(&mut self, decl: DeclId) -> Symbol {
1601        let tast = self.tast;
1602        let node = &tast[decl];
1603        // The assembler name a declaration wrote, which is the symbol whatever the identifier
1604        // spells. It stands for a `static` and for a local one as well as for a name the linker
1605        // sees, so it is read before anything else here: a program that renames a name has said
1606        // what the symbol is, and the numbering below is for the ones that have not.
1607        if let Some(label) = node.asm_label {
1608            let spelling: String =
1609                tast[label].elements.iter().filter_map(|&unit| char::from_u32(unit)).collect();
1610            return self.names.intern(&spelling);
1611        }
1612        if node.linkage != Linkage::None {
1613            let Some(name) = node.name else { return self.names.intern(".Lanon") };
1614            return self.library_name(name).unwrap_or(name);
1615        }
1616        if let Some(&symbol) = self.statics.get(&decl) {
1617            return symbol;
1618        }
1619        // A `static` in a function, or a compound literal with static storage duration. The
1620        // number is what makes two of them in two functions two objects.
1621        let base = match node.name {
1622            Some(name) => self.names.resolve(name).to_string(),
1623            None => ".Lanon".to_string(),
1624        };
1625        let symbol = self.names.intern(&format!("{base}.{}", self.statics.len()));
1626        self.statics.insert(decl, symbol);
1627        symbol
1628    }
1629
1630    /// Emits the global for an object with static storage duration declared inside a function.
1631    pub(crate) fn local_static(&mut self, decl: DeclId) {
1632        if !self.done.insert(decl) {
1633            return;
1634        }
1635        match self.tast[decl].kind {
1636            // A function declared inside a body is a declaration of the function, not an
1637            // object with static storage that happens to be one.
1638            DeclKind::Function => self.function(decl),
1639            DeclKind::Object => self.object(decl),
1640            DeclKind::Type => {}
1641        }
1642    }
1643
1644    /// The value of a constant expression, reporting what folding it reported.
1645    ///
1646    /// Everything this is asked about is part of the image of an object that exists before the
1647    /// program runs, which is the one place C23 6.6p10 lets a compiler take more than the rest of
1648    /// 6.6 does, so it asks for the reading the front end already accepted there. Asking the
1649    /// strict way instead would refuse here what was allowed a pass earlier, which is a wrong
1650    /// answer arriving late rather than an extra check.
1651    fn fold(&mut self, expr: ExprId) -> Option<Const> {
1652        let mut eval = Eval::new(self.tast, self.types, self.target, self.names);
1653        let folded = eval.initializer(expr);
1654        let reported = eval.finish();
1655        self.diagnostics.extend(reported);
1656        match folded {
1657            Ok(value) => Some(value),
1658            Err(stop) => {
1659                if !stop.poisoned {
1660                    let span = self.tast.expr_span(stop.at);
1661                    self.unsupported("an initializer this compiler cannot fold", span);
1662                }
1663                None
1664            }
1665        }
1666    }
1667
1668    /// Reports a construct the walk does not build IR for yet.
1669    pub(crate) fn unsupported(&mut self, what: &str, span: Span) {
1670        self.diagnostics.push(
1671            Diagnostic::error(format!("{what} is not supported yet"), span).with_code("E0519"),
1672        );
1673    }
1674
1675    /// Reports a call to a builtin this compiler knows the name of and does nothing with.
1676    ///
1677    /// It is its own message rather than [`Self::unsupported`] because the construct is not the
1678    /// problem: a call is a call, and what is missing is the one function it goes to. The note is
1679    /// what a reader needs, since a builtin is the one name a programmer does not expect to have
1680    /// to provide and the alternative to this message is a linker asking them for it.
1681    pub(crate) fn missing_builtin(&mut self, spelled: &str, span: Span) {
1682        let message = format!("`{spelled}` is not implemented yet");
1683        let note = "a call to it would go to a symbol no object file defines, so this is refused \
1684                    here rather than at the link";
1685        self.diagnostics.push(Diagnostic::error(message, span).with_code("E0686").note(note, span));
1686    }
1687}
1688
1689/// A count of bytes as a length of a slice of them, saturating on a target whose addresses are
1690/// wider than this host's.
1691fn cap(bytes: u64) -> usize {
1692    usize::try_from(bytes).unwrap_or(usize::MAX)
1693}
1694
1695/// The run of bytes a bit-field entry starts, taken out of the map.
1696///
1697/// [`None`] when there is no byte at that offset, which means an earlier entry in the same run
1698/// already took it, since [`Unit::packed`] puts every byte a field lies in into the map.
1699fn take_run(bytes: &mut BTreeMap<u64, u8>, start: u64) -> Option<Vec<u8>> {
1700    let mut run = vec![bytes.remove(&start)?];
1701    let mut at = start + 1;
1702    while let Some(byte) = bytes.remove(&at) {
1703        run.push(byte);
1704        at += 1;
1705    }
1706    Some(run)
1707}