Skip to main content

rucc_codegen/
elsewhere.rs

1//! Which names this file may not work the address of out for itself.
2//!
3//! Design: `spec/11-asm-objects-debug.md` section 11.3.
4//!
5//! Everything this compiler emits is position independent, so the address of a name is the distance
6//! from the instruction asking to the name, and that distance is a number the assembler leaves a
7//! hole for and the linker fills in. The linker can only fill it in when it is putting both ends in
8//! the same program. A name this file only declares may turn out to be in a shared library, and
9//! then there is no such distance and the link fails rather than guessing one.
10//!
11//! The way round it is a table: the linker gives the name one slot in the global offset table, fills
12//! the slot with whatever address the name ends up at, and the code loads the address out of the
13//! slot instead of working it out. The slot is in this program, so the distance to the slot is a
14//! number the linker has. It costs a load, and the linker takes the load back out again when the
15//! name turns out to have been in this program all along.
16//!
17//! Which names need it is a fact about the whole module and the code generator sees one function at
18//! a time, which is why this is worked out first and handed in rather than asked at the point of
19//! use.
20//!
21//! It is also a fact about which link is coming, which is [`rucc_ir::Pic`] and is why this is built
22//! from more than the module. Under `-fPIC` the link may be one that produces a shared library, and
23//! then a name this file exports is one the dynamic linker may find a different definition of, so
24//! reaching it from the instruction pointer would reach the wrong one. The static linker will not
25//! let that happen quietly: `R_X86_64_PC32` against a name it can see is replaceable is refused
26//! when it is making a shared object, which is how tamnd/rucc#756 was found.
27//!
28//! A thread-local variable is the other name this file cannot work the address of out for itself,
29//! and it is here for the same reason: which names are thread-local is a fact about the module and
30//! the code generator sees one function at a time. It is a harder case than the one above rather
31//! than a variation of it, because there is no address to work out at all. Every thread has its own
32//! copy, so what the link can say is only where the variable sits inside the block a thread gets,
33//! and turning that into an address is something the running program does. See [`Elsewhere::thread`].
34//!
35//! COFF has no global offset table and answers the same question with pointers of its own, one per
36//! name, which is [`Elsewhere::slot`]. A name a declaration said is in another DLL is reached
37//! through the pointer the loader fills in for it, and a variable this file only declares is
38//! reached through a pointer the file writes itself, so that the link may send it to a DLL without
39//! this file having known.
40
41use rucc_base::Symbol;
42use rucc_base::hash::Set;
43use rucc_ir::{AttrSet, Dll, Extra, Linkage, Module, Opcode, Pic, Visibility};
44use rucc_target::ObjectFormat;
45
46/// The names whose address only the linker knows.
47///
48/// Two ways in, and the first one holds whichever link is coming. A function this file only
49/// declares is one, because a function cannot be copied: it has exactly one address that every
50/// object in the program has to agree on, or two pointers to it compare unequal, so the one address
51/// is what the table holds and what everything reads. A variable can be copied, and in an
52/// executable it is, since the linker answers a reference to one another object defines by making
53/// room for it here and copying it there, so the name really does end up somewhere this file can
54/// measure to.
55///
56/// The second way in is `-fPIC`, where the link may be one that produces a shared library and the
57/// copying does not happen. There every replaceable name is in here, defined or not and function or
58/// variable, because the definition the process ends up using may be in another object however
59/// plainly this file defines it. What is not in here is what `-fPIC` costs nothing for: a `static`,
60/// and a name marked hidden or protected, which is the reason `-fPIC -fvisibility=hidden` is the
61/// combination a library that cares about its own speed is built with.
62///
63/// Both ways in are shut on a format with no such table, which is COFF. See `Self::table` for why
64/// the question has a different answer there rather than no answer.
65///
66/// A name this module has never heard of is not in here. Nothing the front end writes produces one,
67/// and treating an unknown name as a function would put the addresses the instrumentation takes of
68/// its own tables through a table of their own for no reason.
69///
70/// A thread-local variable is kept separately and answered by [`Self::thread`], because the two
71/// questions have different answers rather than one being a case of the other: the table slot of an
72/// ordinary name holds its address and the slot of a thread-local holds an offset, and reading
73/// either as though it were the other is a wrong answer rather than a slower one.
74#[derive(Debug, Clone, Default, PartialEq, Eq)]
75pub struct Elsewhere {
76    names: Set<Symbol>,
77    threads: Set<Symbol>,
78    twice: Set<Symbol>,
79    described: bool,
80    indexed: bool,
81    imported: Set<Symbol>,
82    referred: Set<Symbol>,
83}
84
85/// Which pointer a name on COFF is reached through, when it is reached through one.
86///
87/// The code is the same for both, a load of the pointer from the instruction pointer and then the
88/// name's address in a register. What differs is who writes the pointer.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum Slot {
91    /// The one the loader fills in for a name in another DLL, which the import library calls
92    /// `__imp_` and the name. A declaration said `dllimport`, so there is no other way to the name:
93    /// the import library has no stub under the plain name for a variable, and for a function the
94    /// stub is a jump through this same pointer, so going through it here saves the jump.
95    Imported,
96    /// One this file writes itself, called `.refptr.` and the name, for a variable it only
97    /// declares and nothing said was in a DLL.
98    ///
99    /// The variable may still turn out to be in one, and `environ` in the C runtime is one that
100    /// is. Then the address a `lea` would work out is not a distance the linker has, since the DLL
101    /// is loaded wherever it fits, and what it does instead is write a record for the runtime to
102    /// patch the reference with once the DLL is loaded. A four byte reference from the code cannot
103    /// hold an address that far away, and an eight byte pointer in a data section can, so the
104    /// reference the runtime patches is this pointer. Every object that reads the name writes the
105    /// same one in a section of its own that the linker keeps one copy of, which is what gcc and
106    /// clang both do for `x86_64-w64-mingw32`.
107    Referred,
108}
109
110impl Slot {
111    /// The pointer's own name, for a pointer to `name`.
112    #[must_use]
113    pub fn name(self, name: &str) -> String {
114        match self {
115            Self::Imported => format!("__imp_{name}"),
116            Self::Referred => format!(".refptr.{name}"),
117        }
118    }
119}
120
121impl Elsewhere {
122    /// The names that link cannot reach from the instruction pointer.
123    ///
124    /// `copies` is whether the linker answers a reference from the instruction pointer to a
125    /// variable another object defines by copying the variable into the executable. x86-64 does,
126    /// even in a position independent executable. AArch64 and RISC-V do not: GNU ld refuses an
127    /// `adrp` against such a variable when it makes a PIE, which is the default link on every
128    /// distribution, and gcc reads the address out of the table there instead.
129    #[must_use]
130    pub fn of(module: &Module, pic: Pic, format: ObjectFormat, copies: bool) -> Self {
131        let threads = module
132            .globals()
133            .filter(|&id| module[id].tls.is_some())
134            .map(|id| module[id].name)
135            .collect();
136        let twice = module
137            .funcs()
138            .filter(|&id| module[id].attrs.set.contains(AttrSet::RETURNS_TWICE))
139            .map(|id| module[id].name)
140            .collect();
141        let described = format == ObjectFormat::MachO;
142        let indexed = format == ObjectFormat::Coff;
143        let (imported, referred) = Self::pointers(module, format);
144        Self {
145            threads,
146            twice,
147            described,
148            indexed,
149            imported,
150            referred,
151            ..Self::table(module, pic, format, copies)
152        }
153    }
154
155    /// The names COFF reaches through a pointer, as the ones a declaration said are in another DLL
156    /// and the ones this file writes a pointer to itself. Both are empty on every other format.
157    ///
158    /// A variable gets a pointer of this file's own when it is only declared here, the linker may
159    /// see it, and nothing said where it is. A thread-local is left out, since it has no address
160    /// to point at and [`Self::thread`] answers for it. So is a hidden one, which is promised to be
161    /// in this image: clang reaches that one directly and so does this, where gcc still goes
162    /// through a pointer for it. A function never gets one from this file, since the import
163    /// library's stub under the plain name is already an address in this image, and neither
164    /// compiler writes one for a function either.
165    fn pointers(module: &Module, format: ObjectFormat) -> (Set<Symbol>, Set<Symbol>) {
166        if format != ObjectFormat::Coff {
167            return (Set::default(), Set::default());
168        }
169        let funcs = module
170            .funcs()
171            .filter(|&id| module[id].is_declaration() && module[id].dll == Dll::Import)
172            .map(|id| module[id].name);
173        let globals = module
174            .globals()
175            .filter(|&id| module[id].is_declaration() && module[id].tls.is_none())
176            .filter(|&id| module[id].dll == Dll::Import)
177            .map(|id| module[id].name);
178        let referred = module
179            .globals()
180            .filter(|&id| {
181                let global = &module[id];
182                global.is_declaration()
183                    && global.tls.is_none()
184                    && global.dll != Dll::Import
185                    && global.visibility == Visibility::Default
186                    && matches!(global.linkage, Linkage::External | Linkage::Weak)
187            })
188            .map(|id| module[id].name)
189            .collect();
190        (funcs.chain(globals).collect(), referred)
191    }
192
193    /// The half of the above that is about the global offset table, which is the older one.
194    ///
195    /// Empty on a format that has no such table. COFF is the one, and it is not that the question
196    /// goes unanswered there: a name this file only declares is reached from the instruction
197    /// pointer like any other, because whatever supplies it supplies a piece of this image to
198    /// measure to. A name the link resolves out of another object is in the image, and a name that
199    /// comes from a DLL arrives through an import library, which is an archive member holding a
200    /// jump under the plain name, so the name still stands for an address in this image and every
201    /// object that takes it gets the one the linker kept. Measured against gcc 13.2 for
202    /// `x86_64-w64-mingw32`, which writes `leaq other(%rip), %rax` for the address of a function it
203    /// has only seen declared. Asking for a table there instead reached the object writer as a
204    /// relocation it has no way to write, which is what tamnd/rucc#1443 was.
205    ///
206    /// A variable has no stub to stand for it, so one this file only declares is reached through a
207    /// pointer instead, and so is anything a declaration said is in a DLL. Neither is a table the
208    /// linker builds, which is why they are [`Self::slot`] and not in here.
209    fn table(module: &Module, pic: Pic, format: ObjectFormat, copies: bool) -> Self {
210        if format == ObjectFormat::Coff {
211            return Self::default();
212        }
213        let funcs = module.funcs().filter(|&id| {
214            let func = &module[id];
215            func.is_declaration() || pic.replaceable(func.linkage, func.visibility)
216        });
217        // A weak variable nothing here defines is the one variable the copying above does not
218        // cover, since there may be no definition anywhere to copy and then its address is null. The
219        // distance from here to null is not a number the linker has, so lld refuses the
220        // `R_X86_64_PC32` and gcc reads the address out of a slot, which the linker fills with zero.
221        //
222        // Mach-O does no copying at all. `dyld` has no copy relocation, so a variable a library
223        // defines stays in the library and the only way to it is the slot. That is every variable
224        // this file only declares, unless it is hidden and so promised to be in the same image,
225        // and it is what clang writes: `_ext@GOTPAGE` on arm64 and `_ext@GOTPCREL` on x86-64.
226        let uncopied = format == ObjectFormat::MachO || !copies;
227        let globals = module
228            .globals()
229            .filter(|&id| {
230                let global = &module[id];
231                (global.is_declaration()
232                    && (global.linkage == Linkage::Weak
233                        || (uncopied && global.visibility == Visibility::Default)))
234                    || pic.replaceable(global.linkage, global.visibility)
235            })
236            .map(|id| module[id].name);
237        // An alias is a symbol of its own with a linkage and a visibility of its own, so it answers
238        // this for itself the same way it answered the visibility question in #752. What it points
239        // at is a separate name and is decided separately, which is what `weak, alias,
240        // visibility("hidden")` over an exported definition needs.
241        let aliases = module
242            .aliases()
243            .filter(|&id| pic.replaceable(module[id].linkage, module[id].visibility))
244            .map(|id| module[id].name);
245        funcs.map(|id| module[id].name).chain(globals).chain(aliases).collect()
246    }
247
248    /// Whether the address of that name has to be read out of the global offset table.
249    #[must_use]
250    pub fn holds(&self, name: Symbol) -> bool {
251        self.names.contains(&name)
252    }
253
254    /// The pointer the address of that name is read out of on COFF, where it is read out of one.
255    ///
256    /// Asked after [`Self::thread`] and in place of [`Self::holds`], which is never yes on the
257    /// format this is ever yes on.
258    #[must_use]
259    pub fn slot(&self, name: Symbol) -> Option<Slot> {
260        if self.imported.contains(&name) {
261            Some(Slot::Imported)
262        } else if self.referred.contains(&name) {
263            Some(Slot::Referred)
264        } else {
265            None
266        }
267    }
268
269    /// The names this file has to write a pointer of its own for, in the order the module has
270    /// them, which are the ones [`Self::slot`] says are [`Slot::Referred`] and that some function
271    /// here takes the address of.
272    ///
273    /// Asked of the module once its functions have been compiled, because the question is which
274    /// references survived: a read the optimizer took out needs no pointer, and gcc and clang both
275    /// write one only for a name the code still reads. A pointer nothing reads would not be free
276    /// either, since it names the variable and so asks the link to find a definition of it.
277    #[must_use]
278    pub fn referred(&self, module: &Module) -> Vec<Symbol> {
279        Self::read(module, &self.referred)
280    }
281
282    /// The variables a declaration said are in a DLL and that some function here still takes the
283    /// address of, in the order the module has them, which are the ones read through
284    /// [`Slot::Imported`].
285    ///
286    /// Asked once the functions have been compiled, for the reason [`Self::referred`] is. The
287    /// driver hands these to the linker by name on Microsoft's side, which is tamnd/rucc#2182:
288    /// when the static C runtime defines such a variable, `lld-link` makes the pointer itself and
289    /// then throws the variable away as unreferenced, so the pointer holds the image base.
290    #[must_use]
291    pub fn imported_variables(&self, module: &Module) -> Vec<Symbol> {
292        Self::read(module, &self.imported)
293    }
294
295    /// The variables among `names` whose address some function here takes.
296    fn read(module: &Module, names: &Set<Symbol>) -> Vec<Symbol> {
297        if names.is_empty() {
298            return Vec::new();
299        }
300        let mut read = Set::default();
301        for id in module.funcs() {
302            let func = &module[id];
303            for block in func.blocks() {
304                for inst in func.insts(block) {
305                    let data = &func[inst];
306                    if let (Opcode::GlobalAddr, Extra::Symbol(name)) = (data.opcode, data.extra) {
307                        read.insert(name);
308                    }
309                }
310            }
311        }
312        module
313            .globals()
314            .map(|id| module[id].name)
315            .filter(|name| names.contains(name) && read.contains(name))
316            .collect()
317    }
318
319    /// Whether that name is a variable every thread has its own copy of.
320    ///
321    /// Asked before [`Self::holds`] and not instead of it, because the two answers are about
322    /// different things: a thread-local variable that another object may define is still reached
323    /// the same way, since the table slot holds an offset that is the same for every copy and the
324    /// question of whose copy is answered by the segment register rather than by the link.
325    #[must_use]
326    pub fn thread(&self, name: Symbol) -> bool {
327        self.threads.contains(&name)
328    }
329
330    /// Whether a call to that name may come back more than once, because a declaration of it said
331    /// `returns_twice`.
332    ///
333    /// Not a question about addresses like the two above, but it is the same kind of fact: it is
334    /// about the module, the function it changes is a different one from the function it is
335    /// written on, and the code generator sees one function at a time. See
336    /// [`crate::tail::comes_back`] for what the caller does with it.
337    #[must_use]
338    pub fn twice(&self, name: Symbol) -> bool {
339        self.twice.contains(&name)
340    }
341
342    /// Whether a thread-local variable is reached by calling through its descriptor, which is how
343    /// Mach-O does it on both architectures.
344    ///
345    /// The slot the table holds for such a variable is the address of the descriptor rather than an
346    /// offset from the thread pointer, and the first word of the descriptor is a function that takes
347    /// that address and gives back this thread's copy. So there is no thread pointer to add to,
348    /// and the answer is the value the call returns.
349    #[must_use]
350    pub const fn described(&self) -> bool {
351        self.described
352    }
353
354    /// Whether a thread-local variable is reached through the array of `.tls` copies a Windows
355    /// thread keeps, which is how COFF does it. See `crate::select::Indexed`.
356    #[must_use]
357    pub const fn indexed(&self) -> bool {
358        self.indexed
359    }
360}
361
362/// The same set, written out by hand.
363///
364/// [`Elsewhere::of`] is how the driver builds one and is the only way a compilation does. This is
365/// for a test that wants to lower one function and say what is outside the file without building a
366/// module for it to be outside of.
367impl FromIterator<Symbol> for Elsewhere {
368    fn from_iter<T: IntoIterator<Item = Symbol>>(names: T) -> Self {
369        Self { names: names.into_iter().collect(), ..Self::default() }
370    }
371}
372
373impl Elsewhere {
374    /// The same set with those names said to be thread-local, for a test that lowers one function.
375    #[must_use]
376    pub fn with_threads<T: IntoIterator<Item = Symbol>>(mut self, threads: T) -> Self {
377        self.threads = threads.into_iter().collect();
378        self
379    }
380
381    /// The same set with thread-locals reached through a descriptor, for a test that lowers one
382    /// function the way Mach-O would.
383    #[must_use]
384    pub const fn with_descriptors(mut self) -> Self {
385        self.described = true;
386        self
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393
394    use rucc_base::Interner;
395    use rucc_ir::{
396        Alias, Builder, Func, Global, InstData, Linkage, Signature, TlsModel, Visibility,
397    };
398    use rucc_target::{Arch, Env, Os, TargetInfo, Triple};
399
400    /// A module with one of everything: a function with a body and one without, a variable with an
401    /// image and one without, a `static`, a hidden export, an alias and a thread-local.
402    fn module(names: &mut Interner) -> Module {
403        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
404        let mut module = Module::new(names.intern("test.c"), &target);
405        let mut defined = Func::new(names.intern("here"), Signature::new());
406        defined.create_block();
407        module.add_func(defined);
408        module.add_func(Func::new(names.intern("exit"), Signature::new()));
409
410        let mut kept = Global::new(names.intern("kept"), 4, 4);
411        kept.init = Some(module.push_data(&[]));
412        module.add_global(kept);
413        module.add_global(Global::new(names.intern("away"), 4, 4));
414
415        let mut quiet = Global::new(names.intern("quiet"), 4, 4);
416        quiet.init = Some(module.push_data(&[]));
417        quiet.linkage = Linkage::Internal;
418        module.add_global(quiet);
419
420        let mut shy = Global::new(names.intern("shy"), 4, 4);
421        shy.init = Some(module.push_data(&[]));
422        shy.visibility = Visibility::Hidden;
423        module.add_global(shy);
424
425        let mut own = Global::new(names.intern("own"), 4, 4);
426        own.init = Some(module.push_data(&[]));
427        own.tls = Some(TlsModel::GlobalDynamic);
428        module.add_global(own);
429
430        module.add_alias(Alias::new(names.intern("second"), names.intern("here")));
431        module
432    }
433
434    #[test]
435    fn a_variable_every_thread_has_its_own_copy_of_is_one() {
436        let mut names = Interner::new();
437        let module = module(&mut names);
438        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
439        assert!(elsewhere.thread(names.intern("own")));
440    }
441
442    /// The question the other five ask is a different question, and a variable that is not
443    /// thread-local answering yes to this one would put an offset where an address belongs.
444    #[test]
445    fn an_ordinary_variable_is_not() {
446        let mut names = Interner::new();
447        let module = module(&mut names);
448        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
449        for name in ["kept", "away", "quiet", "shy", "here"] {
450            assert!(!elsewhere.thread(names.intern(name)), "{name} was called thread-local");
451        }
452    }
453
454    #[test]
455    fn a_function_this_file_only_declares_is_reached_through_the_table() {
456        let mut names = Interner::new();
457        let module = module(&mut names);
458        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
459        assert!(elsewhere.holds(names.intern("exit")));
460    }
461
462    #[test]
463    fn a_function_this_file_defines_is_not() {
464        let mut names = Interner::new();
465        let module = module(&mut names);
466        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
467        assert!(!elsewhere.holds(names.intern("here")));
468    }
469
470    #[test]
471    fn a_name_the_module_does_not_carry_at_all_is_not() {
472        let mut names = Interner::new();
473        let module = module(&mut names);
474        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
475        assert!(!elsewhere.holds(names.intern("nowhere")));
476    }
477
478    /// The whole of what an executable pays, which is one entry for the one function it calls in a
479    /// library. Every variable is reached from the instruction pointer, the one it does not define
480    /// included, because the linker copies that one in here.
481    #[test]
482    fn an_executable_pays_for_the_functions_and_for_nothing_else() {
483        let mut names = Interner::new();
484        let module = module(&mut names);
485        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
486        for name in ["kept", "away", "quiet", "shy", "second"] {
487            assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
488        }
489    }
490
491    /// A weak variable nothing defines may be at zero, which no distance from the code reaches.
492    #[test]
493    fn a_weak_variable_this_file_only_declares_is_reached_through_the_table() {
494        let mut names = Interner::new();
495        let mut module = module(&mut names);
496        let mut maybe = Global::new(names.intern("maybe"), 4, 4);
497        maybe.linkage = Linkage::Weak;
498        module.add_global(maybe);
499        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
500        assert!(elsewhere.holds(names.intern("maybe")));
501    }
502
503    /// Mach-O never copies a variable into the executable, so the one this file only declares is
504    /// read through the table even in a program, and the ones it defines are still reached
505    /// directly.
506    #[test]
507    fn a_mach_o_executable_pays_for_the_variables_it_does_not_define_as_well() {
508        let mut names = Interner::new();
509        let mut module = module(&mut names);
510        let mut near = Global::new(names.intern("near"), 4, 4);
511        near.visibility = Visibility::Hidden;
512        module.add_global(near);
513        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::MachO, true);
514        assert!(elsewhere.holds(names.intern("away")));
515        for name in ["kept", "quiet", "shy", "near"] {
516            assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
517        }
518    }
519
520    /// An AArch64 executable pays for a variable it only declares, because the linker there makes
521    /// no copy for an `adrp` and refuses one in a PIE. bzip2 reading `stderr` is what found it.
522    #[test]
523    fn an_executable_that_gets_no_copies_pays_for_the_variables_it_does_not_define() {
524        let mut names = Interner::new();
525        let module = module(&mut names);
526        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, false);
527        assert!(elsewhere.holds(names.intern("away")));
528        for name in ["kept", "quiet", "shy"] {
529            assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
530        }
531        let copied = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
532        assert!(!copied.holds(names.intern("away")));
533    }
534
535    /// A library pays for every name it exports, defined here or not, because the definition the
536    /// process uses may be in another object however plainly this file defines it.
537    #[test]
538    fn a_library_pays_for_every_name_something_else_may_define() {
539        let mut names = Interner::new();
540        let module = module(&mut names);
541        let elsewhere = Elsewhere::of(&module, Pic::Library, ObjectFormat::Elf, true);
542        for name in ["here", "exit", "kept", "away", "second"] {
543            assert!(elsewhere.holds(names.intern(name)), "{name} was not in the table");
544        }
545    }
546
547    /// A format with no table asks nothing of anybody, which is not the same as asking and being
548    /// told no. The name of a function this file only declares stands for an address in the image
549    /// on this format whether the link finds it in another object or in an import library, so the
550    /// instruction pointer reaches it and there is nothing left over to put in a table. gcc writes
551    /// the same `leaq other(%rip)` for the same declaration.
552    #[test]
553    fn a_format_with_no_table_puts_nothing_in_one() {
554        let mut names = Interner::new();
555        let module = module(&mut names);
556        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Coff, true);
557        for name in ["here", "exit", "kept", "away", "quiet", "shy", "second"] {
558            assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
559        }
560    }
561
562    /// And the flag that fills the table on the other format does not fill it here either, since
563    /// there is no interposition on this one for it to be about.
564    #[test]
565    fn a_format_with_no_table_does_not_grow_one_under_the_library_flag() {
566        let mut names = Interner::new();
567        let module = module(&mut names);
568        let elsewhere = Elsewhere::of(&module, Pic::Library, ObjectFormat::Coff, true);
569        for name in ["here", "exit", "kept", "away", "second"] {
570            assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
571        }
572    }
573
574    /// The other question this type answers is not the table's, so it keeps its answer whatever the
575    /// format. What a target with no thread-local storage does about it is the writer's refusal
576    /// rather than a name quietly left out here.
577    #[test]
578    fn a_format_with_no_table_still_says_which_variable_every_thread_has_a_copy_of() {
579        let mut names = Interner::new();
580        let module = module(&mut names);
581        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Coff, true);
582        assert!(elsewhere.thread(names.intern("own")));
583    }
584
585    /// And not for the names nothing outside can reach, which is what makes `-fvisibility=hidden`
586    /// worth writing next to it.
587    #[test]
588    fn a_library_pays_nothing_for_a_name_nothing_outside_it_can_see() {
589        let mut names = Interner::new();
590        let module = module(&mut names);
591        let elsewhere = Elsewhere::of(&module, Pic::Library, ObjectFormat::Elf, true);
592        assert!(!elsewhere.holds(names.intern("quiet")));
593        assert!(!elsewhere.holds(names.intern("shy")));
594    }
595
596    /// The module above with the names a Windows program has: a function and a variable a
597    /// declaration said are in a DLL, a variable it only declares and one it said is hidden, and
598    /// a function that reads every variable in it.
599    fn windows(names: &mut Interner) -> Module {
600        let mut module = module(names);
601        let mut pid = Func::new(names.intern("GetCurrentProcessId"), Signature::new());
602        pid.dll = Dll::Import;
603        module.add_func(pid);
604        let mut mode = Global::new(names.intern("_fmode"), 4, 4);
605        mode.dll = Dll::Import;
606        module.add_global(mode);
607        let mut near = Global::new(names.intern("near"), 4, 4);
608        near.visibility = Visibility::Hidden;
609        module.add_global(near);
610        let mut reader = Func::new(names.intern("reader"), Signature::new());
611        let block = reader.create_block();
612        for name in ["kept", "away", "quiet", "_fmode", "near"] {
613            let symbol = names.intern(name);
614            let data =
615                InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) };
616            Builder::new(&mut reader, block).value(data, rucc_ir::Type::PTR);
617        }
618        module.add_func(reader);
619        module
620    }
621
622    /// What a declaration said is in a DLL is reached through the pointer the loader fills in,
623    /// whether it is a function or a variable, and what it said nothing about keeps the plain name
624    /// for a function and gets a pointer of the file's own for a variable.
625    #[test]
626    fn a_name_in_a_dll_is_reached_through_the_pointer_the_loader_fills_in() {
627        let mut names = Interner::new();
628        let module = windows(&mut names);
629        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Coff, true);
630        for name in ["GetCurrentProcessId", "_fmode"] {
631            assert_eq!(elsewhere.slot(names.intern(name)), Some(Slot::Imported), "{name}");
632        }
633        assert_eq!(elsewhere.slot(names.intern("away")), Some(Slot::Referred));
634        for name in ["exit", "here", "kept", "quiet", "shy", "own", "near"] {
635            assert_eq!(elsewhere.slot(names.intern(name)), None, "{name}");
636        }
637        assert_eq!(Slot::Imported.name("_fmode"), "__imp__fmode");
638        assert_eq!(Slot::Referred.name("away"), ".refptr.away");
639    }
640
641    /// A pointer of the file's own is written only for a name some function still reads, so
642    /// `unread`, which is declared the way `away` is and read by nothing, gets none.
643    #[test]
644    fn a_pointer_is_written_only_for_a_variable_the_code_reads() {
645        let mut names = Interner::new();
646        let mut module = windows(&mut names);
647        module.add_global(Global::new(names.intern("unread"), 4, 4));
648        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Coff, true);
649        assert_eq!(elsewhere.referred(&module), vec![names.intern("away")]);
650    }
651
652    /// Every other format has a table of its own and never asks for either pointer.
653    #[test]
654    fn a_format_with_a_table_has_no_pointers() {
655        let mut names = Interner::new();
656        let module = windows(&mut names);
657        let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
658        for name in ["GetCurrentProcessId", "_fmode", "away"] {
659            assert_eq!(elsewhere.slot(names.intern(name)), None, "{name}");
660        }
661        assert!(elsewhere.referred(&module).is_empty());
662    }
663}