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