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};
30
31use rucc_base::{Interner, Symbol};
32use rucc_diag::{Diagnostic, Span};
33use rucc_ir::{
34 Alias, DataList, Datum, Func, Global, Imm, Linkage as IrLinkage, Module, Reloc, SymbolRef,
35 TlsModel, Type,
36};
37use rucc_sema::{
38 Base, Const, Conversion, DeclId, DeclKind, Definition, Eval, ExprId, ExprKind, InitEntry,
39 InitList, Linkage, StorageDuration, StrId, Tast,
40};
41use rucc_target::TargetInfo;
42use rucc_types::{TypeId, TypeKind, Types, compatible};
43
44use crate::abi::{self, Plan};
45use crate::body;
46use crate::reach;
47use crate::repr;
48
49/// Everything the walk reads, which is a checked translation unit and the target it is for.
50///
51/// The interner is mutable because the walk invents names the program never wrote: the label a
52/// string literal is emitted under, and the mangled name of a function-scope `static`.
53#[derive(Debug)]
54pub struct Context<'a> {
55 /// The typed tree.
56 pub tast: &'a Tast,
57 /// The types it points into.
58 pub types: &'a Types,
59 /// What is being compiled for, which is where every width and every alignment comes from.
60 pub target: &'a TargetInfo,
61 /// The name table.
62 pub names: &'a mut Interner,
63}
64
65/// What the walk produced.
66#[derive(Debug)]
67pub struct Lowered {
68 /// The module, which is complete even when something was reported: a construct that is not
69 /// supported yet leaves the rest of the function around it intact.
70 pub module: Module,
71 /// What was reported, in the order it was found.
72 pub diagnostics: Vec<Diagnostic>,
73}
74
75/// Walks a checked translation unit and builds the IR for it.
76///
77/// `name` is the module's name, which is the file the tree came from.
78#[must_use]
79pub fn lower(name: &str, cx: Context<'_>) -> Lowered {
80 let Context { tast, types, target, names } = cx;
81 let module = Module::new(names.intern(name), target);
82 let mut unit = Unit {
83 tast,
84 types,
85 target,
86 names,
87 module,
88 diagnostics: Vec::new(),
89 strings: HashMap::new(),
90 statics: HashMap::new(),
91 done: HashSet::new(),
92 aliases: Vec::new(),
93 aliased: HashSet::new(),
94 reachable: reach::reachable(tast),
95 };
96 unit.run();
97 Lowered { module: unit.module, diagnostics: unit.diagnostics }
98}
99
100/// The walk over one translation unit, and everything it has built so far.
101pub(crate) struct Unit<'a> {
102 pub(crate) tast: &'a Tast,
103 pub(crate) types: &'a Types,
104 pub(crate) target: &'a TargetInfo,
105 pub(crate) names: &'a mut Interner,
106 pub(crate) module: Module,
107 pub(crate) diagnostics: Vec<Diagnostic>,
108 /// The global each string literal was emitted as, so that two mentions of one literal are
109 /// one object.
110 strings: HashMap<StrId, Symbol>,
111 /// The name each object with no linkage was given.
112 statics: HashMap<DeclId, Symbol>,
113 /// What has been emitted, because a redeclaration is the same declaration seen twice.
114 done: HashSet<DeclId>,
115 /// The declarations that are a second name for something rather than a thing of their own,
116 /// in the order the file made them.
117 ///
118 /// Held back rather than emitted where they are met, because what an alias points at may be
119 /// written below it and whether anything defines it is a question only the whole file
120 /// answers.
121 aliases: Vec<DeclId>,
122 /// The symbols something in the file is a second name for.
123 ///
124 /// A `static` function nothing calls is not emitted, and being what an alias points at is a
125 /// reason to emit one that no reference in the file says: the string an alias names is not a
126 /// use of anything as far as the walk over the tree is concerned.
127 aliased: HashSet<Symbol>,
128 /// What something in the file reaches, which is what decides whether a function with
129 /// internal linkage is emitted at all.
130 reachable: HashSet<DeclId>,
131}
132
133// The debug is by hand and short: a translation unit is not something anybody wants printed as
134// a `{:?}`, and the module has a printer of its own for when they do.
135impl std::fmt::Debug for Unit<'_> {
136 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137 f.debug_struct("Unit")
138 .field("module", &self.module.counts())
139 .field("diagnostics", &self.diagnostics.len())
140 .finish()
141 }
142}
143
144impl Unit<'_> {
145 /// Every declaration the file made, in the order it made them.
146 fn run(&mut self) {
147 self.find_aliased();
148 for index in 0..self.tast.top_level().len() {
149 let decl = self.tast.top_level()[index];
150 if !self.done.insert(decl) {
151 continue;
152 }
153 match self.tast[decl].kind {
154 DeclKind::Function => self.function(decl),
155 DeclKind::Object => self.object(decl),
156 }
157 }
158 for index in 0..self.aliases.len() {
159 self.alias(self.aliases[index]);
160 }
161 }
162
163 /// Which symbols the file gives a second name to, before anything is emitted.
164 ///
165 /// Ahead of the walk rather than during it, because a `static` function is emitted or not on
166 /// the strength of what reaches it and the alias that reaches one may be written below it.
167 fn find_aliased(&mut self) {
168 for index in 0..self.tast.top_level().len() {
169 let decl = self.tast.top_level()[index];
170 let Some(target) = self.tast[decl].alias else { continue };
171 let spelling = self.spelled(target);
172 let symbol = self.names.intern(&spelling);
173 self.aliased.insert(symbol);
174 }
175 }
176
177 /// The bytes of a string literal as a name, which is what a symbol in an attribute is.
178 fn spelled(&self, id: StrId) -> String {
179 self.tast[id].elements.iter().filter_map(|&unit| char::from_u32(unit)).collect()
180 }
181
182 /// One object with static storage duration.
183 fn object(&mut self, decl: DeclId) {
184 let tast = self.tast;
185 let node = &tast[decl];
186 let (ty, state, init) = (node.ty, node.state, node.init);
187 let (linkage, duration, alignment) = (node.linkage, node.duration, node.alignment);
188 let span = tast.decl_span(decl);
189 if duration == StorageDuration::Automatic {
190 // A block-scope object with automatic storage is a slot or a value in the function
191 // that declares it, and the body is what makes it. Nothing is emitted here.
192 return;
193 }
194 // A second name for something else is not an object of its own, so nothing is laid out
195 // and no image is built. It is held back until the rest of the file has been walked,
196 // because what it points at may be below it.
197 if node.alias.is_some() {
198 self.aliases.push(decl);
199 return;
200 }
201
202 let symbol = self.symbol_of(decl);
203 let size = repr::size_of(self.types, self.target, ty);
204 let align = alignment.unwrap_or_else(|| repr::align_of(self.types, self.target, ty));
205 let mut global = Global::new(symbol, size, align);
206 global.linkage = match linkage {
207 Linkage::External => IrLinkage::External,
208 Linkage::Internal | Linkage::None => IrLinkage::Internal,
209 };
210 global.tls = (duration == StorageDuration::Thread).then_some(TlsModel::GlobalDynamic);
211 global.constant = repr::is_read_only(self.types, ty);
212 global.init = match state {
213 // `extern int x;` and nothing else names an object another translation unit
214 // defines. The global is here so that a reference to it has something to resolve
215 // against, and it has no image, which is what makes it a declaration.
216 Definition::Declared => None,
217 Definition::Tentative => Some(self.zeros(size)),
218 Definition::Defined => {
219 let (data, covered) = self.image(init, size, span);
220 // The object is as large as its image when the image is the larger of the two.
221 // A structure whose last member is a flexible array is the only way that
222 // happens: `sizeof` answers without the array and an initializer that fills it
223 // makes an object big enough to hold what was written. C 6.7.2.1p18 leaves the
224 // size to the implementation, gcc grows the object, and this does the same
225 // rather than hand the linker a size the image does not fit in.
226 global.size = size.max(covered);
227 Some(data)
228 }
229 };
230 self.place_global(global);
231 }
232
233 /// One function, with its body when it has one.
234 fn function(&mut self, decl: DeclId) {
235 let tast = self.tast;
236 let node = &tast[decl];
237 let (ty, linkage, body, align) = (node.ty, node.linkage, node.body, node.alignment);
238 let span = tast.decl_span(decl);
239 if node.name.is_none() {
240 return;
241 }
242 // The same as for an object: a second name is not a function of its own, and it is held
243 // back until what it points at has been emitted.
244 if node.alias.is_some() {
245 self.aliases.push(decl);
246 return;
247 }
248 // Which asks the one question the reference to it asks, so that a declaration that
249 // renamed the symbol renames the definition as well and the two still meet.
250 let name = self.symbol_of(decl);
251 if self.is_dropped(decl, name) {
252 return;
253 }
254 let Some(plan) = self.plan(ty, &[], span) else { return };
255
256 let mut func = Func::new(name, plan.signature.clone());
257 func.align = align;
258 func.linkage = match linkage {
259 Linkage::Internal | Linkage::None => IrLinkage::Internal,
260 Linkage::External => IrLinkage::External,
261 };
262 // An inline definition is not an external definition, so what goes in the module is the
263 // declaration and not the body. C 6.7.4p7 says the calls in this unit go to the definition
264 // some other unit holds, which is what the declaration gives them, and glibc's headers
265 // rely on it: every one of their inline definitions would otherwise be a second definition
266 // of a name the library already defines.
267 if body.is_some() && node.inline.emits() {
268 body::lower(self, decl, &mut func, &plan);
269 }
270 self.place_func(func);
271 }
272
273 /// Puts a function in the module under a name something may already be under.
274 ///
275 /// Two declarations of one identifier were merged before this, so the only way one name
276 /// arrives twice is an assembler name that renames one identifier onto another: a
277 /// declaration of `f` renamed to `g` beside a definition of `g` is one symbol written two
278 /// ways, which is what the program asked for and what the linker is going to see. The
279 /// definition wins wherever there is one, since what the declaration is here for is to give
280 /// the calls something to resolve against and the definition does that as well.
281 ///
282 /// A name already carrying a definition keeps it. That is the program defining one symbol
283 /// twice, and the assembler says so with the name in front of it, which is a better message
284 /// than anything available here.
285 fn place_func(&mut self, func: Func) {
286 match self.module.lookup(func.name) {
287 None => {
288 self.module.add_func(func);
289 }
290 Some(SymbolRef::Func(id))
291 if self.module[id].is_declaration() && !func.is_declaration() =>
292 {
293 self.module[id] = func;
294 }
295 Some(_) => {}
296 }
297 }
298
299 /// One declaration that is a second name for something the same file defines.
300 ///
301 /// Emitted after everything else, so the target is looked up in a module that already holds
302 /// whatever the file defines whether it was written above the alias or below it.
303 ///
304 /// The target has to be defined here and not merely declared, which is gcc's rule and is
305 /// what the object format can express: an alias is a symbol at another symbol's address, and
306 /// a name this file does not define has no address for one to be at. A program that writes
307 /// an alias of something in another object wants a reference rather than a definition, and
308 /// what it gets from gcc is this same error rather than a name the linker cannot resolve.
309 fn alias(&mut self, decl: DeclId) {
310 let Some(written) = self.tast[decl].alias else { return };
311 let span = self.tast.decl_span(decl);
312 let name = self.symbol_of(decl);
313 let spelling = self.spelled(written);
314 let target = self.names.intern(&spelling);
315 let spelled = self.names.resolve(name).to_owned();
316 if name == target {
317 let what = format!("'{spelled}' is aliased to itself");
318 self.diagnostics.push(Diagnostic::error(what, span).with_code("E0697"));
319 return;
320 }
321 let defined = match self.module.lookup(target) {
322 Some(SymbolRef::Func(id)) => !self.module[id].is_declaration(),
323 Some(SymbolRef::Global(id)) => self.module[id].init.is_some(),
324 // A chain of them is a thing gcc takes and this does not yet, because resolving one
325 // wants the aliases put in an order that the file they were written in need not be
326 // in. It is reported rather than written out as a name pointing at a name.
327 Some(SymbolRef::Alias(_)) | None => false,
328 };
329 if !defined {
330 let what = format!("'{spelled}' is aliased to undefined symbol '{spelling}'");
331 let note = "the target of an alias has to be defined in this same file, since an \
332 alias is a second name for an address and not a reference to one";
333 let refused = Diagnostic::error(what, span).with_code("E0697");
334 self.diagnostics.push(refused.note(note, span));
335 return;
336 }
337 // Something already under this name, which is the program defining one symbol twice. The
338 // definition that is there stands, the way it does for a function and for an object.
339 if self.module.lookup(name).is_some() {
340 return;
341 }
342 let mut alias = Alias::new(name, target);
343 alias.linkage = match self.tast[decl].linkage {
344 Linkage::Internal | Linkage::None => IrLinkage::Internal,
345 Linkage::External => IrLinkage::External,
346 };
347 self.module.add_alias(alias);
348 }
349
350 /// The same for an object, where a global with no image is the declaration.
351 fn place_global(&mut self, global: Global) {
352 match self.module.lookup(global.name) {
353 None => {
354 self.module.add_global(global);
355 }
356 Some(SymbolRef::Global(id))
357 if self.module[id].init.is_none() && global.init.is_some() =>
358 {
359 self.module[id] = global;
360 }
361 Some(_) => {}
362 }
363 }
364
365 /// Whether this function is one nothing can call, which is the set that is not emitted.
366 ///
367 /// A name with internal linkage is not visible to another translation unit, so a definition
368 /// of one that nothing here refers to is a definition of something that can never run.
369 /// [`reach`](mod@crate::reach) is what worked out which those are, and an attribute that asks
370 /// for the definition to be kept has already been read into the answer.
371 ///
372 /// A second name for it is the one reason to keep it that the walk over the tree cannot see,
373 /// since what an alias points at is a string and not a reference to anything. So the symbol
374 /// is what is asked about here rather than the declaration: an alias names what the linker
375 /// will look for, which is what a declaration that renamed itself with `__asm__` is under.
376 ///
377 /// Nothing is said about it. gcc has `-Wunused-function` for a `static` function nobody
378 /// wrote a call to, which is a warning about the program, and this is not that: the header
379 /// that defines six of them is not the file being compiled and its author is not the person
380 /// reading the output.
381 fn is_dropped(&self, decl: DeclId, symbol: Symbol) -> bool {
382 self.tast[decl].linkage != Linkage::External
383 && !self.reachable.contains(&decl)
384 && !self.aliased.contains(&symbol)
385 }
386
387 /// How everything a call to this function type hands over travels, and [`None`] for one the
388 /// walk cannot make.
389 ///
390 /// `actual` is the types of the arguments at a call site, which matter only past the end of
391 /// the prototype: what a variadic argument does is decided from what was written there, and
392 /// there is no parameter to decide it from. A definition passes nothing for it.
393 pub(crate) fn plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
394 self.plan_with(ty, actual, false, span)
395 }
396
397 /// The same, as the call site sees it rather than as the function does.
398 ///
399 /// The two differ for a type that is not a prototype. An old style definition is the one of
400 /// those that knows what its parameters are, and 6.5.2.2p6 checks a call against a prototype
401 /// and against nothing at all otherwise, so a parameter it disagrees with does not make the
402 /// call wrong and cannot be what the argument travels as either: the value at the call is
403 /// the argument's own type and nothing converted it. So a parameter the argument facing it
404 /// is compatible with is used, which is the usual case and is what makes the call go to the
405 /// name, and one it is not compatible with gives way to what was actually written. A call
406 /// like that is undefined behaviour if control reaches it and the file still has to
407 /// translate, which is the same position [`Body::direct`](crate::body) already takes.
408 pub(crate) fn call_plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
409 self.plan_with(ty, actual, true, span)
410 }
411
412 fn plan_with(
413 &mut self,
414 ty: TypeId,
415 actual: &[TypeId],
416 at_call: bool,
417 span: Span,
418 ) -> Option<Plan> {
419 let canonical = self.types.canonical(ty);
420 let canonical = match self.types.kind(canonical) {
421 // A call goes through a pointer to a function, and the type in hand may be either.
422 TypeKind::Pointer(pointee) => self.types.canonical(pointee),
423 _ => canonical,
424 };
425 let TypeKind::Function(id) = self.types.kind(canonical) else {
426 self.unsupported("a call through something that is not a function", span);
427 return None;
428 };
429 let signature = self.types.signature(id);
430 let ret = signature.ret;
431 // A function declared without a prototype takes what it is given, which is what a
432 // signature with no parameters and no end to them says. C23 removed these and this is
433 // what `int f();` means in every dialect before it.
434 let variadic = signature.variadic || !signature.prototyped;
435 let params = if at_call && !signature.prototyped {
436 // An argument past the end of the list has no parameter to travel as, which is what
437 // a call to an unprototyped function with more arguments than the definition takes
438 // is, so the list ends where the arguments do.
439 signature
440 .params
441 .iter()
442 .zip(actual)
443 .map(|(¶m, &arg)| if compatible(self.types, param, arg) { param } else { arg })
444 .collect()
445 } else {
446 signature.params.clone()
447 };
448
449 match abi::plan(self.types, self.target, ret, ¶ms, actual, variadic) {
450 Ok(plan) => Some(plan),
451 Err(what) => {
452 self.unsupported(what, span);
453 None
454 }
455 }
456 }
457
458 /// The image of an initializer: the entries in ascending order, with the gaps zeroed, and
459 /// how many bytes it covers.
460 ///
461 /// The count is the size that was asked for except when a flexible array member was given
462 /// something to hold, which is the one case where an image is larger than the type it is an
463 /// image of.
464 pub(crate) fn image(
465 &mut self,
466 init: Option<InitList>,
467 size: u64,
468 span: Span,
469 ) -> (DataList, u64) {
470 let Some(init) = init else { return (self.zeros(size), size) };
471 let (data, at) = self.pieces(init, size, span);
472 (self.module.push_data(&data), at)
473 }
474
475 /// The data an image is made of, before it becomes a [`DataList`].
476 ///
477 /// This is apart from [`Self::image`] so that an image can be built inside another one,
478 /// which is what a compound literal used as a value in an initializer needs.
479 fn pieces(&mut self, init: InitList, size: u64, span: Span) -> (Vec<Datum>, u64) {
480 let entries = self.in_image_order(&self.tast[init]);
481 let mut packed = self.packed(&entries, size);
482 let mut data: Vec<Datum> = Vec::with_capacity(entries.len());
483 let mut at = 0;
484 for entry in entries {
485 let piece = self.entry(entry, &mut packed, size);
486 if piece.is_empty() {
487 continue;
488 }
489 let covered: u64 = piece.iter().map(|datum| datum.size(&self.module)).sum();
490 match entry.offset.cmp(&at) {
491 Ordering::Greater => data.push(Datum::Zero(entry.offset - at)),
492 // An entry that begins inside the one before it, which is neither the same
493 // place nor a later one. A union whose members are initialized through two
494 // designators is the way to write it. The earlier bytes are already in the
495 // list and the image cannot take them out again, so this is refused, and
496 // nothing here is wrong enough to drop the rest of the image.
497 Ordering::Less => {
498 self.unsupported("an initializer that writes over an earlier one", span);
499 continue;
500 }
501 Ordering::Equal => {}
502 }
503 at = entry.offset + covered;
504 data.extend(piece);
505 }
506 if at < size {
507 // The tail of a partly initialized object, which C says is zero. So is the tail of
508 // an array the initializer did not fill, and so is every byte of padding.
509 data.push(Datum::Zero(size - at));
510 at = size;
511 }
512 (data, at)
513 }
514
515 /// The entries an image is written from, which is not the order they were written in.
516 ///
517 /// A designator names a place, and the places may be named in any order at all:
518 /// `{ .b = 2, .a = 1 }` is the same object as `{ .a = 1, .b = 2 }` and C says so in as many
519 /// words. An image is bytes in ascending order, so the entries are put in that order here.
520 /// The sort is stable, which is what makes the rest of the rule work: naming one place
521 /// twice is legal and the last of them is the one that stands, so among the entries at one
522 /// offset the written order is kept and all but the last are dropped.
523 ///
524 /// A bit-field is never dropped, because several of them share one offset without writing
525 /// over anything. Which bytes they came to is settled by [`Self::packed`] before this runs
526 /// and the whole run goes in under the first entry that has a bit in it.
527 fn in_image_order(&self, entries: &[InitEntry]) -> Vec<InitEntry> {
528 let mut sorted = entries.to_vec();
529 sorted.sort_by_key(|entry| entry.offset);
530 let mut kept: Vec<InitEntry> = Vec::with_capacity(sorted.len());
531 for entry in sorted {
532 if !entry.is_bit_field() {
533 let over = |last: &InitEntry| last.offset == entry.offset && !last.is_bit_field();
534 while kept.last().is_some_and(over) {
535 kept.pop();
536 }
537 }
538 kept.push(entry);
539 }
540 kept
541 }
542
543 /// What one entry of an initializer puts in the image.
544 ///
545 /// A bit-field is not a datum of its own, because two of them can live in one byte and an
546 /// image is written in bytes. They were put together into their bytes by [`Self::packed`]
547 /// before this ran, and the whole run of bytes goes in under the first entry that lies in
548 /// it, which is why a later one in the same run answers with nothing.
549 ///
550 /// The zeroes at the end of a run are left off it, and a run that is nothing but zeroes
551 /// answers with nothing at all. Either way the gap before the next entry covers them, which
552 /// is the same image and is a smaller one to carry, and it is what keeps an object whose
553 /// bit-fields are all zero in `.bss`. A zero at the front of a run or inside one stays, since
554 /// that is where the run starts and what makes it one run. The run comes out of the map
555 /// whatever is in it, so a later entry lying in it answers with nothing for the usual reason
556 /// rather than writing the run a second time.
557 ///
558 /// An entry is usually one datum and a compound literal read is the reason the answer is a
559 /// list: that entry is a whole object and puts as many data in as the object it is.
560 fn entry(&mut self, entry: InitEntry, packed: &mut BTreeMap<u64, u8>, size: u64) -> Vec<Datum> {
561 if entry.is_bit_field() {
562 let Some(bytes) = take_run(packed, entry.offset) else { return Vec::new() };
563 let Some(last) = bytes.iter().rposition(|&byte| byte != 0) else { return Vec::new() };
564 return vec![Datum::Bytes(self.module.push_bytes(&bytes[..=last]))];
565 }
566 if let Some(literal) = self.literal_read(entry.value) {
567 return self.literal_image(literal, self.tast.expr_span(entry.value));
568 }
569 // How much room is left in the object, which is what a string literal longer than the
570 // array it initializes is cut down to. An entry that begins where the object ends is the
571 // initializer of a flexible array member, and there the object grows to hold what was
572 // written rather than the value being cut to fit, so nothing is taken off it.
573 let room = if entry.offset < size { size - entry.offset } else { u64::MAX };
574 self.datum(entry.value, room).into_iter().collect()
575 }
576
577 /// The compound literal an entry reads, if that is what the entry is.
578 ///
579 /// Reading an object is a node of its own, so a literal used as a value comes through as a
580 /// read of a literal. A literal whose address is taken is not a read and is not this: that
581 /// one folds to an address and goes in as a relocation, with the object it points at emitted
582 /// on its own.
583 fn literal_read(&self, value: ExprId) -> Option<DeclId> {
584 let ExprKind::Convert { kind: Conversion::Lvalue, operand } = self.tast[value].kind else {
585 return None;
586 };
587 match self.tast[operand].kind {
588 ExprKind::CompoundLiteral(decl) => Some(decl),
589 _ => None,
590 }
591 }
592
593 /// The bytes a compound literal contributes where it is read, which are its own image.
594 ///
595 /// The literal has static storage duration here, since a file-scope initializer is the only
596 /// place this is reached from, and C 6.7.11p4 is what lets it stand as a constant element.
597 /// Its own initializer is built at the offset the entry is at, so the parent image ends up
598 /// with the literal's bytes laid into it rather than a name pointing at a second object.
599 fn literal_image(&mut self, literal: DeclId, span: Span) -> Vec<Datum> {
600 let size = repr::size_of(self.types, self.target, self.tast[literal].ty);
601 let Some(init) = self.tast[literal].init else {
602 return if size == 0 { Vec::new() } else { vec![Datum::Zero(size)] };
603 };
604 self.pieces(init, size, span).0
605 }
606
607 /// The bit-fields of an initializer, put together into the bytes they lie in.
608 ///
609 /// Every byte a field lies in is in the map, whatever the bits it put there are. It is
610 /// tempting to leave a zero byte out, on the grounds that what an image does not say is zero
611 /// anyway, and it is wrong: the run a field's bytes make is taken out of the map from the
612 /// byte the field starts at, so a field whose first byte happens to be zero would have its
613 /// whole run left behind and `struct { unsigned f : 20; } x = { 0x12300 };` would read as
614 /// zero. A run that is all zeroes is written as zeroes by [`Self::entry`], so an object that
615 /// really is zero still costs nothing in the image.
616 ///
617 /// A field named twice takes only the bits of the field, so the last of them stands and does
618 /// not read as the two values together.
619 fn packed(&mut self, entries: &[InitEntry], size: u64) -> BTreeMap<u64, u8> {
620 let mut bytes = BTreeMap::new();
621 for entry in entries.iter().filter(|entry| entry.is_bit_field()) {
622 let Some(folded) = self.fold(entry.value) else { continue };
623 let Const::Int(number) = folded else {
624 let span = self.tast.expr_span(entry.value);
625 let what = "a bit-field initialized by something that is not an integer";
626 self.unsupported(what, span);
627 continue;
628 };
629 let width = entry.bit_width;
630 let ones = if width >= 128 { u128::MAX } else { (1u128 << width) - 1 };
631 let mut mask = ones << entry.bit_offset;
632 let mut placed = ((number as u128) & ones) << entry.bit_offset;
633 let mut at = entry.offset;
634 while mask != 0 && at < size {
635 let (bits, keep) = ((placed & 0xff) as u8, !((mask & 0xff) as u8));
636 let byte = bytes.entry(at).or_insert(0);
637 *byte = (*byte & keep) | bits;
638 mask >>= 8;
639 placed >>= 8;
640 at += 1;
641 }
642 }
643 bytes
644 }
645
646 /// One entry of an image, given how many bytes are left in the object it goes in.
647 fn datum(&mut self, value: ExprId, room: u64) -> Option<Datum> {
648 let tast = self.tast;
649 let ty = tast[value].ty;
650 let span = tast.expr_span(value);
651 if let TypeKind::Array { .. } = self.types.kind(self.types.canonical(ty)) {
652 // An array in an initializer is a string literal initializing it, because that is
653 // the only way an array is ever a value. `char s[2] = "hi";` drops the terminator,
654 // which is the one case where the literal is longer than what it initializes, and
655 // the front end has already given the value the type of the array it is filling, so
656 // the type is what says how many of the literal's bytes are part of it. `room` is
657 // still consulted because a flexible array member is filled by a literal that keeps
658 // its own type and there is no size in the object for it to be cut to.
659 let ExprKind::Str(id) = tast[value].kind else {
660 self.unsupported("this initializer", span);
661 return None;
662 };
663 let bytes = tast[id].bytes(self.target);
664 let holds = repr::size_of(self.types, self.target, ty);
665 let take = bytes.len().min(cap(holds)).min(cap(room));
666 return Some(Datum::Bytes(self.module.push_bytes(&bytes[..take])));
667 }
668
669 let size = repr::size_of(self.types, self.target, ty);
670 match self.fold(value)? {
671 Const::Int(number) => {
672 let ty = repr::value_type(self.types, self.target, ty)?;
673 // An integer constant of pointer type is a null pointer constant, which is what
674 // `NULL` is, or an address the program wrote as a number. An image is bytes and
675 // `ptr` says nothing about how many, so it goes in as the integer it is at the
676 // width the target's addresses have. An address the linker has to fill in is
677 // the arm below, and is the only one that stays a pointer.
678 let ty = if ty.is_ptr() { Type::int(self.target.pointer_width) } else { ty };
679 let imm = self.module.add_imm(Imm::int(number, ty));
680 Some(Datum::Scalar { ty, value: imm })
681 }
682 Const::Float(number) => {
683 let ty = repr::value_type(self.types, self.target, ty)?;
684 let imm = self.module.add_imm(Imm::from_bits(number.to_bits()));
685 Some(Datum::Scalar { ty, value: imm })
686 }
687 Const::Address(address) => {
688 let symbol = match address.base {
689 Base::Decl(decl) => {
690 // A compound literal is an object nothing declares, so the address of
691 // one is also the only thing that asks for it to be emitted. Without
692 // this the image names a symbol the module never defines and the link
693 // is what finds out. Anything with a name of its own is left alone,
694 // since the walk over the unit reaches those on its own.
695 if self.tast[decl].name.is_none() {
696 self.local_static(decl);
697 }
698 self.symbol_of(decl)
699 }
700 Base::Str(id) => self.string(id),
701 };
702 let addend = i64::try_from(address.offset).unwrap_or(0);
703 let size = u32::try_from(size).unwrap_or(0);
704 Some(Datum::Addr(self.module.add_reloc(Reloc { symbol, addend, size })))
705 }
706 }
707 }
708
709 /// An image of nothing but zeros, which is what a tentative definition has.
710 fn zeros(&mut self, size: u64) -> DataList {
711 if size == 0 {
712 return DataList::EMPTY;
713 }
714 self.module.push_data(&[Datum::Zero(size)])
715 }
716
717 /// The global a string literal is emitted as, making it the first time it is asked for.
718 pub(crate) fn string(&mut self, id: StrId) -> Symbol {
719 if let Some(&symbol) = self.strings.get(&id) {
720 return symbol;
721 }
722 let literal = &self.tast[id];
723 let bytes = literal.bytes(self.target);
724 let align = literal.encoding.element_width(self.target) / 8;
725 let symbol = self.names.intern(&format!(".Lstr.{}", self.strings.len()));
726
727 let mut global = Global::new(symbol, bytes.len() as u64, align.max(1));
728 global.linkage = IrLinkage::Internal;
729 // Not because the type says so, since a literal is an array of `char` and not of
730 // `const char`, but because writing to one is undefined and every target puts them
731 // somewhere read-only.
732 global.constant = true;
733 let range = self.module.push_bytes(&bytes);
734 global.init = Some(self.module.push_data(&[Datum::Bytes(range)]));
735 self.module.add_global(global);
736 self.strings.insert(id, symbol);
737 symbol
738 }
739
740 /// The name the C library gives a function the program named with the `__builtin_` prefix,
741 /// and nothing for every other name.
742 ///
743 /// `__builtin_abort` is a call to `abort`: the prefix is how a program reaches the function
744 /// the library promises where a macro or a definition of its own has taken the plain name,
745 /// so the two spellings are one function and the one the linker will look for is the short
746 /// one. Which names those are is [`rucc_sema::library_name`]'s to say, since it is the same
747 /// answer the front end declared them out of.
748 fn library_name(&mut self, name: Symbol) -> Option<Symbol> {
749 let library = rucc_sema::library_name(self.names.resolve(name))?;
750 Some(self.names.intern(library))
751 }
752
753 /// The name an object or a function is known by in the object file.
754 pub(crate) fn symbol_of(&mut self, decl: DeclId) -> Symbol {
755 let tast = self.tast;
756 let node = &tast[decl];
757 // The assembler name a declaration wrote, which is the symbol whatever the identifier
758 // spells. It stands for a `static` and for a local one as well as for a name the linker
759 // sees, so it is read before anything else here: a program that renames a name has said
760 // what the symbol is, and the numbering below is for the ones that have not.
761 if let Some(label) = node.asm_label {
762 let spelling: String =
763 tast[label].elements.iter().filter_map(|&unit| char::from_u32(unit)).collect();
764 return self.names.intern(&spelling);
765 }
766 if node.linkage != Linkage::None {
767 let Some(name) = node.name else { return self.names.intern(".Lanon") };
768 return self.library_name(name).unwrap_or(name);
769 }
770 if let Some(&symbol) = self.statics.get(&decl) {
771 return symbol;
772 }
773 // A `static` in a function, or a compound literal with static storage duration. The
774 // number is what makes two of them in two functions two objects.
775 let base = match node.name {
776 Some(name) => self.names.resolve(name).to_string(),
777 None => ".Lanon".to_string(),
778 };
779 let symbol = self.names.intern(&format!("{base}.{}", self.statics.len()));
780 self.statics.insert(decl, symbol);
781 symbol
782 }
783
784 /// Emits the global for an object with static storage duration declared inside a function.
785 pub(crate) fn local_static(&mut self, decl: DeclId) {
786 if !self.done.insert(decl) {
787 return;
788 }
789 match self.tast[decl].kind {
790 // A function declared inside a body is a declaration of the function, not an
791 // object with static storage that happens to be one.
792 DeclKind::Function => self.function(decl),
793 DeclKind::Object => self.object(decl),
794 }
795 }
796
797 /// The value of a constant expression, reporting what folding it reported.
798 fn fold(&mut self, expr: ExprId) -> Option<Const> {
799 let mut eval = Eval::new(self.tast, self.types, self.target, self.names);
800 let folded = eval.constant(expr);
801 let reported = eval.finish();
802 self.diagnostics.extend(reported);
803 match folded {
804 Ok(value) => Some(value),
805 Err(stop) => {
806 if !stop.poisoned {
807 let span = self.tast.expr_span(stop.at);
808 self.unsupported("an initializer this compiler cannot fold", span);
809 }
810 None
811 }
812 }
813 }
814
815 /// Reports a construct the walk does not build IR for yet.
816 pub(crate) fn unsupported(&mut self, what: &str, span: Span) {
817 self.diagnostics.push(
818 Diagnostic::error(format!("{what} is not supported yet"), span).with_code("E0519"),
819 );
820 }
821
822 /// Reports a call to a builtin this compiler knows the name of and does nothing with.
823 ///
824 /// It is its own message rather than [`Self::unsupported`] because the construct is not the
825 /// problem: a call is a call, and what is missing is the one function it goes to. The note is
826 /// what a reader needs, since a builtin is the one name a programmer does not expect to have
827 /// to provide and the alternative to this message is a linker asking them for it.
828 pub(crate) fn missing_builtin(&mut self, spelled: &str, span: Span) {
829 let message = format!("`{spelled}` is not implemented yet");
830 let note = "a call to it would go to a symbol no object file defines, so this is refused \
831 here rather than at the link";
832 self.diagnostics.push(Diagnostic::error(message, span).with_code("E0686").note(note, span));
833 }
834}
835
836/// A count of bytes as a length of a slice of them, saturating on a target whose addresses are
837/// wider than this host's.
838fn cap(bytes: u64) -> usize {
839 usize::try_from(bytes).unwrap_or(usize::MAX)
840}
841
842/// The run of bytes a bit-field entry starts, taken out of the map.
843///
844/// [`None`] when there is no byte at that offset, which means an earlier entry in the same run
845/// already took it, since [`Unit::packed`] puts every byte a field lies in into the map.
846fn take_run(bytes: &mut BTreeMap<u64, u8>, start: u64) -> Option<Vec<u8>> {
847 let mut run = vec![bytes.remove(&start)?];
848 let mut at = start + 1;
849 while let Some(byte) = bytes.remove(&at) {
850 run.push(byte);
851 at += 1;
852 }
853 Some(run)
854}