Skip to main content

rucc_driver/
compile.rs

1//! Running the front end over one file, from the bytes on disk to the typed tree.
2//!
3//! Design: `spec/04-driver-and-cli.md` section 4.3, and the `M2` exit criterion in
4//! `spec/17-milestones.md` that says `--emit=tast` works.
5//!
6//! [`preprocess`](mod@crate::preprocess) stops after phase 4 because `-E` stops there. This
7//! carries on: phase 7, the parse, and the checking. It is one function rather than four composed
8//! ones because of what the four share. The tokens hold interned symbols, the untyped tree holds
9//! tokens, the typed tree holds the untyped tree's spans, and none of them owns the table it is
10//! reading, so one [`Session`] has to outlive all of them and there has to be one place that
11//! holds it.
12
13use std::path::Path;
14
15use rucc_base::Interner;
16use rucc_codegen::coverage::Fired;
17use rucc_codegen::pipeline::{self, Machine};
18use rucc_diag::{Diagnostic, Severity, Span};
19use rucc_lex::{Convert, Keywords, PpToken, convert};
20use rucc_sema::{Checker, Context as CheckContext};
21use rucc_session::{EmitKind, FileSystem, Options, Session};
22use rucc_target::TargetInfo;
23
24use crate::preprocess::render;
25
26/// What a compilation produced, which is text for most of the kinds and bytes for one of them.
27///
28/// Two variants rather than a string, because an object file is not text and a `Vec<u8>` holding
29/// UTF-8 for six kinds and a file format for the seventh would leave every reader guessing which
30/// it had. [`Artifact::Nothing`] is what a compilation that stopped early gives back, and it is
31/// not the same as an empty file: nothing is written for it at all.
32#[derive(Debug, Clone, PartialEq, Eq, Default)]
33pub enum Artifact {
34    /// The compilation stopped before it produced anything, or the kind asked for produces
35    /// nothing yet.
36    #[default]
37    Nothing,
38    /// Text, which is every kind up to and including assembly.
39    Text(String),
40    /// An object file, which is `-c`.
41    Object(Vec<u8>),
42}
43
44impl Artifact {
45    /// The bytes to write, which is nothing at all for [`Artifact::Nothing`].
46    #[must_use]
47    pub fn bytes(&self) -> &[u8] {
48        match self {
49            Artifact::Nothing => &[],
50            Artifact::Text(text) => text.as_bytes(),
51            Artifact::Object(bytes) => bytes,
52        }
53    }
54}
55
56/// What compiling one file produced.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Compiled {
59    /// What to write, which is nothing when the compilation failed or produced nothing.
60    pub artifact: Artifact,
61    /// The diagnostics, already rendered, one per element, in the order they were reported.
62    pub messages: Vec<String>,
63    /// How many of them were errors.
64    pub errors: u32,
65    /// Which lowering rules this file fired, for `-Zrule-coverage`.
66    ///
67    /// Empty for a compilation that stopped before the back end, which every kind up to and
68    /// including `--emit=ir` does. That is not the same as a rule set nothing reaches and the
69    /// caller unions these rather than reading one, so a file that fired nothing adds nothing.
70    pub fired: Fired,
71    /// What `-fdump-ir=` asked to see, in the order the passes ran.
72    ///
73    /// The optimizer does not write files, because nothing below the driver in
74    /// `spec/18-package-layout.md` knows what a file is, so the text comes back here and the
75    /// caller decides where it goes.
76    pub dumps: Vec<rucc_opt::Dump>,
77    /// What `-fopt-info` asked to hear, already rendered, one remark per line.
78    ///
79    /// Empty when the flag was not given, and also empty when it was given and no pass had
80    /// anything of the kinds asked for to say. Those two are the same text and different facts,
81    /// which is why a misspelled keyword is an error rather than a quiet nothing.
82    pub remarks: String,
83}
84
85impl Compiled {
86    /// Whether anything went wrong badly enough that the output should not be used.
87    #[must_use]
88    pub fn failed(&self) -> bool {
89        self.errors > 0
90    }
91
92    /// The text that was produced, and the empty string for anything that is not text.
93    ///
94    /// A caller that asked for one of the text kinds knows which it asked for, so this saves it
95    /// matching on a variant it has already ruled out.
96    #[must_use]
97    pub fn text(&self) -> &str {
98        match &self.artifact {
99            Artifact::Text(text) => text,
100            _ => "",
101        }
102    }
103}
104
105/// Compiles one file as far as `opts.emit` asks for and renders the result.
106///
107/// `name` is the path as the user wrote it, which is the name every diagnostic about the file
108/// uses. Every kind but the executable produces something today, and that one runs the same front
109/// end and gives back nothing, so that a file with a mistake in it is reported the same way
110/// whichever kind was asked for, rather than compiling silently until the part that is written
111/// notices.
112///
113/// The checking is skipped when the parse reported an error. The two poisoning rules mean a
114/// diagnosed expression produces no further complaints, but a declaration the parser had to skip
115/// past leaves no declaration behind at all, and every later use of that name would be reported
116/// as undeclared. One mistake is worth one message.
117#[must_use]
118pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
119    let mut sess = Session::new(opts.clone());
120    // Before anything else interns a name. The keyword symbols have to be one unbroken run for
121    // a lookup to be a subtraction, and the preprocessor interns every identifier it reads, so
122    // building this after the expansion would mean building it after `char` had been seen.
123    let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
124    let mut diagnostics: Vec<Diagnostic> = Vec::new();
125    // Filled in by the back end when there is one, and empty for every kind that stops before it.
126    let mut fired = Fired::new();
127    // Filled in by the optimizer, and only when `-fdump-ir=` asked for something.
128    let mut dumps = Vec::new();
129    let mut remarks = String::new();
130
131    let bytes = match fs.read(Path::new(name)) {
132        Ok(bytes) => bytes,
133        Err(e) => return failure(format!("{name}: {e}")),
134    };
135    let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
136        return failure(format!("{name}: the source map has no room left for this file"));
137    };
138
139    // Phases 1 to 4. The expanded stream is turned into pp-tokens straight away, because the
140    // include context borrows the source map that rendering a diagnostic reads and the borrow
141    // has to end before anything is rendered.
142    let mut pp = rucc_pp::Preprocessor::new();
143    let predef = rucc_pp::Predef::for_options(opts);
144    let expanded: Vec<PpToken> = {
145        let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
146        cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
147        if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
148            return failure(format!("{name}: the source map has no room for the built in macros"));
149        }
150        pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
151    };
152    diagnostics.extend(pp.take_diagnostics());
153
154    // Phase 7, which is where a spelling becomes a keyword and a preprocessing number becomes
155    // a constant of a type.
156    let cx = Convert {
157        keywords: &keywords,
158        interner: &sess.interner,
159        target: &sess.target,
160        std: opts.std,
161        gnu: opts.gnu_extensions,
162        pedantic: opts.pedantic,
163    };
164    let (tokens, complaints) = convert(&expanded, &cx);
165    diagnostics.extend(complaints);
166
167    let parsed = rucc_parse::parse(
168        &tokens,
169        rucc_parse::Context {
170            interner: &sess.interner,
171            std: opts.std,
172            gnu: opts.gnu_extensions,
173            pedantic: opts.pedantic,
174            error_limit: opts.error_limit as usize,
175        },
176    );
177    let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
178    diagnostics.extend(parsed.diagnostics);
179
180    let mut artifact = Artifact::Nothing;
181    // Zero when nothing instruments, which is the truthful summary of a file built without
182    // `-fsafety`: no checks went in, so none is standing, and every call it makes is unmodelled.
183    let mut instrumented = Instrumented::default();
184    if !parse_failed {
185        let mut checker = Checker::new(
186            &parsed.ast,
187            CheckContext {
188                names: &sess.interner,
189                target: &sess.target,
190                std: opts.std,
191                gnu: opts.gnu_extensions,
192                pedantic: opts.pedantic,
193                error_limit: opts.error_limit as usize,
194                // A freestanding program has no C library, so a name that is the library's
195                // everywhere else is the program's own here and means whatever it defined.
196                builtins: opts.builtins && opts.hosted,
197                no_builtin: &opts.no_builtin,
198            },
199        );
200        checker.check_unit();
201        let checked = checker.finish();
202        if !checked.failed() {
203            match opts.emit {
204                EmitKind::Tast => {
205                    artifact = Artifact::Text(rucc_sema::print(
206                        &checked.tast,
207                        &checked.types,
208                        &sess.interner,
209                    ));
210                }
211                // Nothing past the checker, because a granule is a fact about a layout and a
212                // layout is settled the moment the closing brace is seen. Lowering the
213                // function bodies would take minutes on an amalgamation and answer nothing.
214                EmitKind::TypeGranules => {
215                    artifact = Artifact::Text(rucc_types::granule_report(
216                        &checked.types,
217                        &sess.interner,
218                        &sess.target,
219                    ));
220                }
221                EmitKind::Ir
222                | EmitKind::MirFinal
223                | EmitKind::Asm
224                | EmitKind::Object
225                | EmitKind::Executable
226                | EmitKind::SafetySummary => {
227                    let mut lowered = rucc_lower::lower(
228                        name,
229                        rucc_lower::Context {
230                            tast: &checked.tast,
231                            types: &checked.types,
232                            target: &sess.target,
233                            names: &mut sess.interner,
234                        },
235                    );
236                    // The walk reports what it cannot build, and what it did build is printed
237                    // anyway: a file with one construct missing from it is more use to read
238                    // than nothing at all, and the errors are what stop it being compiled.
239                    let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
240                    if !failed {
241                        // The verifier runs on everything the walk builds, always. It is the
242                        // one check that a bug in the walk cannot talk its way past, and a
243                        // wrong instruction found here costs a message rather than an hour
244                        // in front of a debugger over the assembly it turned into.
245                        if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
246                            for error in errors {
247                                diagnostics.push(internal(&format!("invalid IR, {error}")));
248                            }
249                        } else if let Err(complaints) =
250                            instrument(&mut lowered.module, &mut sess.interner, opts)
251                                .map(|done| instrumented = done)
252                        {
253                            diagnostics.extend(complaints);
254                        } else if let Err(complaints) = optimize(
255                            &mut lowered.module,
256                            &sess.interner,
257                            opts,
258                            name,
259                            &mut dumps,
260                            &mut remarks,
261                        ) {
262                            diagnostics.extend(complaints);
263                        } else if opts.emit == EmitKind::SafetySummary {
264                            // After the optimizer, because the number that matters is how many
265                            // checks are still standing and there is no way to know that before it
266                            // has run. Before the back end, because the back end turns a check into
267                            // a call and a summary of calls is not a summary of checks.
268                            artifact = Artifact::Text(
269                                rucc_safety::summarize(
270                                    &lowered.module,
271                                    &sess.interner,
272                                    name,
273                                    opts.safety.as_str(),
274                                    instrumented.checks,
275                                    instrumented.interposed,
276                                    instrumented.crossings,
277                                )
278                                .render(),
279                            );
280                        } else if opts.emit == EmitKind::Ir {
281                            // After the optimizer rather than before it, so that `--emit=ir -O2`
282                            // is the IR the back end will be given rather than the IR it would
283                            // have been given at `-O0`. There is no other way to see what a pass
284                            // did without reading the assembly it turned into.
285                            artifact =
286                                Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
287                        } else {
288                            // The back end, which is every pass after the IR and which is
289                            // where a construct nothing has a rule for is finally noticed.
290                            match generate(
291                                &mut lowered.module,
292                                &mut sess.interner,
293                                &sess.target,
294                                opts,
295                                &mut fired,
296                            ) {
297                                Ok(made) => artifact = made,
298                                Err(complaints) => diagnostics.extend(complaints),
299                            }
300                        }
301                    }
302                    diagnostics.extend(lowered.diagnostics);
303                }
304                _ => {}
305            }
306        }
307        diagnostics.extend(checked.diagnostics);
308    }
309
310    let mut messages = Vec::with_capacity(diagnostics.len());
311    let mut errors = 0;
312    for diag in &diagnostics {
313        // `-w` drops the warning here rather than at the several hundred places one is raised,
314        // and it drops it before the count, so `-w -Werror` compiles. A warning that was never
315        // raised is not a warning there is anything to promote.
316        if !opts.warnings && diag.severity == Severity::Warning {
317            continue;
318        }
319        if diag.severity.is_fatal()
320            || (diag.severity == Severity::Warning && opts.warnings_are_errors)
321        {
322            errors += 1;
323        }
324        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
325    }
326    if errors > 0 {
327        // A tree built from a file that did not compile is not a tree anything should read.
328        artifact = Artifact::Nothing;
329    }
330    // Kept even when the compilation failed, because a rule that fired did fire and a report about
331    // which rules a corpus reaches should not lose the ones a file with a mistake in it reached.
332    Compiled { artifact, messages, errors, fired, dumps, remarks }
333}
334
335/// Reads one file of IR, checks it, and prints it back.
336///
337/// This is the compiler's own textual IR arriving as an input rather than leaving as an output,
338/// which is what makes the round trip in the M2 exit criterion something to run rather than
339/// something to believe: what the printer wrote is read back, verified, and written again, and
340/// the two files are either the same bytes or they are not.
341///
342/// The verifier runs here for the reason it runs after the walk. A module that was printed by
343/// this compiler has been through it once already, and one that a person edited has not.
344#[must_use]
345pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
346    let mut sess = Session::new(opts.clone());
347    if opts.emit != EmitKind::Ir {
348        return failure(format!(
349            "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
350             the C in front of it became",
351            opts.emit.as_str()
352        ));
353    }
354    let bytes = match fs.read(Path::new(name)) {
355        Ok(bytes) => bytes,
356        Err(e) => return failure(format!("{name}: {e}")),
357    };
358    let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
359        return failure(format!("{name}: this is not text, so it is not IR"));
360    };
361
362    let module = match rucc_ir::parse(text, &mut sess.interner) {
363        Ok(module) => module,
364        Err(error) => {
365            return failure(format!("{name}:{}: {}", error.line, error.message));
366        }
367    };
368    let mut diagnostics: Vec<Diagnostic> = Vec::new();
369    if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
370        for error in errors {
371            diagnostics.push(invalid(&format!("invalid IR, {error}")));
372        }
373    }
374    let mut messages = Vec::with_capacity(diagnostics.len());
375    for diag in &diagnostics {
376        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
377    }
378    let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
379    let artifact = if errors > 0 {
380        Artifact::Nothing
381    } else {
382        Artifact::Text(rucc_ir::print(&module, &sess.interner))
383    };
384    // Nothing here reaches the back end, so no rule fired and there is nothing to record.
385    Compiled {
386        artifact,
387        messages,
388        errors,
389        fired: Fired::new(),
390        dumps: Vec::new(),
391        remarks: String::new(),
392    }
393}
394
395/// Puts the memory safety checks in and redirects the calls that cross the boundary, when
396/// `-fsafety=` asked for them.
397///
398/// Between the walk and the optimizer, which is where section 15.3 of
399/// `spec/safe-memory/15-integration.md` puts it and which is the whole design in one line: the
400/// checks go in while the addresses the program computes still exist, and the optimizer then
401/// discharges the ones it can prove. Every sanitizer that came before instruments after the
402/// optimizer so that its checks cannot be deleted, and pays for all of them forever.
403///
404/// The calls to the C library are redirected here too, and in the same window and for a related
405/// reason. `spec/safe-memory/10-boundaries.md` section 10.3 wants a `memcpy` modelled by a wrapper
406/// that performs the judgements, and `rucc_safety::wrap` is why that has to happen before the
407/// optimizer sees the call rather than after.
408///
409/// The verifier runs again afterwards, for the reason it runs after the walk. This pass rewrites
410/// every function in the module, and a pass that produced IR nothing else accepts should say so
411/// here rather than in the assembly it turned into.
412///
413/// # Errors
414///
415/// When the inserted checks left the module in a state the verifier refuses, which is a bug in
416/// this compiler and not in the program being compiled.
417fn instrument(
418    module: &mut rucc_ir::Module,
419    names: &mut Interner,
420    opts: &Options,
421) -> Result<Instrumented, Vec<Diagnostic>> {
422    if !opts.safety.instruments() {
423        return Ok(Instrumented::default());
424    }
425    let checks = rucc_safety::run(module);
426    // Before the optimizer rather than beside the check lowering, which is what
427    // `rucc_safety::wrap` argues out: `memcpy` is a name an optimizer knows things about, and a
428    // pass that turns a short copy into a pair of loads and stores would leave behind accesses the
429    // check insertion has already finished walking past.
430    let interposed = rucc_safety::redirect(module, names);
431    // After the redirection, so that a call this build models with a wrapper is not also counted
432    // as a crossing it did not model.
433    let crossings = rucc_safety::witness(module, names);
434    match rucc_ir::verify(module, names) {
435        Ok(()) => Ok(Instrumented { checks, interposed, crossings }),
436        Err(errors) => Err(errors
437            .iter()
438            .map(|e| internal(&format!("invalid IR after check insertion, {e}")))
439            .collect()),
440    }
441}
442
443/// What the instrumentation did, which nothing but the summary reads.
444///
445/// Carried out of [`instrument`] rather than recovered from the module afterwards because neither
446/// number survives the optimizer: a check that was discharged leaves nothing behind saying it was
447/// ever there, and a call that was pointed at a wrapper looks like a call that always named one.
448#[derive(Clone, Copy, Debug, Default)]
449struct Instrumented {
450    /// How many checks of each class went in.
451    checks: rucc_safety::Counts,
452    /// How many calls were pointed at an interposition wrapper.
453    interposed: usize,
454    /// How many places a pointer crosses to or from code this build did not instrument.
455    crossings: rucc_safety::Sites,
456}
457
458/// Runs the optimizer over the module, and collects whatever the dumps asked for.
459///
460/// The level chooses a pipeline, the `-f` flags edit it, and at `-O0` there is nothing in it, so
461/// this is a walk over an empty list rather than a branch on the level. See section 9.1 of
462/// `spec/09-optimizer.md` for why the pipelines are written out rather than assembled.
463///
464/// # Errors
465///
466/// When a pass left the module in a state the verifier refuses, which is a bug in the pass and
467/// not in the program being compiled, so it is reported as an internal error the way a bad
468/// lowering is.
469fn optimize(
470    module: &mut rucc_ir::Module,
471    names: &Interner,
472    opts: &Options,
473    file: &str,
474    dumps: &mut Vec<rucc_opt::Dump>,
475    remarks: &mut String,
476) -> Result<(), Vec<Diagnostic>> {
477    let mut settings = rucc_opt::Options::for_level(opts.opt_level);
478    settings.toggles.clone_from(&opts.passes);
479    settings.fuel = opts.pass_fuel.iter().cloned().collect();
480    settings.global_fuel = opts.pass_fuel_global;
481    settings.verify |= opts.verify_each;
482    for (on, spec) in &opts.pass_gates {
483        // Same argument as the dumps below: every spelling in here was checked while the
484        // arguments were parsed, so a rejection now is this compiler disagreeing with itself.
485        if let Err(why) = settings.gates.add(*on, spec) {
486            return Err(vec![internal(&why)]);
487        }
488    }
489    for spec in &opts.dump_ir {
490        // Every spelling in here was checked while the arguments were parsed, so a rejection
491        // now is this compiler disagreeing with itself rather than the command line being wrong.
492        if let Err(why) = settings.dumps.add(spec) {
493            return Err(vec![internal(&why)]);
494        }
495    }
496    let mut wants = rucc_opt::Wants::none();
497    for spec in &opts.opt_info {
498        // Same argument as the dumps above: every spelling was checked while the arguments were
499        // parsed, so a rejection now is the compiler disagreeing with itself.
500        if let Err(why) = wants.add(spec) {
501            return Err(vec![internal(&why)]);
502        }
503    }
504    let report = rucc_opt::run(module, names, &settings);
505    remarks.push_str(&rucc_opt::optinfo::render(file, &report, names, wants));
506    dumps.extend(report.dumps);
507    match report.broke.is_empty() {
508        true => Ok(()),
509        false => Err(report.broke.iter().map(|why| internal(why)).collect()),
510    }
511}
512
513/// Runs the back end over every function in `module` and writes what came out.
514///
515/// One machine function per definition in the module, in the order the module holds them, every
516/// register physical and every frame offset a constant. A declaration has no body and is skipped,
517/// because there is nothing in it to compile.
518///
519/// What the last step is, is the only thing `--emit=mir-final`, `-S` and `-c` disagree about. The
520/// three read the same functions and differ in whether they are printed as machine IR, printed as
521/// assembly, or encoded and put in a file, which is the point of section 11.1 of
522/// `spec/11-asm-objects-debug.md`: a listing that disagrees with the object file beside it is
523/// worse than no listing, and the way to make that impossible is to have one description of an
524/// instruction and two ways of writing it down.
525///
526/// # Errors
527///
528/// One diagnostic per function the back end could not compile, or one about the target when no
529/// back end covers it at all. Every function is attempted rather than stopping at the first, so a
530/// file with three constructs missing from the rule set reports three rather than one at a time.
531fn generate(
532    module: &mut rucc_ir::Module,
533    names: &mut Interner,
534    target: &TargetInfo,
535    opts: &Options,
536    fired: &mut Fired,
537) -> Result<Artifact, Vec<Diagnostic>> {
538    let Some(machine) = Machine::for_target(target) else {
539        return Err(vec![unsupported(&format!(
540            "there is no back end for {} in this compiler yet, so there is nothing to generate",
541            target.triple
542        ))]);
543    };
544    let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
545
546    // The checks become calls here rather than beside the insertion, because the id each one
547    // carries is an index into a table and a row for a check the optimizer deleted is a row nothing
548    // will ever name. Section 6.3.1 of `spec/safe-memory/06-instrumentation.md` is what this
549    // eventually becomes and `rucc_safety::lower` says why it is not that yet.
550    //
551    // It is inside the back end rather than beside the optimizer so that `--emit=ir` still shows
552    // the checks. The IR a person reads should say what the compiler decided, not how it spelled it
553    // for the machine.
554    if opts.safety.instruments() {
555        rucc_safety::lower(module, names);
556        if let Err(errors) = rucc_ir::verify(module, names) {
557            return Err(errors
558                .iter()
559                .map(|e| internal(&format!("invalid IR after check lowering, {e}")))
560                .collect());
561        }
562    }
563
564    let mut funcs = Vec::new();
565    let mut complaints = Vec::new();
566    for id in module.funcs() {
567        if module[id].is_declaration() {
568            continue;
569        }
570        match pipeline::compile_recording(&mut module[id], names, &machine, flags, fired) {
571            Ok(func) => funcs.push(func),
572            Err(why) => {
573                let name = names.resolve(module[id].name).to_owned();
574                // The function knows where the instruction came from, so the message lands on
575                // the line somebody wrote rather than on the file as a whole.
576                let span = why.inst().map_or(Span::DUMMY, |inst| module[id].span(inst));
577                let said = format!("cannot generate code for '{name}': {why}");
578                complaints.push(unsupported_at(&said, span));
579            }
580        }
581    }
582    if !complaints.is_empty() {
583        return Err(complaints);
584    }
585    // The variables the file defines, which go through the back end the way the functions did not:
586    // there is nothing in a variable to select instructions for, so the module is what says what
587    // one is right up to the point where it is written down.
588    // The second names go the same way and for the same reason, and they are neither a function
589    // nor a variable: an alias is an entry in the symbol table and no bytes of anything.
590    let (globals, aliases) = match opts.emit {
591        EmitKind::Asm | EmitKind::Object | EmitKind::Executable => (
592            rucc_asm::globals(module, names).map_err(refused)?,
593            rucc_asm::aliases(module, names).map_err(refused)?,
594        ),
595        _ => (rucc_asm::Globals::default(), Vec::new()),
596    };
597    // A failure in either of the last two is a bug here rather than a program this compiler is
598    // behind on, because every instruction in a function that got this far came out of the same
599    // description both of them read and every register in it has been allocated.
600    match opts.emit {
601        EmitKind::Asm => rucc_asm::print(&funcs, &globals, &aliases, names, target)
602            .map(Artifact::Text)
603            .map_err(refused),
604        // An executable is an object as far as this gets: one is what each file of a link
605        // contributes, and the linker is what turns them into the other.
606        EmitKind::Object | EmitKind::Executable => {
607            let text = rucc_asm::assemble(&funcs, names, target).map_err(refused)?;
608            let data = globals.image();
609            // A format with no writer is a target this compiler is behind on and anything else
610            // the writer refused is a bug here, and the two are not the same news to get.
611            rucc_object::write(&text, &data, &aliases, target).map(Artifact::Object).map_err(
612                |why| match why {
613                    rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
614                    rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
615                },
616            )
617        }
618        _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
619    }
620}
621
622/// What the assembler said, as the kind of news it is.
623///
624/// Two of these are about a program and the rest are about this compiler. A thread-local variable
625/// and an ifunc are both valid C that the back end does not build yet, and everything else the
626/// assembler refuses is something that should never have reached it.
627fn refused(why: rucc_asm::Error) -> Vec<Diagnostic> {
628    match why {
629        rucc_asm::Error::Thread { .. } | rucc_asm::Error::IFunc { .. } => {
630            vec![unsupported(&why.to_string())]
631        }
632        _ => vec![internal(&why.to_string())],
633    }
634}
635
636/// A diagnostic about a program this compiler is not finished enough to compile.
637///
638/// Not an internal error, because nothing here is wrong: the program is valid C and the part of
639/// the back end that would handle it has not been written. The note says so, so that a report
640/// about one of these is filed against the milestone rather than as a miscompilation.
641fn unsupported(message: &str) -> Diagnostic {
642    unsupported_at(message, Span::DUMMY)
643}
644
645/// The same, about somewhere in the file rather than about the file.
646///
647/// The note names the issue tracker rather than `spec/17-milestones.md`, which is a document
648/// about the plan: a reader who follows it wants to know whether the construct in front of them
649/// is already written down as work, and the milestone list does not answer that.
650fn unsupported_at(message: &str, span: Span) -> Diagnostic {
651    Diagnostic::error(message.to_owned(), span)
652        .with_code("E0653")
653        .note("this construct is not lowered yet, see https://github.com/tamnd/rucc/issues", span)
654}
655
656/// A diagnostic about IR that was handed to us rather than built by us.
657fn invalid(message: &str) -> Diagnostic {
658    Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
659}
660
661/// A diagnostic about this compiler rather than about the program it was given.
662fn internal(message: &str) -> Diagnostic {
663    Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
664        .with_code("E0652")
665        .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
666}
667
668/// A result that is nothing but one message, for the failures that happen before there is
669/// anything to compile.
670fn failure(message: String) -> Compiled {
671    Compiled {
672        artifact: Artifact::Nothing,
673        messages: vec![format!("rucc: error: {message}")],
674        errors: 1,
675        fired: Fired::new(),
676        dumps: Vec::new(),
677        remarks: String::new(),
678    }
679}
680
681#[cfg(test)]
682mod tests {
683    use rucc_session::{MemoryFileSystem, Std};
684    use rucc_target::Triple;
685
686    use super::*;
687
688    fn options() -> Options {
689        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
690        opts.emit = EmitKind::Tast;
691        opts
692    }
693
694    fn run(opts: &Options, source: &str) -> Compiled {
695        let mut fs = MemoryFileSystem::new();
696        fs.insert("/main.c", source.to_owned().into_bytes());
697        compile(opts, "/main.c", &fs)
698    }
699
700    /// Options with the compiler's own headers on the search path and nothing else, which is
701    /// what a freestanding compilation is. There is no file system underneath these tests,
702    /// so a header that reached for one would fail to resolve and say so.
703    fn freestanding() -> Options {
704        let mut opts = options();
705        opts.hosted = false;
706        opts.search.push_system(rucc_session::runtime::DIR);
707        opts
708    }
709
710    /// The typed tree of a freestanding `source`, insisting that it compiled cleanly.
711    fn shipped(source: &str) -> String {
712        let result = run(&freestanding(), source);
713        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
714        result.text().to_owned()
715    }
716
717    /// The typed tree of `source`, insisting that it compiled cleanly.
718    fn tast(source: &str) -> String {
719        let result = run(&options(), source);
720        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
721        result.text().to_owned()
722    }
723
724    #[test]
725    fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
726        let text = shipped(concat!(
727            "#include <stdarg.h>\n",
728            "int sum(int n, ...) {\n",
729            "  va_list ap, copy;\n",
730            "  va_start(ap, n);\n",
731            "  va_copy(copy, ap);\n",
732            "  int total = va_arg(ap, int) + va_arg(copy, int);\n",
733            "  va_end(ap);\n",
734            "  va_end(copy);\n",
735            "  return total;\n",
736            "}\n",
737        ));
738        assert!(text.contains("va-start"), "{text}");
739        assert!(text.contains("va-copy"), "{text}");
740        assert!(text.contains("va-arg"), "{text}");
741        assert!(text.contains("va-end"), "{text}");
742    }
743
744    /// glibc includes `<stdarg.h>` this way from every header that declares a `vprintf`, and
745    /// what it wants is the type without the four macro names. Answering the whole header
746    /// would put `va_start` in the way of a program that has its own.
747    #[test]
748    fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
749        let text = shipped(concat!(
750            "#define __need___va_list\n",
751            "#include <stdarg.h>\n",
752            "int vprint(const char *f, __gnuc_va_list ap);\n",
753            "#ifdef va_start\n",
754            "#error va_start should not be defined\n",
755            "#endif\n",
756            "#ifdef _VA_LIST_DEFINED\n",
757            "#error va_list should not have been made\n",
758            "#endif\n",
759        ));
760        assert!(text.contains("vprint"), "{text}");
761    }
762
763    /// The same protocol on `<stddef.h>`, which glibc uses far more heavily: `<stdio.h>` asks
764    /// for `size_t` and `NULL` and would be wrong to receive `offsetof` as well.
765    #[test]
766    fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
767        let text = shipped(concat!(
768            "#define __need_size_t\n",
769            "#include <stddef.h>\n",
770            "#ifdef offsetof\n",
771            "#error offsetof should not be defined yet\n",
772            "#endif\n",
773            "#define __need_ptrdiff_t\n",
774            "#include <stddef.h>\n",
775            "#include <stddef.h>\n",
776            "size_t a;\n",
777            "ptrdiff_t b;\n",
778            "wchar_t c;\n",
779            "max_align_t d;\n",
780            "void *e = NULL;\n",
781            "struct P { int x; long y; };\n",
782            "size_t f = offsetof(struct P, y);\n",
783        ));
784        assert!(text.contains("decl #0 a : unsigned long"), "{text}");
785        assert!(text.contains("decl #1 b : long"), "{text}");
786    }
787
788    #[test]
789    fn the_shipped_limits_and_float_are_the_targets_own_answers() {
790        let text = shipped(concat!(
791            "#include <limits.h>\n",
792            "#include <float.h>\n",
793            "int bits = CHAR_BIT;\n",
794            "long big = LONG_MAX;\n",
795            "int low = INT_MIN;\n",
796            "int radix = FLT_RADIX;\n",
797            "int digits = DBL_MANT_DIG;\n",
798        ));
799        assert!(text.contains("const 8 : int"), "{text}");
800        assert!(text.contains("const 9223372036854775807 : long"), "{text}");
801        assert!(text.contains("const 2 : int"), "{text}");
802        assert!(text.contains("const 53 : int"), "{text}");
803    }
804
805    /// Freestanding, so there is no library header to chain to and `<stdint.h>` writes the
806    /// whole set out itself. The widths are the ones the target picked, which is the only
807    /// reason this header is the compiler's.
808    #[test]
809    fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
810        let text = shipped(concat!(
811            "#include <stdint.h>\n",
812            "int64_t a = INT64_C(1);\n",
813            "uint_least16_t b;\n",
814            "intptr_t c;\n",
815            "uintmax_t d = UINTMAX_MAX;\n",
816            "int wide = sizeof(int_fast64_t);\n",
817        ));
818        assert!(text.contains("decl #0 a : long"), "{text}");
819        assert!(text.contains("decl #1 b : unsigned short"), "{text}");
820        assert!(text.contains("decl #2 c : long"), "{text}");
821    }
822
823    #[test]
824    fn the_three_formality_headers_still_have_to_work() {
825        let text = shipped(concat!(
826            "#include <stdbool.h>\n",
827            "#include <stdalign.h>\n",
828            "#include <iso646.h>\n",
829            "#include <stdnoreturn.h>\n",
830            "int t = true and not false;\n",
831            "_Alignas(16) char buf[16];\n",
832            "int a = alignof(long);\n",
833        ));
834        assert!(text.contains("decl #0 t : int"), "{text}");
835        assert!(text.contains("const 8 : unsigned long"), "{text}");
836    }
837
838    /// Including everything twice has to change nothing, because that is what happens in any
839    /// program large enough to matter and a guard that is wrong shows up nowhere else.
840    #[test]
841    fn every_shipped_header_can_be_included_twice() {
842        let mut source = String::new();
843        for _ in 0..2 {
844            for name in rucc_session::runtime::names() {
845                source.push_str(&format!("#include <{name}>\n"));
846            }
847        }
848        source.push_str("int x;\n");
849        let text = shipped(&source);
850        assert!(text.starts_with("decl #0 x : int"), "{text}");
851    }
852
853    #[test]
854    fn a_file_that_is_not_there_says_so_and_produces_nothing() {
855        let fs = MemoryFileSystem::new();
856        let result = compile(&options(), "/nope.c", &fs);
857        assert!(result.failed());
858        assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
859        assert!(result.text().is_empty());
860    }
861
862    #[test]
863    fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
864        let text = tast("int x = 1;\n");
865        let expected = "\
866decl #0 x : int object external static defined
867  init
868    +0
869      const 1 : int
870";
871        assert_eq!(text, expected);
872    }
873
874    #[test]
875    fn the_macros_are_expanded_before_anything_is_parsed() {
876        // The whole pipeline in one line. The bound came out of a macro, so it was expanded,
877        // converted from a preprocessing number to a constant of a type, parsed as an
878        // expression, and folded to the number the array type carries.
879        let text = tast("#define N 2\nint a[N];\n");
880        assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
881    }
882
883    /// A pragma survives the preprocessor on purpose, since what one means is not its
884    /// business, and nothing after it has a place for a `#` in the grammar. `pack` is the one
885    /// the parser reads and every other line is walked past. Both spellings are here because
886    /// they arrive by different routes and only one of them was ever on a line of its own in
887    /// the source.
888    #[test]
889    fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
890        let text = tast(concat!(
891            "#pragma pack(4)\n",
892            "struct s { int a; };\n",
893            "#pragma pack()\n",
894            "int b;\n",
895            "_Pragma(\"GCC visibility push(default)\") int c;\n",
896        ));
897        assert!(text.contains("decl #0 b : int"), "{text}");
898        assert!(text.contains("decl #1 c : int"), "{text}");
899    }
900
901    /// Every number in these two tests was read off gcc 16 on x86-64 under `-std=gnu23`
902    /// rather than reasoned about, which is why they are written as assertions the program
903    /// makes about itself: a compilation with no messages is every one of them holding.
904    ///
905    /// This half is the attributes. `packed` takes the padding out, on the record or on one
906    /// member, `aligned` raises and never lowers, and the two written together are the
907    /// combination that packs and then aligns the whole thing.
908    #[test]
909    fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
910        tast(concat!(
911            "struct A { char c; int i; } __attribute__((packed));\n",
912            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
913            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
914            // `aligned` with nothing in the parentheses is the largest alignment the target
915            // has, which gcc calls BIGGEST_ALIGNMENT and which is sixteen everywhere here.
916            "struct B { char c; int i; } __attribute__((aligned));\n",
917            "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
918            "struct C { char c; int i __attribute__((packed)); };\n",
919            "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
920            "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
921            "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
922            "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
923            "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
924            "struct E { char c; _Alignas(8) int i; };\n",
925            "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
926            "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
927            "struct F { char c; int i __attribute__((aligned(8))); };\n",
928            "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
929            // Two the record already had, so the attribute asks for nothing new, and two
930            // where four was already there, so the attribute is ignored rather than obeyed.
931            "struct G { char c; short s; } __attribute__((aligned(2)));\n",
932            "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
933            "struct H { char c; int i; } __attribute__((aligned(2)));\n",
934            "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
935            // `packed` on a member takes the padding out in front of that member alone, so on
936            // the first one it does nothing and on the second one it does all of it.
937            "struct I { [[gnu::packed]] char c; int i; };\n",
938            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
939            "struct J { char c; [[gnu::packed]] int i; };\n",
940            "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
941            "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
942            "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
943            "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
944            "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
945            "union L { char c; int i; } __attribute__((packed));\n",
946            "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
947            // The armoured spellings, which are the ones a system header writes, since a
948            // program is entitled to a macro called `packed` and is not entitled to one called
949            // `__packed__`. The two names are one attribute and the layout is the same one.
950            "struct O { char c; int i; } __attribute__((__packed__));\n",
951            "_Static_assert(sizeof(struct O) == 5 && _Alignof(struct O) == 1, \"O\");\n",
952            "struct P { char c; int i; } __attribute__((__aligned__(8)));\n",
953            "_Static_assert(sizeof(struct P) == 8 && _Alignof(struct P) == 8, \"P\");\n",
954        ));
955    }
956
957    /// The same attribute on a declaration rather than on a type, which asks that this object or
958    /// this function be at a multiple of that, and which is where a program that has to hand a
959    /// buffer to hardware or keep two counters off one cache line writes it.
960    ///
961    /// A raise and never a lower, which is the one place it does not agree with `_Alignas`: below
962    /// what the type already has, `_Alignas` is a constraint violation and this is ignored without
963    /// a word. `__alignof__` of the object answers what the object got and not what its type has,
964    /// because that is the question a program asking it is asking.
965    #[test]
966    fn the_aligned_attribute_on_a_declaration_raises_what_that_one_object_is_aligned_to() {
967        tast(concat!(
968            "int v __attribute__((aligned(64)));\n",
969            "_Static_assert(__alignof__(v) == 64, \"v\");\n",
970            // Written on the specifiers rather than after the declarator, which asks the same
971            // thing and is the spelling a header is more likely to use.
972            "__attribute__((aligned(32))) int w;\n",
973            "_Static_assert(__alignof__(w) == 32, \"w\");\n",
974            "[[gnu::aligned(16)]] int x;\n",
975            "_Static_assert(__alignof__(x) == 16, \"x\");\n",
976            // Two below the four an `int` already has, so nothing is asked for and nothing is
977            // said, and the type still answers for the object.
978            "int y __attribute__((aligned(2)));\n",
979            "_Static_assert(__alignof__(y) == 4, \"y\");\n",
980            // A local, which is the same question one scope down.
981            "void f(void) { int a __attribute__((aligned(128)));\n",
982            "_Static_assert(__alignof__(a) == 128, \"a\"); (void)a; }\n",
983            // The type is untouched by any of it: `aligned` on a declaration says where that
984            // declaration goes and says nothing about every other `int` in the program.
985            "_Static_assert(__alignof__(int) == 4, \"int\");\n",
986            // A function, which has no alignment of its own for this to be measured against and
987            // takes whatever was asked for.
988            "void g(void) __attribute__((aligned(256)));\n",
989            "void g(void) {}\n",
990            "_Static_assert(__alignof__(g) == 256, \"g\");\n",
991        ));
992    }
993
994    /// And what the object file says, which is the half that makes the answer above true. A
995    /// function is at a fixed offset inside the text section, so it is at a multiple of two
996    /// hundred and fifty six only if the section is at one too.
997    #[test]
998    fn what_a_declaration_asked_to_be_aligned_to_is_what_the_assembler_is_told() {
999        let text = asm(concat!(
1000            "int v __attribute__((aligned(64)));\n",
1001            "void g(void) __attribute__((aligned(256)));\n",
1002            "void g(void) {}\n",
1003            "void plain(void) {}\n",
1004        ));
1005        assert!(text.contains("\t.p2align\t6\n\t.type\tv, @object\n"), "{text}");
1006        assert!(text.contains("\t.p2align\t8, 0x90\n\t.globl\tg\n"), "{text}");
1007        assert!(text.contains("\t.p2align\t4, 0x90\n\t.globl\tplain\n"), "{text}");
1008    }
1009
1010    /// And the one position where the attribute means something else. On a declaration it raises
1011    /// what that one object is aligned to, and on a typedef it says what the type is aligned to,
1012    /// which gcc lets it lower as well: `typedef int L __attribute__((aligned(2)))` really is an
1013    /// `int` at a multiple of two and a record with one in it really is smaller for it.
1014    ///
1015    /// The size is left alone, which is gcc's answer rather than an omission here. An aligned
1016    /// typedef whose alignment is larger than what it stands for keeps the size it stands for,
1017    /// and gcc refuses an array of one rather than padding the elements out to fit.
1018    #[test]
1019    fn an_aligned_typedef_says_what_an_object_of_it_is_aligned_to_and_may_lower_it() {
1020        tast(concat!(
1021            "typedef int L __attribute__((aligned(2)));\n",
1022            "_Static_assert(__alignof__(L) == 2, \"L\");\n",
1023            "_Static_assert(_Alignof(L) == 2, \"L alignof\");\n",
1024            // Below what an `int` has, which is the half a declaration cannot ask for.
1025            "_Static_assert(sizeof(L) == 4, \"L size\");\n",
1026            "struct T { char c; L x; };\n",
1027            "_Static_assert(sizeof(struct T) == 6, \"T\");\n",
1028            "_Static_assert(__builtin_offsetof(struct T, x) == 2, \"T.x\");\n",
1029            // And upwards, which is the ordinary direction and the one a header writes.
1030            "typedef int H __attribute__((aligned(16)));\n",
1031            "_Static_assert(__alignof__(H) == 16, \"H\");\n",
1032            "_Static_assert(sizeof(H) == 4, \"H size\");\n",
1033            "struct U { char c; H x; };\n",
1034            "_Static_assert(sizeof(struct U) == 32, \"U\");\n",
1035            "_Static_assert(__builtin_offsetof(struct U, x) == 16, \"U.x\");\n",
1036            // A typedef of a typedef, where the nearer one is the one the declaration was
1037            // written with and is the one that answers.
1038            "typedef L M __attribute__((aligned(8)));\n",
1039            "_Static_assert(__alignof__(M) == 8, \"M\");\n",
1040            // And one that asked for nothing, which still has whatever the one behind it asked
1041            // for because it is the same type spelled again.
1042            "typedef L N;\n",
1043            "_Static_assert(__alignof__(N) == 2, \"N\");\n",
1044            // The type it stands for is untouched by any of it.
1045            "_Static_assert(__alignof__(int) == 4, \"int\");\n",
1046        ));
1047        let text = asm(concat!(
1048            "typedef int L __attribute__((aligned(2)));\n",
1049            "typedef int H __attribute__((aligned(16)));\n",
1050            "L low;\n",
1051            "H high;\n",
1052        ));
1053        assert!(text.contains("\t.p2align\t1\n\t.type\tlow, @object\n"), "{text}");
1054        assert!(text.contains("\t.p2align\t4\n\t.type\thigh, @object\n"), "{text}");
1055    }
1056
1057    /// The attribute that builds a type rather than changing a layout. `vector_size(n)` says the
1058    /// declared type is `n` bytes of what was written, taken as lanes, and every operator over
1059    /// one is that operator over each lane.
1060    ///
1061    /// The size is in bytes and not in lanes, which is the part a reader gets backwards: sixteen
1062    /// of `int` is four lanes and sixteen of `char` is sixteen. A vector is aligned to its own
1063    /// size, which is what a machine that has the registers wants and what gcc gives one here.
1064    #[test]
1065    fn the_vector_size_attribute_builds_a_type_of_lanes_and_measures_it_in_bytes() {
1066        tast(concat!(
1067            "typedef int __attribute__((vector_size(16))) v4si;\n",
1068            "_Static_assert(sizeof(v4si) == 16 && _Alignof(v4si) == 16, \"v4si\");\n",
1069            "typedef char __attribute__((vector_size(16))) v16qi;\n",
1070            "_Static_assert(sizeof(v16qi) == 16, \"v16qi\");\n",
1071            // One lane, which is a power of two and is a vector rather than the type it was
1072            // written on: the operators it takes are the vector's and not the scalar's.
1073            "typedef int __attribute__((vector_size(4))) v1si;\n",
1074            "_Static_assert(sizeof(v1si) == 4, \"v1si\");\n",
1075            // The armoured spelling and the bracket one, which are the same attribute.
1076            "typedef float __attribute__((__vector_size__(8))) v2sf;\n",
1077            "_Static_assert(sizeof(v2sf) == 8, \"v2sf\");\n",
1078            "typedef short [[gnu::vector_size(8)]] v4hi;\n",
1079            "_Static_assert(sizeof(v4hi) == 8, \"v4hi\");\n",
1080            // A lane is what a subscript answers with, and a vector is not a pointer: there is
1081            // nothing to decay and the lane type is the one the arithmetic happens in.
1082            "v4si g;\n",
1083            "_Static_assert(sizeof(g[0]) == 4, \"lane\");\n",
1084            "_Static_assert(sizeof(g + g) == 16, \"whole\");\n",
1085            // A scalar beside a vector stands for itself in every lane, so the answer is still
1086            // the vector and not the wider of the two types.
1087            "_Static_assert(sizeof(g + 1) == 16, \"broadcast\");\n",
1088            // An array of them, which is the ordinary way a program holds several.
1089            "_Static_assert(sizeof(v4si[3]) == 48, \"array\");\n",
1090        ));
1091    }
1092
1093    /// A whole vector written into an array of them, and a vector named by a type name rather
1094    /// than by a typedef.
1095    ///
1096    /// Both are the same question asked twice. A vector is filled like an array of its lanes when
1097    /// a list is written into it, so a braced element that is itself a vector has to be taken
1098    /// whole rather than started as the first lane, and the type of what was written is the only
1099    /// thing that says which was meant. And a type name is where a compound literal and a cast
1100    /// spell the type out, which a macro taking a lane type and a lane count does, so the
1101    /// attribute has to be read there and not only on a declaration.
1102    #[test]
1103    fn a_vector_is_written_whole_into_an_array_of_them_and_named_by_a_type_name() {
1104        tast(concat!(
1105            "typedef int __attribute__((vector_size(8))) v2si;\n",
1106            "v2si table[] = { (v2si){ 1, 2 }, (v2si){ 3, 4 } };\n",
1107            "_Static_assert(sizeof(table) == 16, \"two of them and not eight lanes\");\n",
1108            // The size written out rather than named, which is the spelling a macro expands to.
1109            "v2si written = (int __attribute__((vector_size(8)))){ 5, 6 };\n",
1110            "_Static_assert(sizeof((int __attribute__((vector_size(16)))){ 0 }) == 16, \"named\");\n",
1111            // A lane is still a lane, so a list of them fills the vector the way it always did
1112            // and the rule above did not turn brace elision off.
1113            "v2si lanes[2] = { 1, 2, 3, 4 };\n",
1114            "_Static_assert(sizeof(lanes) == 16, \"still elided\");\n",
1115        ));
1116    }
1117
1118    /// A lane written rather than read, and a shift whose two vectors are not the same type.
1119    ///
1120    /// Both are places where a vector is not the aggregate it looks like. A subscript of one is
1121    /// an lvalue because the vector it came from is an object, so a lane can be assigned to and
1122    /// has an address, and a qualifier written on the vector reaches every lane the way it does
1123    /// on an array. And a shift is the one lanewise operator whose sides are not brought to a
1124    /// single type, since the right side counts rather than computes.
1125    #[test]
1126    fn a_lane_is_assignable_and_a_shift_takes_a_count_of_its_own_lane() {
1127        let result = run(
1128            &options(),
1129            concat!(
1130                "typedef int __attribute__((vector_size(16))) v4si;\n",
1131                "typedef unsigned __attribute__((vector_size(16))) v4ui;\n",
1132                "void write(v4si *out, v4ui a, v4si b, int n) {\n",
1133                "  v4si v = { 1, 2, 3, 4 };\n",
1134                "  v[0] = n;\n",
1135                "  v[1] += n;\n",
1136                "  v[2]++;\n",
1137                "  *&v[3] = n;\n",
1138                // The count is signed and the value is not, which no other operator allows.
1139                "  v4ui shifted = a >> b;\n",
1140                "  shifted <<= b;\n",
1141                // A scalar stands in every lane on either side of a shift, which is the half
1142                // that looks wrong: the shape of the answer comes off the count here.
1143                "  *out = v + (v4si)shifted + (1 << b);\n",
1144                "}\n",
1145                // A qualifier on the vector is a qualifier on the lane, so there is nothing here
1146                // to write to.
1147                "void refused(const v4si c) {\n",
1148                "  c[0] = 1;\n",
1149                "}\n",
1150            ),
1151        );
1152        assert_eq!(result.messages.len(), 1, "{:?}", result.messages);
1153        assert!(result.messages[0].contains("assignment of read-only"), "{:?}", result.messages);
1154    }
1155
1156    /// The third layout attribute, and the one that is refused rather than read. Reversing the
1157    /// byte order of every scalar in a record is not something a compiler can do half of, and a
1158    /// compilation that ignored it would lay the record out in the host's order and hand back
1159    /// every field with its bytes the wrong way round. Both spellings are here because a header
1160    /// writes the armoured one, and the member is here because the refusal has to arrive before
1161    /// the layout is used rather than after.
1162    #[test]
1163    fn a_record_that_asks_for_the_other_byte_order_is_refused_rather_than_laid_out_in_this_one() {
1164        let opts = options();
1165        let big = "struct s { int i; } __attribute__((scalar_storage_order(\"big-endian\")));\n";
1166        assert_eq!(
1167            run(&opts, big).messages,
1168            ["/main.c:1:36: error: 'scalar_storage_order' is not implemented yet [E0688]\n\
1169              /main.c:1:36: note: every scalar in this record would be read in the wrong byte \
1170              order"]
1171        );
1172
1173        let armoured =
1174            "struct s { int i; } __attribute__((__scalar_storage_order__(\"little-endian\")));\n";
1175        let messages = run(&opts, armoured).messages;
1176        assert!(messages[0].contains("[E0688]"), "{messages:?}");
1177
1178        // The attribute in front of the body reaches the same list as the one behind it, and
1179        // the C23 spelling in gcc's namespace is the same attribute written a third way.
1180        let front = "struct __attribute__((scalar_storage_order(\"big-endian\"))) s { int i; };\n";
1181        assert!(run(&opts, front).messages[0].contains("[E0688]"), "{front}");
1182        let standard = "struct s { int i; } [[gnu::scalar_storage_order(\"big-endian\")]];\n";
1183        assert!(run(&opts, standard).messages[0].contains("[E0688]"), "{standard}");
1184    }
1185
1186    /// Where a bit-field goes, which packing decides and which is the part of all this that
1187    /// is not what the names suggest. A bit-field goes at the next free bit unless that would
1188    /// make it span more storage than its own type occupies, and then it moves to the next
1189    /// boundary of its alignment. Any packing at all takes that rule out, and `#pragma pack`
1190    /// counts even where it lowers nothing, which is the fourth and seventh cases here.
1191    ///
1192    /// Nothing in the language can be asked where a bit-field is, since `offsetof` refuses one
1193    /// and every size below comes out the same either way, so what is asked is the byte a read
1194    /// of the field loads from.
1195    #[test]
1196    fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
1197        // A `char` field after twelve bits, which will not straddle unpacked and does packed.
1198        assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
1199        assert_eq!(
1200            bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
1201            1
1202        );
1203        assert_eq!(
1204            bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
1205            1
1206        );
1207        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
1208        // A thirty bit field after a byte, which is the case the rule was written for.
1209        assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
1210        assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
1211        // Four is what an `int` asked for anyway, so this caps nothing and still counts.
1212        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
1213        assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
1214    }
1215
1216    /// The byte a read of `s.y` loads from, which is where the bit-field was placed.
1217    fn bit_field_byte(record: &str) -> u64 {
1218        let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
1219        let body = body(&source);
1220        let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
1221        let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
1222        constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
1223    }
1224
1225    /// An attribute in the middle of a specifier list, which is where a member usually carries
1226    /// one and which was read and then thrown away. The `[[...]]` spelling and whatever was
1227    /// written in front of the declaration are collected as the list is walked and the
1228    /// `__attribute__` spelling is put straight on the specifiers, and the two were assigned
1229    /// over each other rather than joined.
1230    #[test]
1231    fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
1232        tast(concat!(
1233            "struct a { char c; __attribute__((aligned(8))) int i; };\n",
1234            "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
1235            "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
1236            "struct b { char c; __attribute__((packed)) int i; };\n",
1237            "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
1238            "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
1239            "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
1240            "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
1241        ));
1242    }
1243
1244    /// The other half, which is `#pragma pack`. It caps a member's alignment where `packed`
1245    /// drops it, so `pack(2)` leaves a `short` where it was and moves an `int`, and it caps a
1246    /// member the program asked to align as well, which is where the two differ. It is read
1247    /// at the closing brace of the body, so a line written in the middle of one settles the
1248    /// whole record rather than the members after it, and `push` and `pop` nest.
1249    #[test]
1250    fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
1251        tast(concat!(
1252            "#pragma pack(1)\n",
1253            "struct A { char c; int i; };\n",
1254            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
1255            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
1256            "#pragma pack()\n",
1257            "struct B { char c; int i; };\n",
1258            "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
1259            "#pragma pack(2)\n",
1260            "struct C { char c; int i; double d; };\n",
1261            "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
1262            "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
1263            // A member the program aligned, which `pack` caps and `packed` would not.
1264            "struct K { char c; int i __attribute__((aligned(8))); };\n",
1265            "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
1266            "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
1267            // The record's own `aligned` is not a member's, so it is not capped.
1268            "struct J { char c; int i; } __attribute__((aligned(8)));\n",
1269            "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
1270            "#pragma pack()\n",
1271            "#pragma pack(push, 1)\n",
1272            "struct D { char c; short s; };\n",
1273            "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
1274            "#pragma pack(pop)\n",
1275            "struct E { char c; short s; };\n",
1276            "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
1277            // Written in the middle of a body, and it still settles the whole record.
1278            "struct H { char c;\n",
1279            "#pragma pack(1)\n",
1280            "  int i; };\n",
1281            "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
1282            "#pragma pack(1)\n",
1283            "struct I { char c;\n",
1284            "#pragma pack()\n",
1285            "  int i; };\n",
1286            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
1287            "#pragma pack()\n",
1288            // Nested pushes, each one giving back what the one under it had.
1289            "#pragma pack(push, 8)\n",
1290            "#pragma pack(push, 1)\n",
1291            "struct P { char c; int i; };\n",
1292            "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
1293            "#pragma pack(pop)\n",
1294            "struct Q { char c; int i; };\n",
1295            "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
1296            "#pragma pack(pop)\n",
1297            // A cap above what every member already asks for changes nothing at all.
1298            "#pragma pack(16)\n",
1299            "struct R { char c; int i; };\n",
1300            "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
1301            "#pragma pack()\n",
1302            "#pragma pack(1)\n",
1303            "struct S { char c; int i : 5; int j : 20; };\n",
1304            "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
1305            "union T { char c; int i; };\n",
1306            "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
1307            "#pragma pack()\n",
1308        ));
1309    }
1310
1311    /// A line the reader cannot make sense of is a warning and the line is dropped, which is
1312    /// what GCC does with one, and these are its words for each of them. The last line is the
1313    /// one nothing else would reach, since it stands after every record in the file.
1314    #[test]
1315    fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
1316        let result = run(
1317            &options(),
1318            concat!(
1319                "#pragma pack 4\n",
1320                "#pragma pack(pop)\n",
1321                "#pragma pack(3)\n",
1322                "#pragma pack(1) junk\n",
1323                "#pragma pack(push, 1\n",
1324                "#pragma pack(x)\n",
1325                // These two are well formed and say nothing. Zero is how a line asks for the
1326                // target's own alignments back without writing empty parentheses.
1327                "#pragma pack(0)\n",
1328                "#pragma pack(push)\n",
1329                "struct s { char c; int i; };\n",
1330                "#pragma pack(pop)\n",
1331                "#pragma pack(pop, foo)\n",
1332            ),
1333        );
1334        let expected = [
1335            "missing `(` after `#pragma pack` - ignored",
1336            "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
1337            "alignment must be a small power of two, not 3",
1338            "junk at end of `#pragma pack`",
1339            "malformed `#pragma pack(push[, id][, <n>])` - ignored",
1340            "unknown action `x` for `#pragma pack` - ignored",
1341            "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
1342        ];
1343        assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
1344        for (message, want) in result.messages.iter().zip(expected) {
1345            assert!(message.contains(want), "expected {want:?} in {message:?}");
1346        }
1347    }
1348
1349    /// The two typedef spellings of the 128 bit types. gcc offers them as keywords rather
1350    /// than as typedefs in a header, which is the only way a program that includes nothing at
1351    /// all can still use them, and Apple's `<mach/arm/_structs.h>` is one such program.
1352    #[test]
1353    fn the_wide_integer_answers_to_all_three_of_its_names() {
1354        let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
1355        assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
1356        assert!(text.contains("decl #1 b : __int128"), "{text}");
1357        assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
1358    }
1359
1360    #[test]
1361    fn every_conversion_the_language_performs_is_a_node_in_the_output() {
1362        // The point of a typed tree. The source has one operator and the output has the
1363        // widening that operator asked for, spelled out, so that nothing downstream has to
1364        // work out the conversion rules a second time.
1365        let text = tast("long f(int a, long b) { return a + b; }\n");
1366        assert!(text.contains("convert arithmetic"), "{text}");
1367    }
1368
1369    #[test]
1370    fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
1371        for source in [
1372            "#error stop\n",
1373            "int f(void) { return 1 + ; }\n",
1374            "int f(void) { return undeclared; }\n",
1375        ] {
1376            let result = run(&options(), source);
1377            assert!(result.failed(), "expected this to fail:\n{source}");
1378            assert!(
1379                result.text().is_empty(),
1380                "a file that did not compile wrote a tree:\n{source}"
1381            );
1382        }
1383    }
1384
1385    #[test]
1386    fn one_undeclared_name_is_one_message_and_not_one_per_use() {
1387        // The poisoning rule from `spec/06-lexer-and-parser.md` section 6.8, seen from the
1388        // outside. Three uses of a name that was never declared, and the operators over them
1389        // say nothing at all.
1390        let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
1391        assert_eq!(result.errors, 1, "{:?}", result.messages);
1392    }
1393
1394    #[test]
1395    fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
1396        // The reason the checking is skipped after a failed parse. The parser gave up on the
1397        // first line and there is no `x` in the tree, so a checker run over it would report
1398        // every use of `x` below as undeclared, which is a second message about one mistake.
1399        let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
1400        assert_eq!(result.errors, 1, "{:?}", result.messages);
1401    }
1402
1403    #[test]
1404    fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
1405        let source = "int f(void) { char c = 300; return c; }\n";
1406        let plain = run(&options(), source);
1407        assert_eq!(plain.errors, 0, "{:?}", plain.messages);
1408        assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
1409        assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
1410
1411        let mut opts = options();
1412        opts.warnings_are_errors = true;
1413        let strict = run(&opts, source);
1414        assert!(strict.failed());
1415        assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
1416        for message in &strict.messages {
1417            assert!(!message.contains("warning:"), "{message}");
1418        }
1419    }
1420
1421    #[test]
1422    fn w_drops_the_warning_before_werror_can_promote_it() {
1423        let source = "int f(void) { char c = 300; return c; }\n";
1424        let mut opts = options();
1425        opts.warnings = false;
1426        let quiet = run(&opts, source);
1427        assert_eq!(quiet.messages, Vec::<String>::new());
1428        assert_eq!(quiet.errors, 0);
1429        assert!(!quiet.text().is_empty(), "and the file still compiles");
1430
1431        // A build that passes both means it wants neither, and the order it wrote them in is not
1432        // something to make it think about.
1433        opts.warnings_are_errors = true;
1434        let both = run(&opts, source);
1435        assert_eq!(both.messages, Vec::<String>::new());
1436        assert!(!both.failed(), "-w -Werror is not an error about a warning nobody saw");
1437    }
1438
1439    #[test]
1440    fn the_dialect_reaches_the_keywords_and_the_checking() {
1441        // `typeof` is C23's and GNU's, so the same source is a declaration under one dialect
1442        // and a mistake under the other, which is the keyword table being built per dialect.
1443        let source = "typeof(1) x;\n";
1444        let mut opts = options();
1445        opts.std = Std::C23;
1446        opts.gnu_extensions = false;
1447        assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
1448
1449        opts.std = Std::C17;
1450        assert!(run(&opts, source).failed());
1451    }
1452
1453    #[test]
1454    fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
1455        let mut opts = options();
1456        opts.emit = EmitKind::Object;
1457        let result = run(&opts, "int x = 1;\n");
1458        assert!(!result.failed(), "{:?}", result.messages);
1459        assert!(result.text().is_empty());
1460        // And it still finds what the checking finds, so a later kind on a broken file is not
1461        // a silent success.
1462        assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
1463    }
1464
1465    /// The machine code of `source`, insisting that it compiled cleanly.
1466    fn mir(source: &str) -> String {
1467        let mut opts = options();
1468        opts.emit = EmitKind::MirFinal;
1469        let result = run(&opts, source);
1470        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1471        result.text().to_owned()
1472    }
1473
1474    /// The whole compiler in one assertion, which is what this emit kind is for.
1475    ///
1476    /// C in, machine instructions out, every register a real one and every frame offset a
1477    /// number. Everything between the two is checked somewhere else, one pass at a time. What is
1478    /// checked here is that the passes are joined up and that the driver runs them.
1479    #[test]
1480    fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
1481        let text = mir("int add(int a, int b) { return a + b; }\n");
1482        assert!(text.starts_with("mfunc @add {"), "{text}");
1483        assert!(text.contains("x64.add_rr_32"), "{text}");
1484        assert!(text.contains("x64.ret"), "{text}");
1485        // A virtual register is what the allocator was there to remove, so one left in the
1486        // output is the difference between code and something that looks like code.
1487        assert!(!text.contains('%'), "{text}");
1488    }
1489
1490    /// A declaration has no body, so there is nothing to generate for one and nothing is.
1491    #[test]
1492    fn a_function_with_no_body_produces_no_machine_function() {
1493        let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1494        assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1495        assert!(text.contains("mfunc @f {"), "{text}");
1496        assert!(text.contains("x64.call"), "{text}");
1497    }
1498
1499    /// Two functions come out in the order the module holds them, which is source order.
1500    #[test]
1501    fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1502        let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1503        let first = text.find("mfunc @a").expect("the first function");
1504        let second = text.find("mfunc @b").expect("the second function");
1505        assert!(first < second, "{text}");
1506    }
1507
1508    /// The target reaches the back end, so the same C is different instructions on Windows.
1509    #[test]
1510    fn the_target_decides_which_convention_the_generated_code_follows() {
1511        let mut opts = options();
1512        opts.emit = EmitKind::MirFinal;
1513        let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1514        assert!(linux.contains("$rdi"), "{linux}");
1515
1516        opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1517        let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1518        assert!(windows.contains("$rcx"), "{windows}");
1519        assert!(!windows.contains("$rdi"), "{windows}");
1520    }
1521
1522    /// A target with no back end says so rather than generating something for another machine.
1523    #[test]
1524    fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1525        let mut opts = options();
1526        opts.emit = EmitKind::MirFinal;
1527        opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1528        let result = run(&opts, "int f(int a) { return a; }\n");
1529        assert!(result.failed());
1530        assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1531        assert!(result.text().is_empty());
1532    }
1533
1534    /// A construct the rule set does not reach yet is named, along with the function it is in.
1535    ///
1536    /// The message is about this compiler being unfinished rather than about the program, which
1537    /// is valid C either way, so it carries the note that says where the work is tracked. Both
1538    /// functions are attempted, so a file that is ahead of the back end in three places says so
1539    /// three times rather than one recompilation at a time.
1540    #[test]
1541    fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1542        let mut opts = options();
1543        opts.emit = EmitKind::MirFinal;
1544        let source = "long double a(long double x) { return x; }\n\
1545                      long double b(long double x) { return x; }\n";
1546        let result = run(&opts, source);
1547        assert!(result.failed());
1548        assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1549        assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1550        assert!(result.messages[0].contains("x87 stack"), "{:?}", result);
1551        assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1552        assert!(result.text().is_empty());
1553    }
1554
1555    /// An opcode the rule language has no word for is named anyway, and pointed at.
1556    ///
1557    /// The rule language's spelling is the better name when there is one, but an opcode it has
1558    /// no word for is exactly the opcode no rule lowers, so falling back to the opcode and the
1559    /// type is what makes the message say anything at all in the cases that happen. The span is
1560    /// the instruction's own, so the message lands on the line rather than on the file.
1561    #[test]
1562    fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1563        let mut opts = options();
1564        opts.emit = EmitKind::MirFinal;
1565        let result = run(&opts, "int f(int a) {\n  __int128 wide = a;\n  return (int) wide;\n}\n");
1566        assert!(result.failed());
1567        assert!(
1568            result.messages[0].contains("no rule lowers a `sext` producing a `i128`"),
1569            "{result:?}"
1570        );
1571        assert!(result.messages[0].contains(":2:"), "the line the widening is on: {result:?}");
1572        assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1573    }
1574
1575    /// The note names the issue tracker, which is where a reader finds out whether it is known.
1576    #[test]
1577    fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1578        let mut opts = options();
1579        opts.emit = EmitKind::MirFinal;
1580        let result = run(&opts, "int f(int a) { __int128 wide = a; return (int) wide; }\n");
1581        assert!(result.failed());
1582        let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1583        assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1584        assert!(!note.contains("spec/17-milestones.md"), "{note}");
1585    }
1586
1587    /// The two frame flags reach the frame, which is the only thing either of them does.
1588    #[test]
1589    fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1590        let source = "int f(int a) { return a; }\n";
1591        assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1592
1593        let mut opts = options();
1594        opts.emit = EmitKind::MirFinal;
1595        opts.frame_pointer = true;
1596        let kept = run(&opts, source).text().to_owned();
1597        assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1598    }
1599
1600    /// The assembly of `source`, insisting that it compiled cleanly.
1601    fn asm(source: &str) -> String {
1602        let mut opts = options();
1603        opts.emit = EmitKind::Asm;
1604        let result = run(&opts, source);
1605        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1606        result.text().to_owned()
1607    }
1608
1609    /// `-S`, which is the same compiler as the kind above it with a different last step.
1610    ///
1611    /// What the assembly says is checked in `rucc-asm`, one instruction at a time and against the
1612    /// target's own description of what an instruction is. What is checked here is that a C file
1613    /// goes all the way to a listing an assembler would take, which means the directives around
1614    /// the function as well as the instructions in it.
1615    #[test]
1616    fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1617        let text = asm("int add(int a, int b) { return a + b; }\n");
1618        assert!(text.contains("\t.globl\tadd\n"), "{text}");
1619        assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1620        assert!(text.contains("\nadd:\n"), "{text}");
1621        assert!(text.contains("\taddl\t"), "{text}");
1622        assert!(text.contains("\tret\n"), "{text}");
1623        assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1624        // Without this the stack the program runs on is executable, which is not a default
1625        // anybody chose and is not a thing a reader would notice missing.
1626        assert!(text.contains(".note.GNU-stack"), "{text}");
1627    }
1628
1629    /// A call through a function pointer, which is a different instruction from a call to a name.
1630    ///
1631    /// Both are in the one function on purpose. What is being read is that the two calls are told
1632    /// apart all the way down: one carries a name the linker resolves and one carries a register,
1633    /// and neither turns into the other on the way.
1634    #[test]
1635    fn a_call_through_a_function_pointer_goes_through_the_register_it_is_in() {
1636        let text = asm("int g(int);\nint f(int (*p)(int), int a) { return p(a) + g(a); }\n");
1637        assert!(text.contains("\tcall\t*%"), "{text}");
1638        assert!(text.contains("\tcall\tg\n"), "{text}");
1639        // The address arrived in the first argument register and the argument the call passes has
1640        // to end up there, so the two cannot be the same register and the compiler has to have
1641        // moved one of them.
1642        assert!(text.contains("%rdi"), "{text}");
1643    }
1644
1645    /// A name at file scope, which is the one address a function cannot compute for itself.
1646    #[test]
1647    fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1648        let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1649        assert!(text.contains("\tleaq\tcounter(%rip), "), "{text}");
1650    }
1651
1652    /// A cast between a pointer and an integer as wide as one, which is every one C writes here.
1653    #[test]
1654    fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1655        let text = asm("long f(void *p) { return (long)p; }\n");
1656        // Every instruction in the body is a full width move or the return. The copies are the
1657        // allocator taking no hints, and what matters here is what is not among them: nothing
1658        // narrows the value and nothing widens it again, which is what a cast that did something
1659        // would look like.
1660        for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1661            let mnemonic = line.split_whitespace().next().unwrap_or("");
1662            assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1663        }
1664    }
1665
1666    /// The arguments past the sixth arrive in the caller's memory rather than in a register, and
1667    /// where that memory is depends on what the prologue did, so this is checked at the end of the
1668    /// pipeline rather than in the middle of it.
1669    #[test]
1670    fn an_argument_past_the_last_register_is_read_out_of_the_caller_s_stack() {
1671        let six = "long a, long b, long c, long d, long e, long f";
1672        let text = asm(&format!("long f({six}, long g, long h) {{ return g + h; }}\n"));
1673
1674        // Nothing is pushed and no frame is taken, so the only thing between the stack pointer and
1675        // the caller's arguments is the return address the call pushed. Which is where gcc 16.2.0
1676        // reads them from too, at `-O0`, in the same two instructions.
1677        assert!(text.contains("\tmovq\t8(%rsp), "), "{text}");
1678        assert!(text.contains("\tmovq\t16(%rsp), "), "{text}");
1679
1680        // A narrower one is read at its own width, because the bits above it are bits the
1681        // convention says nothing about, and one in the other register file with the other file's
1682        // instruction.
1683        let narrow = asm(&format!("int f({six}, int g) {{ return g; }}\n"));
1684        assert!(narrow.contains("\tmovl\t8(%rsp), "), "{narrow}");
1685        let eight =
1686            "double a, double b, double c, double d, double e, double f, double g, double h";
1687        let float = asm(&format!("double f({eight}, double i) {{ return i; }}\n"));
1688        assert!(float.contains("\tmovsd\t8(%rsp), "), "{float}");
1689    }
1690
1691    /// The other end of the same thing. What the caller writes is at the stack pointer, because
1692    /// that is the bottom of its frame and the bottom of its frame is where the callee looks.
1693    #[test]
1694    fn a_call_writes_the_arguments_with_no_register_left_at_the_stack_pointer() {
1695        let six = "1, 2, 3, 4, 5, 6";
1696        let decl = "long g(long, long, long, long, long, long, long, long);\n";
1697        let text = asm(&format!("{decl}long f(void) {{ return g({six}, 7, 8); }}\n"));
1698
1699        assert!(text.contains("\tmovq\t%"), "{text}");
1700        assert!(text.contains(", (%rsp)\n"), "{text}");
1701        assert!(text.contains(", 8(%rsp)\n"), "{text}");
1702        // And it reserved the bytes it wrote into, so nothing else in the frame is on top of them.
1703        assert!(text.contains("\tsubq\t$"), "{text}");
1704
1705        // A narrower one is written at its own width, matching what the callee reads it back with.
1706        let narrow = "int g(int, int, int, int, int, int, int);\n";
1707        let text = asm(&format!("{narrow}int f(void) {{ return g({six}, 7); }}\n"));
1708        assert!(text.contains("\tmovl\t%"), "{text}");
1709        assert!(text.contains(", (%rsp)\n"), "{text}");
1710    }
1711
1712    /// The count a variadic callee on this convention reads is a count of vector registers, so a
1713    /// float that ran out of them and went to memory is not in it.
1714    #[test]
1715    fn a_variadic_call_counts_registers_and_not_arguments() {
1716        let nine = "1., 2., 3., 4., 5., 6., 7., 8., 9.";
1717        let decl = "int g(int, ...);\n";
1718        let text = asm(&format!("{decl}int f(void) {{ return g(0, {nine}); }}\n"));
1719
1720        assert!(text.contains("\tmovl\t$8, "), "eight registers, not nine: {text}");
1721        assert!(text.contains("\tmovsd\t%"), "{text}");
1722        assert!(text.contains(", (%rsp)\n"), "{text}");
1723    }
1724
1725    /// The callee's half of the same convention. Every argument register it was handed is written
1726    /// into its frame on the way in, because which of them hold anything is a thing only the caller
1727    /// knew, and the ones the signature does name are left out because `va_start` sets the offsets
1728    /// past them and nothing ever reads their slots.
1729    #[test]
1730    fn a_variadic_function_writes_the_argument_registers_it_was_handed_into_its_frame() {
1731        let body =
1732            "__builtin_va_list ap; __builtin_va_start(ap, n); __builtin_va_end(ap); return n;";
1733        let text = asm(&format!("int f(int n, ...) {{ {body} }}\n"));
1734
1735        // Five general purpose registers and eight vector ones, since the one parameter the
1736        // signature names took the first of the six.
1737        let stores = |mnemonic: &str| text.matches(&format!("\t{mnemonic}\t%")).count();
1738        assert!(text.contains(", 8(%r"), "the second slot, not the first: {text}");
1739        assert!(!text.contains(", 0(%r"), "{text}");
1740        assert_eq!(stores("movsd"), 8, "every vector register: {text}");
1741
1742        // And the area is one of the function's own stack objects, so the frame holds it.
1743        assert!(text.contains("\tsubq\t$"), "{text}");
1744    }
1745
1746    /// What `va_start` writes is the four fields of the list, and the two numbers among them are
1747    /// where the arguments the signature names left the walk over each file's registers.
1748    #[test]
1749    fn va_start_writes_the_four_fields_the_psabi_describes() {
1750        let start = "__builtin_va_list ap; __builtin_va_start(ap, d);";
1751        let params = "int a, int b, int c, double d";
1752        let text = asm(&format!("int f({params}, ...) {{ {start} return a; }}\n"));
1753
1754        // Three integers took three of the six general purpose registers, and one double took one
1755        // of the eight vector ones, so the walk starts at twenty four bytes into the first half and
1756        // sixteen bytes into the second, which begins at forty eight.
1757        assert!(text.contains("	movl	$24, "), "{text}");
1758        assert!(text.contains("	movl	$64, "), "{text}");
1759        // The other two fields are addresses rather than numbers, so each is stored as a word and
1760        // each is a `lea` away. One of them reaches above the frame, which is where the caller's
1761        // arguments are and is the only thing in this function that is not below the stack pointer.
1762        assert!(text.contains(", 8(%r"), "{text}");
1763        assert!(text.contains(", 16(%r"), "{text}");
1764        let frame: u32 = text
1765            .lines()
1766            .find_map(|line| line.trim().strip_prefix("subq	$")?.split(',').next()?.parse().ok())
1767            .expect("a variadic function takes a frame for the save area");
1768        let above = |line: &str| {
1769            let at: u32 = line.trim().strip_prefix("leaq	")?.split('(').next()?.parse().ok()?;
1770            Some(at > frame)
1771        };
1772        assert!(text.lines().filter_map(above).any(|it| it), "{frame}: {text}");
1773    }
1774
1775    /// A `va_arg` is a branch on whether the argument it wants is still in the save area, and which
1776    /// of the two halves it walks is the type's answer.
1777    #[test]
1778    fn va_arg_branches_on_whether_the_argument_is_still_in_the_save_area() {
1779        let read = "__builtin_va_list ap; __builtin_va_start(ap, n);";
1780        let ints = format!("int f(int n, ...) {{ {read} return __builtin_va_arg(ap, int); }}\n");
1781        let text = asm(&ints);
1782
1783        // The last general purpose slot begins at forty, so an offset above it is an argument the
1784        // caller left in its own memory instead.
1785        assert!(text.contains("$40, "), "{text}");
1786        assert!(text.contains("	cmpl	"), "{text}");
1787        assert!(text.contains("	setbe	"), "unsigned, since an offset is a count of bytes: {text}");
1788
1789        let arg = "__builtin_va_arg(ap, double)";
1790        let text = asm(&format!("double f(int n, ...) {{ {read} return {arg}; }}\n"));
1791        assert!(text.contains("$160, "), "the last vector slot: {text}");
1792    }
1793
1794    /// A structure assigned is a copy of a known size, and a copy of a known size is a run of
1795    /// moves rather than a call to a library this compiler has no way to reach yet.
1796    #[test]
1797    fn a_structure_assignment_is_a_move_for_each_word_of_it() {
1798        let decl = "struct pair { long a, b; };\n";
1799        let body = "struct pair p = *q; return p.a + p.b;";
1800        let text = asm(&format!("{decl}long f(struct pair *q) {{ {body} }}\n"));
1801
1802        assert!(!text.contains("memcpy"), "nothing calls the library: {text}");
1803        assert!(!text.contains("\tcall"), "{text}");
1804        // Sixteen bytes aligned to eight is two words, and each is a load and a store.
1805        assert!(text.matches("\tmovq\t").count() >= 4, "two words each way: {text}");
1806    }
1807
1808    /// A word is as wide as the object is aligned to and no wider, so a character array is copied
1809    /// a byte at a time and a structure of longs eight bytes at a time.
1810    #[test]
1811    fn how_wide_a_word_of_a_copy_is_follows_the_alignment() {
1812        let decl = "struct bytes { char a[8]; };\n";
1813        let body = "struct bytes p = *q; return p.a[0];";
1814        let text = asm(&format!("{decl}int f(struct bytes *q) {{ {body} }}\n"));
1815
1816        // Eight bytes aligned to one is eight words, and each is a load and a store.
1817        assert!(text.matches("\tmovb\t").count() >= 16, "a byte at a time: {text}");
1818    }
1819
1820    /// What an initialiser does not name is zero, which the front end writes as a fill and this
1821    /// writes as the byte spread across each word.
1822    #[test]
1823    fn the_part_of_an_initialiser_that_names_nothing_is_stored_as_zero() {
1824        let decl = "struct wide { long a, b, c; };\n";
1825        let text = asm(&format!("{decl}long f(void) {{ struct wide w = {{ 7 }}; return w.c; }}\n"));
1826
1827        assert!(!text.contains("memset"), "nothing calls the library: {text}");
1828        assert!(text.contains("\tmovq\t$0, ") || text.contains("$0, %"), "the zero: {text}");
1829    }
1830
1831    /// A copy too large to be worth unrolling is a call to the runtime, which is the C library on
1832    /// a hosted target and `rucc-builtins` on a freestanding one.
1833    #[test]
1834    fn a_copy_too_large_to_unroll_calls_the_runtime() {
1835        let decl = "struct huge { char a[4096]; };\n";
1836        let mut opts = options();
1837        opts.emit = EmitKind::Asm;
1838        let source = format!("{decl}void f(struct huge *p, struct huge *q) {{ *p = *q; }}\n");
1839        let result = run(&opts, &source);
1840        assert!(!result.failed(), "{:?}", result.messages);
1841        let text = result.text();
1842        assert!(text.contains("call") && text.contains("memcpy"), "{text}");
1843        // The size in the register the convention passes the third argument in, which is what
1844        // says the call was built from the convention and not from the shape of the IR.
1845        assert!(text.contains("4096"), "the size travels: {text}");
1846    }
1847
1848    /// A frame that had to force its own alignment cannot say how far away the caller's stack
1849    /// pointer was, so it reaches back through the frame pointer instead.
1850    #[test]
1851    fn a_realigned_frame_reads_them_through_the_frame_pointer() {
1852        let six = "long a, long b, long c, long d, long e, long f";
1853        let body = "_Alignas(32) long wide[4]; wide[0] = g; return wide[0];";
1854        let text = asm(&format!("long f({six}, long g) {{ {body} }}\n"));
1855
1856        // The frame pointer is saved and pointed at where it was saved before the alignment is
1857        // forced, so the caller's arguments stay a constant distance from it: one word for the
1858        // saved frame pointer and one for the return address.
1859        assert!(text.contains("\tandq\t$-32, %rsp"), "{text}");
1860        assert!(text.contains("\tmovq\t16(%rbp), "), "{text}");
1861        assert!(!text.contains("\tmovq\t16(%rsp), "), "{text}");
1862    }
1863
1864    /// The object format decides the directives, and the target decides the object format.
1865    #[test]
1866    fn the_target_decides_how_the_assembly_is_spelled() {
1867        let mut opts = options();
1868        opts.emit = EmitKind::Asm;
1869        opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1870        let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1871        assert!(text.contains("__TEXT,__text"), "{text}");
1872        assert!(text.contains("\n_f:\n"), "{text}");
1873        assert!(!text.contains(".note.GNU-stack"), "{text}");
1874    }
1875
1876    /// The object file of `source`, insisting that it compiled cleanly.
1877    fn obj(source: &str) -> Vec<u8> {
1878        let mut opts = options();
1879        opts.emit = EmitKind::Object;
1880        let result = run(&opts, source);
1881        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1882        match result.artifact {
1883            Artifact::Object(bytes) => bytes,
1884            other => panic!("expected an object, got {other:?}"),
1885        }
1886    }
1887
1888    /// `-c`, which is the last step of the three the back end can end with.
1889    ///
1890    /// What is in the file is checked in `rucc-object`, a field at a time. What is checked here is
1891    /// that a C file goes all the way to one, which is the whole compiler in one line and the
1892    /// thing that stops working when a layer between them changes its mind about something.
1893    #[test]
1894    fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1895        let bytes = obj("int add(int a, int b) { return a + b; }\n");
1896        assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1897        let text = asm("int add(int a, int b) { return a + b; }\n");
1898        assert!(
1899            text.contains("\taddl\t"),
1900            "and the listing of it is the same instructions:\n{text}"
1901        );
1902    }
1903
1904    /// A variable this file defines, which is what a reference to one has to resolve against.
1905    #[test]
1906    fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
1907        let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
1908        assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
1909        assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
1910        assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
1911        // A zeroed variable carries its size and none of its bytes, and a `static` one is not
1912        // announced to the linker at all, which is the whole of what `static` means here.
1913        assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
1914        assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
1915        assert!(!text.contains(".globl\thidden"), "{text}");
1916        // Nothing writes through it, so it goes in a page the loader can map read only and every
1917        // process running the program can share.
1918        assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1919    }
1920
1921    /// A bit-field with a value in it, which is written as the bytes the value lands in.
1922    ///
1923    /// The interesting one is the field whose lowest byte is zero. The bytes a bit-field
1924    /// initializer makes are put together first and then taken back out as the run they make,
1925    /// and taking them out starts at the byte the field starts at, so a zero byte at the front
1926    /// used to end the object up in `.bss` with the rest of its value thrown away.
1927    #[test]
1928    fn a_bit_field_initializer_writes_every_byte_of_the_value_and_not_only_the_ones_that_are_set() {
1929        let text = asm("struct s { unsigned f : 20; } x = { 0x12300 };\n");
1930        assert!(text.contains("\t.data\n"), "there is something to write: {text}");
1931        assert!(text.contains("\nx:\n\t.ascii\t\"\\000#\\001\"\n"), "and it is the value: {text}");
1932
1933        // Two fields, the first of them zero, which is the same thing said with the zero byte
1934        // inside the run rather than at the front of it.
1935        let text = asm("struct s { unsigned a : 8; unsigned b : 8; } x = { 0, 3 };\n");
1936        assert!(text.contains("\nx:\n\t.ascii\t\"\\000\\003\"\n"), "{text}");
1937
1938        // Wider than an `int`, which is the same code and is worth saying because the value no
1939        // longer fits in the thirty two bits a bit-field used to be read at.
1940        let text = asm("struct s { unsigned long long f : 40; } x = { 0x100000 };\n");
1941        assert!(text.contains("\nx:\n\t.ascii\t\"\\000\\000\\020\"\n\t.space\t5\n"), "{text}");
1942
1943        // Nothing in it, which still costs no bytes in the file.
1944        let text = asm("struct s { unsigned f : 20; } x = { 0 };\n");
1945        assert!(text.contains("\t.bss\n"), "an object of zeroes is zeroes: {text}");
1946        assert!(text.contains("\nx:\n\t.space\t4\n"), "{text}");
1947    }
1948
1949    /// A string literal, which is a variable the program never named.
1950    #[test]
1951    fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
1952        let text = asm("const char *f(void) { return \"hi\"; }\n");
1953        assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
1954        assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1955        let label = text
1956            .lines()
1957            .find(|line| line.starts_with(".Lstr"))
1958            .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
1959        assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
1960    }
1961
1962    /// A variable holding the address of another one, which is the only hole an image has in it.
1963    #[test]
1964    fn an_address_in_an_initializer_is_left_to_the_linker() {
1965        let source = "int counter;\nint *p = &counter;\n";
1966        let text = asm(source);
1967        assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
1968        // And in the object it is eight zero bytes and a relocation, which is what the two paths
1969        // being one description is for.
1970        let bytes = obj(source);
1971        assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
1972    }
1973
1974    /// A thread-local variable, which is valid C that the back end does not build yet.
1975    #[test]
1976    fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
1977        let mut opts = options();
1978        opts.emit = EmitKind::Asm;
1979        let result = run(&opts, "_Thread_local int x = 1;\n");
1980        assert!(result.failed(), "every thread sharing one variable is worse than a message");
1981        assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
1982        // Not an internal error: nothing here is wrong and the note says where the work is.
1983        assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
1984    }
1985
1986    /// Not a rewording of the check above: what the two paths agree about is the point.
1987    #[test]
1988    fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
1989        // A call, because it is the one thing whose spelling in the two differs completely: the
1990        // listing writes a name and the object writes four zero bytes and a relocation asking the
1991        // linker for the same name. If either path had lost the callee, one of these would fail.
1992        let source = "int callee(void); int g(void) { return callee(); }\n";
1993        let bytes = obj(source);
1994        assert!(
1995            bytes.windows(7).any(|w| w == b"callee\0"),
1996            "the object has to name the callee for the linker to find it"
1997        );
1998        let text = asm(source);
1999        assert!(text.contains("\tcall\tcallee\n"), "{text}");
2000    }
2001
2002    /// What a file of a link contributes is an object, and the default emit is a link.
2003    ///
2004    /// This is here because getting it wrong is silent in the worst way: an empty file is a valid
2005    /// empty linker script, so a link fed one gets as far as reporting every symbol of the file as
2006    /// undefined and says nothing about the compilation that produced nothing.
2007    #[test]
2008    fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
2009        let mut opts = options();
2010        // What a command line with no `-c` and no `-S` on it asks for.
2011        opts.emit = EmitKind::Executable;
2012        let result = run(&opts, "int main(void) { return 0; }\n");
2013        assert_eq!(result.messages, Vec::<String>::new());
2014        match result.artifact {
2015            Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
2016            other => panic!("expected an object, got {other:?}"),
2017        }
2018    }
2019
2020    /// A target with a back end but no object writer says so rather than writing the wrong file.
2021    #[test]
2022    fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
2023        let mut opts = options();
2024        opts.emit = EmitKind::Object;
2025        opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
2026        let result = run(&opts, "int f(void) { return 0; }\n");
2027        assert!(result.failed(), "an object nobody can read is worse than a message");
2028        assert!(
2029            result.messages.iter().any(|m| m.contains("no object writer")),
2030            "{:?}",
2031            result.messages
2032        );
2033    }
2034
2035    /// The IR of `source`, insisting that it compiled cleanly.
2036    fn ir(source: &str) -> String {
2037        let mut opts = options();
2038        opts.emit = EmitKind::Ir;
2039        let result = run(&opts, source);
2040        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2041        result.text().to_owned()
2042    }
2043
2044    /// What was said about `source`, insisting that something was.
2045    fn errors(source: &str) -> Vec<String> {
2046        let mut opts = options();
2047        opts.emit = EmitKind::Ir;
2048        let result = run(&opts, source);
2049        assert!(result.failed(), "expected this to be refused:\n{source}");
2050        result.messages
2051    }
2052
2053    /// The body of the one function in `source`, which is what most of these are about.
2054    fn body(source: &str) -> String {
2055        let text = ir(source);
2056        let (_, rest) = text.split_once("{\n").expect("a function definition");
2057        let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
2058        body.to_owned()
2059    }
2060
2061    /// The IR of `source` at one safety tier, insisting that it compiled cleanly.
2062    fn safe_ir(tier: rucc_session::Safety, source: &str) -> String {
2063        let mut opts = options();
2064        opts.emit = EmitKind::Ir;
2065        opts.safety = tier;
2066        let result = run(&opts, source);
2067        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2068        result.text().to_owned()
2069    }
2070
2071    const READS_THROUGH_A_POINTER: &str = "int read(int *p) { return p[1]; }\n";
2072
2073    #[test]
2074    fn a_build_that_did_not_ask_for_the_monitor_is_compiled_the_way_it_always_was() {
2075        // This is the load bearing test of the whole flag. The monitor is being built in the open
2076        // and every build in the world is compiled by this compiler with the flag absent, so a
2077        // check that leaked into that path would be a regression for everybody.
2078        let text = ir(READS_THROUGH_A_POINTER);
2079        assert!(!text.contains("check_"), "{text}");
2080        assert!(!text.contains("cap_of"), "{text}");
2081    }
2082
2083    #[test]
2084    fn asking_for_a_tier_puts_the_checks_in_before_the_optimizer_sees_them() {
2085        let text = safe_ir(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2086        assert!(text.contains("cap_of"), "{text}");
2087        assert!(text.contains("check_bounds"), "{text}");
2088        assert!(text.contains("check_live"), "{text}");
2089        // The subscript is address arithmetic, so J2 applies to it as well as J1.
2090        assert!(text.contains("check_deriv"), "{text}");
2091    }
2092
2093    #[test]
2094    fn the_three_tiers_that_are_not_off_all_check_the_same_accesses_so_far() {
2095        // What separates them is the reporter and the boundary, which are milestones S2 and S3.
2096        // Pinning it here means the day they stop agreeing, this test says so rather than the
2097        // difference going unnoticed.
2098        let detect = safe_ir(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2099        for tier in [rucc_session::Safety::Enforce, rucc_session::Safety::Kernel] {
2100            assert_eq!(safe_ir(tier, READS_THROUGH_A_POINTER), detect, "{tier}");
2101        }
2102    }
2103
2104    /// The safety summary of `source` at one tier, insisting that it compiled cleanly.
2105    fn summary(tier: rucc_session::Safety, source: &str) -> String {
2106        let mut opts = options();
2107        opts.emit = EmitKind::SafetySummary;
2108        opts.safety = tier;
2109        let result = run(&opts, source);
2110        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2111        result.text().to_owned()
2112    }
2113
2114    #[test]
2115    fn the_summary_counts_the_checks_that_went_in_and_the_ones_still_standing() {
2116        let text = summary(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2117        assert!(text.contains("\"tier\": \"detect\""), "{text}");
2118        // One load, so one of each of the two access checks, and the subscript is a derivation.
2119        assert!(
2120            text.contains("\"bounds\": { \"emitted\": 1, \"remaining\": 1, \"discharged\": 0 }"),
2121            "{text}"
2122        );
2123        assert!(
2124            text.contains(
2125                "\"derivation\": { \"emitted\": 1, \"remaining\": 1, \"discharged\": 0 }"
2126            ),
2127            "{text}"
2128        );
2129    }
2130
2131    #[test]
2132    fn a_build_without_the_monitor_summarises_as_a_build_with_no_checks_in_it() {
2133        // Which is the honest summary rather than an error. A build system that emits a summary
2134        // for every unit should get one for the units nobody asked to instrument too, and the
2135        // zeroes are what say that the guarantee over that file is nothing at all.
2136        let text = summary(rucc_session::Safety::Off, READS_THROUGH_A_POINTER);
2137        assert!(text.contains("\"tier\": \"off\""), "{text}");
2138        assert!(
2139            text.contains("\"bounds\": { \"emitted\": 0, \"remaining\": 0, \"discharged\": 0 }"),
2140            "{text}"
2141        );
2142    }
2143
2144    #[test]
2145    fn a_call_the_boundary_models_is_counted_apart_from_one_it_does_not() {
2146        let text = summary(
2147            rucc_session::Safety::Detect,
2148            "void *memcpy(void *, const void *, unsigned long);\n\
2149             int puts(const char *);\n\
2150             void f(char *d, char *s) { memcpy(d, s, 4); puts(d); }\n",
2151        );
2152        assert!(text.contains("\"interposed\": 1"), "{text}");
2153        assert!(text.contains("\"puts\""), "{text}");
2154        // The wrapper it was pointed at is ours, so it is not on the list of things this build
2155        // failed to model. Counting it there would make instrumenting a file look worse than
2156        // leaving it alone.
2157        assert!(!text.contains("__rucc_wrap_memcpy\""), "{text}");
2158    }
2159
2160    #[test]
2161    fn the_two_directions_a_pointer_crosses_the_boundary_are_counted_apart() {
2162        // `f` is a name the linker can bind to and takes a pointer, so a pointer arrives there.
2163        // `notes_open` is a library this build did not instrument, so a pointer comes back from
2164        // it. Both are crossings and neither is the other, which is why there are two numbers.
2165        let text = summary(
2166            rucc_session::Safety::Detect,
2167            "void *notes_open(void);\n\
2168             char *f(char *p) { char *q = notes_open(); return q ? q : p; }\n",
2169        );
2170        assert!(text.contains("\"crossings\": { \"entered\": 1, \"returned\": 1 }"), "{text}");
2171        assert!(text.contains("\"notes_open\""), "{text}");
2172    }
2173
2174    #[test]
2175    fn a_static_function_nobody_takes_the_address_of_is_not_a_crossing() {
2176        // Nothing outside the file can reach it, so a witness on its parameters would be counting
2177        // a crossing that does not happen.
2178        let text = summary(
2179            rucc_session::Safety::Detect,
2180            "static int len(const char *p) { return p ? 1 : 0; }\n\
2181             int f(void) { return len(\"x\"); }\n",
2182        );
2183        assert!(text.contains("\"crossings\": { \"entered\": 0, \"returned\": 0 }"), "{text}");
2184    }
2185
2186    /// The granule report for `source`, insisting that it compiled cleanly.
2187    fn granules(source: &str) -> String {
2188        let mut opts = options();
2189        opts.emit = EmitKind::TypeGranules;
2190        let result = run(&opts, source);
2191        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2192        result.text().to_owned()
2193    }
2194
2195    #[test]
2196    fn the_granule_report_names_every_record_and_both_keyings() {
2197        let text = granules(
2198            "struct hot { char *p; int a; int b; };\n\
2199             int f(struct hot *h) { return h->a; }\n",
2200        );
2201        assert!(text.contains("struct hot"), "{text}");
2202        // Both keyings are reported because which types count as one is a decision the design
2203        // has not made yet, and a report that picked one would be hiding the cost of the other.
2204        assert!(text.contains("every type distinct"), "{text}");
2205        assert!(text.contains("every pointer one type"), "{text}");
2206        assert!(text.contains("budget"), "{text}");
2207    }
2208
2209    #[test]
2210    fn a_record_nothing_uses_is_still_measured() {
2211        // The measurement is about what a program declares, not about what it runs, so a type
2212        // that is only ever declared still costs the plane whatever its layout costs.
2213        let text = granules("struct unused { long a; double b; };\nint f(void) { return 0; }\n");
2214        assert!(text.contains("struct unused"), "{text}");
2215    }
2216
2217    #[test]
2218    fn the_granule_report_stops_before_anything_is_lowered() {
2219        // A layout is settled at the closing brace, so lowering the function bodies would take
2220        // minutes on an amalgamation and answer nothing. The evidence that it stops is that a
2221        // body the back end has no way to compile still produces a report.
2222        let text = granules(
2223            "struct wide { long double d; };\n\
2224             long double f(long double x) { return x * x; }\n",
2225        );
2226        assert!(text.contains("struct wide"), "{text}");
2227    }
2228
2229    #[test]
2230    fn a_witness_reaches_the_assembler_as_a_call_to_the_runtime() {
2231        // The count only means anything if the call is really there, and a summary saying one is
2232        // there is not evidence that the back end emitted it.
2233        let text = safe_asm(rucc_session::Safety::Detect, "char *f(char *p) { return p; }\n");
2234        assert!(text.contains("\tcall\t__rucc_cap_witness\n"), "{text}");
2235    }
2236
2237    #[test]
2238    fn a_pointer_turned_into_an_integer_is_on_the_trust_set() {
2239        let text = summary(
2240            rucc_session::Safety::Detect,
2241            "unsigned long f(int *p) { return (unsigned long) p; }\n",
2242        );
2243        assert!(text.contains("\"exposed\": 1"), "{text}");
2244    }
2245
2246    /// The assembly of `source` at one safety tier, insisting that it compiled cleanly.
2247    fn safe_asm(tier: rucc_session::Safety, source: &str) -> String {
2248        let mut opts = options();
2249        opts.emit = EmitKind::Asm;
2250        opts.safety = tier;
2251        let result = run(&opts, source);
2252        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2253        result.text().to_owned()
2254    }
2255
2256    #[test]
2257    fn a_check_reaches_the_assembler_as_a_call_to_the_runtime() {
2258        let text = safe_asm(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2259        assert!(text.contains("\tcall\t__rucc_check_bounds\n"), "{text}");
2260        assert!(text.contains("\tcall\t__rucc_check_live\n"), "{text}");
2261        assert!(text.contains("\tcall\t__rucc_check_deriv\n"), "{text}");
2262    }
2263
2264    #[test]
2265    fn every_check_that_reached_the_assembler_has_a_row_describing_it() {
2266        // Three checks and three descriptors, each in the section the runtime's reporter reads.
2267        // The width is `rucc_safety::lower::WIDTH` and the row is `rucc_safe_rt::fail::Descriptor`,
2268        // and the two agreeing is what makes the address a check is handed mean anything.
2269        let text = safe_asm(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2270        let section = format!("\t.section\t{},", rucc_safety::SECTION);
2271        assert_eq!(text.matches(&section).count(), 3, "{text}");
2272        for index in 0..3 {
2273            let name = format!("__rucc_safety_desc_{index}");
2274            // Defined once and referenced once, because a descriptor nothing points at describes
2275            // nothing and a reference with no definition does not link.
2276            assert!(text.contains(&format!("{name}:\n")), "{text}");
2277            assert!(text.contains(&format!("{name}(%rip)")), "{text}");
2278        }
2279        assert!(!text.contains("__rucc_safety_desc_3"), "{text}");
2280    }
2281
2282    /// `__builtin_constant_p` is answered in the front end and never reaches the IR.
2283    ///
2284    /// gcc folds it after optimization, so its answer for an argument that is not written as a
2285    /// constant can differ between `-O0` and `-O2`. What is checked here is the front end's
2286    /// answer, which is the same at every level, and the four cases where gcc gives the same
2287    /// answer at both levels are the ones measured on gcc 16: a literal is one, a variable is
2288    /// zero, a string literal is one and the address of an object is zero.
2289    #[test]
2290    fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
2291        let text = ir(concat!(
2292            "int g;\n",
2293            "int a = __builtin_constant_p(1);\n",
2294            "int b = __builtin_constant_p(g);\n",
2295            "int c = __builtin_constant_p(\"abc\");\n",
2296            "int d = __builtin_constant_p(&g);\n",
2297            "int e = __builtin_constant_p(1.5);\n",
2298            "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
2299        ));
2300        assert!(text.contains("global @a : i32 = 1,"), "{text}");
2301        assert!(text.contains("global @b : i32 = 0,"), "{text}");
2302        assert!(text.contains("global @c : i32 = 1,"), "{text}");
2303        assert!(text.contains("global @d : i32 = 0,"), "{text}");
2304        assert!(text.contains("global @e : i32 = 1,"), "{text}");
2305        assert!(text.contains("global @h : i32 = 11,"), "{text}");
2306        assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
2307
2308        // The argument is not evaluated, which is what gcc does with it as well, so `i` is
2309        // still zero. The second constant is the answer, which nothing reads and which the
2310        // first pass that looks for dead code will take out.
2311        let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
2312        assert_eq!(text, "block0:\n    %0 = iconst.i32 0\n    %1 = iconst.i32 0\n    return %0\n");
2313    }
2314
2315    /// A library builtin is the library function of the same name, and the call says so.
2316    ///
2317    /// A program writes `__builtin_strlen` rather than `strlen` to reach the function the C
2318    /// library promises where its own name has been taken by a macro, and to say that the usual
2319    /// meaning is the one intended. So the name in the program and the name in the object file
2320    /// are two different names and the call carries the second one. gcc folds several of these
2321    /// when the arguments allow it, which is an optimization on top of a call that is already
2322    /// right rather than instead of it, so nothing here depends on any folding happening.
2323    #[test]
2324    fn a_call_to_a_library_builtin_reaches_the_library_function() {
2325        let text = body("void f(void) { __builtin_abort(); }\n");
2326        assert_eq!(text, "block0:\n    call @abort() : ()\n    return\n");
2327
2328        // Nothing declared either of these and nothing had to: the prefix is what says the name
2329        // belongs to the implementation, and the type comes out of `features.toml`.
2330        let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
2331        assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
2332        assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
2333        assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
2334    }
2335
2336    /// The absolute value family is four instructions and not a call, whoever declared the name.
2337    ///
2338    /// `abs`, `labs` and `llabs` are reserved to the implementation, so a program that writes one
2339    /// means the one the C library promises and the compiler is allowed to know what it does. The
2340    /// program in `gcc.c-torture/execute/20021127-1.c` is the one that insists: it defines `llabs`
2341    /// to abort and expects the call not to reach it. Measured against gcc 16.2.0, which writes a
2342    /// `neg` and a `cmovns` and never calls the definition either.
2343    ///
2344    /// The most negative value comes back as itself, which is what the arithmetic gives and what
2345    /// gcc's pair of instructions gives, and C says the answer is undefined there.
2346    #[test]
2347    fn the_absolute_value_family_is_the_magnitude_and_not_a_call() {
2348        let text = body(concat!(
2349            "long long llabs(long long);\n",
2350            "long long f(long long x) { return llabs(x); }\n",
2351        ));
2352        assert!(text.contains("%1 = iconst.i64 63"), "{text}");
2353        assert!(text.contains("%2 = ashr %0, %1"), "{text}");
2354        assert!(text.contains("%3 = xor %0, %2"), "{text}");
2355        assert!(text.contains("%4 = sub %3, %2"), "{text}");
2356        assert!(!text.contains("call"), "the call does not happen:\n{text}");
2357
2358        // The narrower two, whose width comes from the type the library gives the name and not
2359        // from anything at the call.
2360        let text = body("int abs(int);\nint f(int x) { return abs(x); }\n");
2361        assert!(text.contains("iconst.i32 31"), "{text}");
2362        let text = body("long labs(long);\nlong f(long x) { return labs(x); }\n");
2363        assert!(text.contains("iconst.i64 63"), "{text}");
2364
2365        // The prefixed spelling is the same node, and it is what a program writes to reach the
2366        // library's meaning where the plain name has been taken.
2367        let text = body("long long f(long long x) { return __builtin_llabs(x); }\n");
2368        assert!(!text.contains("call"), "{text}");
2369
2370        // A definition of the name in the same file changes nothing, which is the whole point.
2371        let text = ir(concat!(
2372            "long long llabs(long long b);\n",
2373            "long long g(long long x) { return llabs(x); }\n",
2374            "long long llabs(long long b) { return 7; }\n",
2375        ));
2376        assert!(!text.contains("call @llabs"), "{text}");
2377    }
2378
2379    /// A byte swap is one instruction and not a call, and nothing had to declare it.
2380    ///
2381    /// SQLite writes these for its page headers and glibc's `<endian.h>` defines `htobe32` and its
2382    /// neighbours as exactly these, so a program that reads a file format reaches one without ever
2383    /// naming it. There is no object file anywhere that defines `__builtin_bswap32`, so a call left
2384    /// standing here would not link.
2385    #[test]
2386    fn a_byte_swap_is_arithmetic_and_not_a_call() {
2387        let text = body("unsigned f(unsigned x) { return __builtin_bswap32(x); }\n");
2388        assert_eq!(text, "block0(%0: i32):\n    %1 = bswap %0\n    return %1\n");
2389
2390        // The argument is converted by the prototype the way any other call's would be, so the
2391        // swap happens at the width the name says and not at the width the program wrote.
2392        let text = body("unsigned f(unsigned char c) { return __builtin_bswap32(c); }\n");
2393        assert!(text.contains("zext.i32 %0"), "widened first: {text}");
2394        assert!(text.contains("bswap %1"), "and swapped at four bytes: {text}");
2395    }
2396
2397    /// Each of the three reverses in the width its name says, which is the type of the node.
2398    ///
2399    /// The width matters more here than it looks. `__builtin_bswap16` is the two bytes of a
2400    /// `uint16_t` exchanged, and if the node came out at the machine's width instead then the bits
2401    /// above the value would be dragged into the answer and the result would be zero.
2402    #[test]
2403    fn the_byte_swaps_reverse_at_the_width_their_name_says() {
2404        for (name, ty, width) in [
2405            ("__builtin_bswap16", "unsigned short", "i16"),
2406            ("__builtin_bswap32", "unsigned", "i32"),
2407            ("__builtin_bswap64", "unsigned long long", "i64"),
2408        ] {
2409            let source = format!("{ty} f({ty} x) {{ return {name}(x); }}\n");
2410            let text = body(&source);
2411            assert_eq!(
2412                text,
2413                format!("block0(%0: {width}):\n    %1 = bswap %0\n    return %1\n"),
2414                "{name}"
2415            );
2416        }
2417    }
2418
2419    /// The three bit counts the IR has an instruction for are that instruction and not a call.
2420    ///
2421    /// Fifteen rows of `features.toml` come out of five questions, and three of the five are one
2422    /// instruction each. The kernel's bitmap search is built on them, ffmpeg counts leading zeroes
2423    /// in its bitstream reader and SQLite uses one to size a page, so a call left standing here
2424    /// would not link against anything and would be slow if it did.
2425    #[test]
2426    fn the_bit_counts_are_instructions_and_not_calls() {
2427        let text = body("int f(unsigned x) { return __builtin_clz(x); }\n");
2428        assert_eq!(text, "block0(%0: i32):\n    %1 = ctlz %0\n    return %1\n");
2429
2430        let text = body("int f(unsigned x) { return __builtin_ctz(x); }\n");
2431        assert_eq!(text, "block0(%0: i32):\n    %1 = cttz %0\n    return %1\n");
2432
2433        let text = body("int f(unsigned x) { return __builtin_popcount(x); }\n");
2434        assert_eq!(text, "block0(%0: i32):\n    %1 = ctpop %0\n    return %1\n");
2435    }
2436
2437    /// The width counted is the operand's and the width answered is `int`, which are two different
2438    /// things at every spelling but the narrowest.
2439    ///
2440    /// This is the mistake the family invites. `__builtin_clz` of a value counts the leading zeroes
2441    /// of it narrowed to `unsigned int` and `__builtin_clzll` counts them at sixty four bits, and
2442    /// those are different numbers for the same value. What decides it is the prototype the row
2443    /// carries, so the count happens after the conversion and the narrowing back to `int` happens
2444    /// after the count.
2445    #[test]
2446    fn the_bit_counts_ask_about_the_width_their_name_says() {
2447        let text = body("int f(unsigned long long x) { return __builtin_clzll(x); }\n");
2448        assert!(text.starts_with("block0(%0: i64):"), "counted at eight bytes: {text}");
2449        assert!(text.contains("%1 = ctlz %0"), "{text}");
2450        assert!(text.contains("trunc.i32 %1"), "and answered in an int: {text}");
2451
2452        // The same value asked about at the narrower width, which converts first and so counts
2453        // something else.
2454        let text = body("int f(unsigned long long x) { return __builtin_clz(x); }\n");
2455        assert!(text.contains("trunc.i32 %0"), "narrowed to what was asked about: {text}");
2456        assert!(text.contains("ctlz %1"), "and counted there: {text}");
2457
2458        let text = body("int f(unsigned long x) { return __builtin_popcountl(x); }\n");
2459        assert!(text.contains("%1 = ctpop %0"), "{text}");
2460        assert!(!text.contains("call"), "{text}");
2461    }
2462
2463    /// A parity is whether the count of set bits is odd, which is that count and its low bit.
2464    ///
2465    /// Not the machine's parity flag, which on x86-64 is over the low byte of a result and so is a
2466    /// different question, and not the count itself, since C says the answer is zero or one.
2467    #[test]
2468    fn a_parity_is_the_low_bit_of_the_set_bit_count() {
2469        let text = body("int f(unsigned x) { return __builtin_parity(x); }\n");
2470        assert!(text.contains("%1 = ctpop %0"), "{text}");
2471        assert!(text.contains("iconst.i32 1"), "{text}");
2472        assert!(text.contains("and %1, %2"), "the low bit of it: {text}");
2473    }
2474
2475    /// `__builtin_ffs` is the trailing zero count and one, kept only when there was a bit to find.
2476    ///
2477    /// The one in the family defined at zero, where it answers zero. Written as a mask rather than
2478    /// as a branch: the count and the comparison do not depend on each other and both are cheap, so
2479    /// a branch would buy nothing and cost two blocks and a join.
2480    #[test]
2481    fn the_first_set_bit_is_one_based_and_zero_for_a_zero() {
2482        let text = body("int f(int x) { return __builtin_ffs(x); }\n");
2483        assert!(text.contains("%1 = cttz %0"), "{text}");
2484        assert!(text.contains("%4 = add %1, %2"), "one more than the count: {text}");
2485        assert!(text.contains("%5 = icmp ne %0, %3"), "whether there was a bit at all: {text}");
2486        assert!(text.contains("%7 = sub %3, %6"), "spread to a mask: {text}");
2487        assert!(text.contains("%8 = and %4, %7"), "and kept only then: {text}");
2488        assert!(!text.contains("br_if"), "no branch: {text}");
2489    }
2490
2491    /// The three overflow checks are arithmetic and a flag, and not a call to anything.
2492    ///
2493    /// gcc has emitted these since 5.0 and there is no object file that defines one, so a call left
2494    /// standing here would not link. SQLite reaches all three within twenty lines of each other, in
2495    /// `sqlite3AddInt64` and its two neighbours, which is the reason they were done now.
2496    ///
2497    /// The IR instruction answers two things at once, the wrapped value and whether it wrapped,
2498    /// which is a shape nothing else in the IR has. The store is the builtin writing the answer
2499    /// through the pointer it was handed.
2500    #[test]
2501    fn an_overflow_check_is_arithmetic_and_not_a_call() {
2502        let text =
2503            body("int f(int a, int b, int *r) { return __builtin_add_overflow(a, b, r); }\n");
2504        assert!(text.contains("%3, %4 = sadd_overflow.(i32, i1) %0, %1"), "{text}");
2505        assert!(text.contains("store %3 -> %2"), "{text}");
2506        assert!(!text.contains("call"), "{text}");
2507
2508        let text =
2509            body("int f(int a, int b, int *r) { return __builtin_sub_overflow(a, b, r); }\n");
2510        assert!(text.contains("ssub_overflow.(i32, i1) %0, %1"), "{text}");
2511
2512        let text =
2513            body("int f(int a, int b, int *r) { return __builtin_mul_overflow(a, b, r); }\n");
2514        assert!(text.contains("smul_overflow.(i32, i1) %0, %1"), "{text}");
2515
2516        // Unsigned operands get the unsigned form, which is a different question about the same
2517        // arithmetic: an unsigned sum wraps where a signed one of the same bits does not.
2518        let text = body(
2519            "int f(unsigned a, unsigned b, unsigned *r) { return __builtin_add_overflow(a, b, r); }\n",
2520        );
2521        assert!(text.contains("uadd_overflow.(i32, i1) %0, %1"), "{text}");
2522    }
2523
2524    /// The arithmetic happens at a type that holds every value all three written types can hold.
2525    ///
2526    /// That is what makes the check exact. `unsigned int` and `int` in one call need thirty three
2527    /// bits between them, so the add is done at sixty four with each operand extended the way its
2528    /// own signedness says: the unsigned one zero extended, the signed one sign extended. Sign
2529    /// extending the unsigned one would turn three billion into a negative number before the
2530    /// addition ever saw it.
2531    #[test]
2532    fn an_overflow_check_is_done_at_a_type_that_holds_every_operand() {
2533        let text = body(
2534            "int f(unsigned a, int b, long long *r) { return __builtin_add_overflow(a, b, r); }\n",
2535        );
2536        assert!(text.contains("%3 = zext.i64 %0"), "the unsigned operand keeps its value: {text}");
2537        assert!(text.contains("%4 = sext.i64 %1"), "and so does the signed one: {text}");
2538        assert!(text.contains("sadd_overflow.(i64, i1) %3, %4"), "{text}");
2539
2540        // Three types that agree need no extension at all, which is what nearly every real call
2541        // is written as.
2542        let text = body(
2543            "int f(long long a, long long b, long long *r) { return __builtin_mul_overflow(a, b, r); }\n",
2544        );
2545        assert!(text.contains("smul_overflow.(i64, i1) %0, %1"), "{text}");
2546        assert!(!text.contains("sext."), "{text}");
2547        // The one widening left is the answer, which is a bit becoming the `int` C says it is.
2548        assert!(!text.contains("zext.i64"), "{text}");
2549    }
2550
2551    /// The wrapped answer is written through the pointer whether or not it fit.
2552    ///
2553    /// That is gcc's rule and it is what makes the builtin usable as a wrapping add with a flag on
2554    /// the side. A destination narrower than the arithmetic is narrowed and widened back, and the
2555    /// answer being different is the second half of the test: the instruction says whether the
2556    /// arithmetic itself needed more room, and the round trip says whether what came out survived
2557    /// the trip down to where it was going.
2558    #[test]
2559    fn an_overflow_check_writes_the_wrapped_answer_whether_or_not_it_fit() {
2560        let text =
2561            body("int f(int a, int b, char *r) { return __builtin_sub_overflow(a, b, r); }\n");
2562        assert!(text.contains("%3, %4 = ssub_overflow.(i32, i1) %0, %1"), "{text}");
2563        assert!(text.contains("%5 = trunc.i8 %3"), "narrowed to where it goes: {text}");
2564        assert!(text.contains("%6 = sext.i32 %5"), "and back: {text}");
2565        assert!(text.contains("%7 = icmp ne %6, %3"), "which is whether it fit: {text}");
2566        assert!(text.contains("store %5 -> %2"), "the narrowed value is stored either way: {text}");
2567        assert!(text.contains("%8 = or %4, %7"), "and either bit is an overflow: {text}");
2568    }
2569
2570    /// A call needing more than sixty four bits is refused by name rather than got wrong.
2571    ///
2572    /// Two ways to reach it: a `__int128` operand, and a sixty four bit unsigned type mixed with a
2573    /// signed one, which needs sixty five bits to represent both. gcc handles the second by being
2574    /// cleverer in the mixed case rather than by widening. Until that is written, the message says
2575    /// what the call needed.
2576    #[test]
2577    fn a_call_needing_more_than_sixty_four_bits_says_so() {
2578        let refused = concat!(
2579            "int f(unsigned long long a, long long b, long long *r) {\n",
2580            "    return __builtin_add_overflow(a, b, r);\n",
2581            "}\n",
2582        );
2583        let messages = errors(refused);
2584        assert_eq!(messages.len(), 1, "{messages:?}");
2585        assert!(messages[0].contains("E0694"), "{messages:?}");
2586        assert!(messages[0].contains("wider than 64 bits"), "{messages:?}");
2587    }
2588
2589    /// An operand that is not an integer at all is the older message, from the type checking every
2590    /// type generic builtin shares.
2591    #[test]
2592    fn an_overflow_check_over_something_that_is_not_an_integer_says_so() {
2593        let messages =
2594            errors("int f(double a, int b, int *r) { return __builtin_add_overflow(a, b, r); }\n");
2595        assert!(messages.iter().any(|line| line.contains("E0671")), "{messages:?}");
2596
2597        let messages =
2598            errors("int f(int a, int b, double *r) { return __builtin_add_overflow(a, b, r); }\n");
2599        assert!(messages.iter().any(|line| line.contains("E0671")), "{messages:?}");
2600    }
2601
2602    /// An ordered access is an ordered access in the IR, with the ordering the program wrote.
2603    ///
2604    /// Which is the point of the node existing at all. An ordering is not an argument anything is
2605    /// passed, it is a thing the IR says about an access, so the number in the source is read once
2606    /// in the front end and after that the ordering travels on the instruction where every pass
2607    /// that moves code can see it.
2608    ///
2609    /// SQLite is why these are done: `AtomicLoad` and `AtomicStore` in `sqlite3.c` are
2610    /// `__atomic_load_n` and `__atomic_store_n` at the relaxed ordering, and there are thirty five
2611    /// calls to the pair.
2612    #[test]
2613    fn an_ordered_access_is_ordered_in_the_ir() {
2614        let text = body("int f(int *p) { return __atomic_load_n(p, 0); }\n");
2615        assert!(text.contains("atomic_load.i32 %0, align 4, relaxed"), "{text}");
2616
2617        let text = body("long f(long *p) { return __atomic_load_n(p, 2); }\n");
2618        assert!(text.contains("atomic_load.i64 %0, align 8, acquire"), "{text}");
2619
2620        let text = body("void f(int *p, int v) { __atomic_store_n(p, v, 3); }\n");
2621        assert!(text.contains("atomic_store %1 -> %0, align 4, release"), "{text}");
2622
2623        let text = body("void f(int *p, int v) { __atomic_store_n(p, v, 5); }\n");
2624        assert!(text.contains("atomic_store %1 -> %0, align 4, seq_cst"), "{text}");
2625
2626        // The value is converted to what the pointer points at before it is stored, which is what
2627        // the call would have done if it had a prototype to convert against.
2628        let text = body("void f(char *p, int v) { __atomic_store_n(p, v, 0); }\n");
2629        assert!(text.contains("trunc.i8 %1"), "{text}");
2630        assert!(text.contains("atomic_store %2 -> %0, align 1, relaxed"), "{text}");
2631    }
2632
2633    /// On this machine the ordered access is the plain instruction, except at the strongest
2634    /// ordering of a store.
2635    ///
2636    /// x86-64 is total store order: every load is already an acquire and every store is already a
2637    /// release, and an aligned access no wider than a word is indivisible whether or not anybody
2638    /// asked. So the whole family is `mov` and the one thing the machine does not give away is a
2639    /// store staying in front of a later load, which is `mfence` behind the store. Every line below
2640    /// is what gcc 16.2.0 writes for the same function.
2641    #[test]
2642    fn an_ordered_access_is_the_plain_instruction_on_this_machine() {
2643        let text = asm("int f(int *p) { return __atomic_load_n(p, 5); }\n");
2644        assert!(text.contains("movl\t(%rdi), %eax"), "{text}");
2645        assert!(!text.contains("mfence"), "a load needs no barrier here: {text}");
2646
2647        let text = asm("void f(int *p, int v) { __atomic_store_n(p, v, 3); }\n");
2648        assert!(text.contains("movl\t%esi, (%rdi)"), "{text}");
2649        assert!(!text.contains("mfence"), "a release store needs no barrier here: {text}");
2650
2651        let text = asm("void f(int *p, int v) { __atomic_store_n(p, v, 5); }\n");
2652        let (before, after) = text.split_once("mfence").expect("a barrier: {text}");
2653        assert!(before.contains("movl\t%esi, (%rdi)"), "the store comes first: {text}");
2654        assert!(!after.contains("movl"), "and nothing else is between them: {text}");
2655    }
2656
2657    /// A barrier is one instruction at the strongest ordering and no instruction below it.
2658    ///
2659    /// The same reasoning the other way round. An acquire, a release and an acquire release fence
2660    /// are already true of every program running on this machine, and what a program wanted from
2661    /// one is that the compiler not move accesses across it, which is already so by the time any
2662    /// instruction is picked. Sequential consistency is the one that costs something.
2663    ///
2664    /// `__sync_synchronize` is the older family's spelling of the strongest one and compiles to
2665    /// exactly the same instruction, which is what SQLite calls twice in `sqlite3.c`.
2666    #[test]
2667    fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
2668        assert!(asm("void f(void) { __atomic_thread_fence(5); }\n").contains("mfence"));
2669        assert!(asm("void f(void) { __sync_synchronize(); }\n").contains("mfence"));
2670
2671        for weaker in ["1", "2", "3", "4"] {
2672            let source = format!("void f(void) {{ __atomic_thread_fence({weaker}); }}\n");
2673            assert!(!asm(&source).contains("mfence"), "{weaker} costs nothing here");
2674        }
2675    }
2676
2677    /// A memory order an operation cannot carry is read as the strongest one, and said so about.
2678    ///
2679    /// There are three ways the number is not one the operation can take: it is not a constant at
2680    /// all, it is not one of the six the headers define, or it is one of them and means nothing for
2681    /// this operation, which is a release load or an acquire store. All three become sequential
2682    /// consistency, which is stronger than anything the program could have meant, so a program that
2683    /// wrote nonsense gets a correct answer rather than a fast one. gcc does the same.
2684    ///
2685    /// The last two also warn, because the number was written down and is wrong. The first does
2686    /// not: gcc takes a computed order, and so does the C11 spelling, so a warning there would fire
2687    /// on correct programs.
2688    #[test]
2689    fn a_memory_order_an_operation_cannot_carry_is_read_as_the_strongest() {
2690        let mut opts = options();
2691        opts.emit = EmitKind::Ir;
2692
2693        let acquire_store = run(&opts, "void f(int *p, int v) { __atomic_store_n(p, v, 2); }\n");
2694        assert!(acquire_store.text().contains("seq_cst"), "{:?}", acquire_store.text());
2695        assert!(acquire_store.messages[0].contains("[W0333]"), "{:?}", acquire_store.messages);
2696
2697        let nonsense = run(&opts, "int f(int *p) { return __atomic_load_n(p, 99); }\n");
2698        assert!(nonsense.text().contains("seq_cst"), "{:?}", nonsense.text());
2699        assert!(nonsense.messages[0].contains("[W0333]"), "{:?}", nonsense.messages);
2700
2701        let computed = run(&opts, "int f(int *p, int n) { return __atomic_load_n(p, n); }\n");
2702        assert!(computed.text().contains("seq_cst"), "{:?}", computed.text());
2703        assert_eq!(computed.messages, Vec::<String>::new(), "a computed order is not a mistake");
2704    }
2705
2706    /// A conversion between a float and the widest unsigned integer, which the machine has not got.
2707    ///
2708    /// Every other conversion between a float and an integer is the signed one at some width with a
2709    /// widening in front or a narrowing behind. These two are not, because there is no signed width
2710    /// that holds every value of an unsigned sixty four bit integer, so each is the signed
2711    /// conversion with arithmetic around it that brings the value into range and puts it back.
2712    ///
2713    /// What is checked here is that the conversion happens at all and that it happens without a
2714    /// branch. gcc writes a branch for both; this writes the choice as a mask, because every rewrite
2715    /// in that pass stays inside the block it started in. The arithmetic itself is checked in
2716    /// `rucc-codegen`, where it can be run against the answer rather than read in the assembly.
2717    #[test]
2718    fn a_conversion_between_a_float_and_the_widest_unsigned_integer_is_written_without_a_branch() {
2719        let text = asm("double f(unsigned long long x) { return (double)x; }\n");
2720        assert!(text.contains("cvtsi2sdq"), "the signed conversion is what runs: {text}");
2721        assert!(text.contains("shrq"), "with the value halved first: {text}");
2722        assert!(text.contains("addsd"), "and doubled after: {text}");
2723        assert!(!text.contains("\tj"), "and no branch anywhere: {text}");
2724
2725        let text = asm("unsigned long long f(double d) { return (unsigned long long)d; }\n");
2726        assert!(text.contains("cvttsd2siq"), "the signed conversion is what runs: {text}");
2727        assert!(text.contains("subsd"), "with half the range taken off first: {text}");
2728        assert!(text.contains("shlq\t$63"), "and the top bit put back: {text}");
2729        assert!(!text.contains("\tj"), "and no branch anywhere: {text}");
2730    }
2731
2732    /// The plain names are the library's only where nothing else has taken them.
2733    ///
2734    /// Four ways a program says it means something else. A `static` definition is its own
2735    /// function and the name outside the file is somebody else's. A declaration of another type
2736    /// is another function. `-fno-builtin` and `-fno-builtin-<name>` say so outright, and
2737    /// `-ffreestanding` says there is no C library for the name to be the name of. Every one of
2738    /// these was measured against gcc 16.2.0, which calls the program's function in all of them.
2739    ///
2740    /// The `__builtin_` spelling goes on meaning the library's function through all of it, which
2741    /// is what the prefix is for and what lets a freestanding build reach one deliberately.
2742    #[test]
2743    fn a_plain_name_the_program_took_is_the_programs_own_function() {
2744        let taken = concat!(
2745            "static long long llabs(long long b) { return 7; }\n",
2746            "long long f(long long x) { return llabs(x); }\n",
2747        );
2748        assert!(ir(taken).contains("call @llabs"), "a static definition is the program's own");
2749
2750        let retyped = concat!("int llabs(int b);\n", "int f(int x) { return llabs(x); }\n",);
2751        assert!(ir(retyped).contains("call @llabs"), "another type is another function");
2752
2753        let plain = concat!(
2754            "long long llabs(long long b);\n",
2755            "long long f(long long x) { return llabs(x); }\n",
2756        );
2757        let mut opts = options();
2758        opts.emit = EmitKind::Ir;
2759        assert!(!run(&opts, plain).text().contains("call @llabs"), "the library's by default");
2760
2761        opts.builtins = false;
2762        assert!(run(&opts, plain).text().contains("call @llabs"), "-fno-builtin");
2763
2764        opts.builtins = true;
2765        opts.no_builtin = vec!["llabs".to_owned()];
2766        assert!(run(&opts, plain).text().contains("call @llabs"), "-fno-builtin-llabs");
2767        let one = "long labs(long b);\nlong f(long x) { return labs(x); }\n";
2768        assert!(!run(&opts, one).text().contains("call @labs"), "one name and not the family");
2769
2770        // `-ffreestanding` reaches the front end as the same answer, which is what the driver
2771        // does with it in `compile`, and the prefixed spelling is untouched by any of it.
2772        opts.no_builtin = Vec::new();
2773        opts.builtins = false;
2774        let prefixed = "long long f(long long x) { return __builtin_llabs(x); }\n";
2775        assert!(!run(&opts, prefixed).text().contains("call @llabs"), "the prefix is a promise");
2776    }
2777
2778    /// The hint builtins are their first argument, and nothing is left of the hint.
2779    ///
2780    /// Which way a branch is expected to go is the whole of what they say, and there is nothing
2781    /// here that reads a branch weight yet, so what reaches the IR is the value and the hint is
2782    /// gone. The one thing the prototype has to keep doing is converting: gcc gives both of them
2783    /// a `long` result, so `sizeof(__builtin_expect((char)1, 1))` is eight and a narrower argument
2784    /// widens before it is answered with.
2785    ///
2786    /// The arguments after the first are checked and then dropped, so a side effect in one does
2787    /// not happen. That is what gcc does with them too, measured on gcc 16.2.0: the `i` below
2788    /// comes back zero there as well.
2789    #[test]
2790    fn the_hint_builtins_are_their_first_argument_and_the_hint_leaves_no_trace() {
2791        let text = ir(concat!(
2792            "long a = __builtin_expect(7, 1);\n",
2793            "long b = __builtin_expect_with_probability(9, 1, 0.9);\n",
2794            "unsigned long c = sizeof(__builtin_expect((char)1, 1));\n",
2795        ));
2796        assert!(text.contains("global @a : i64 = 7,"), "{text}");
2797        assert!(text.contains("global @b : i64 = 9,"), "{text}");
2798        assert!(text.contains("global @c : i64 = 8,"), "{text}");
2799        assert!(!text.contains("__builtin_expect"), "it is not a call to anything:\n{text}");
2800
2801        // A narrower argument is widened by the prototype before it is handed back, and it is
2802        // widened with its sign, since the parameter is a signed `long`.
2803        let text = body("long f(char c) { return __builtin_expect(c, 1); }\n");
2804        assert!(text.contains("sext"), "{text}");
2805
2806        // The second argument is not evaluated, so `i` is still zero, and neither is the third.
2807        // What is left of each statement is the first argument widened, which nothing reads and
2808        // which the first pass that looks for dead code will take out.
2809        let one = "block0:\n    %0 = iconst.i32 0\n    %1 = iconst.i32 1\n    %2 = sext.i64 %1\n    return %0\n";
2810        assert_eq!(body("int f(void) { int i = 0; __builtin_expect(1, i++); return i; }\n"), one);
2811        let source = "int g(void) { int i = 0; __builtin_expect_with_probability(1, i++, 0.5); return i; }\n";
2812        assert_eq!(body(source), one);
2813    }
2814
2815    /// A point control does not arrive at, in both of the ways the compiler has one.
2816    ///
2817    /// `__builtin_unreachable()` is the promise written down, and a function whose body can run
2818    /// off the bottom is the walk arriving at the same place on its own. Neither writes an
2819    /// instruction, which is what gcc 16.2.0 does at `-O0`: it emits the epilogue and the `ret`
2820    /// for both of the functions below and nothing else, and the two of them come out byte for
2821    /// byte the same there.
2822    ///
2823    /// The `ret` is the part worth holding on to. It is not there because anything runs it, it is
2824    /// there because a function whose last instruction is not a return is one that falls into
2825    /// whatever the assembler puts after it.
2826    #[test]
2827    fn a_promise_that_control_does_not_arrive_writes_no_instruction() {
2828        let promised = "int f(int x) { if (x) return 1; __builtin_unreachable(); }\n";
2829        let text = ir(promised);
2830        assert!(text.contains("    unreachable_hint\n"), "{text}");
2831        assert!(!text.contains("call"), "it is not a call to anything:\n{text}");
2832
2833        // The statement after it is still lowered. Continuing to translate a path the program
2834        // promised is dead is one of the things a compiler may do with undefined behaviour, and
2835        // it is the one that keeps a program built at `-O0` behaving the way it was watched to.
2836        let after = body("int g(int x) { __builtin_unreachable(); return x; }\n");
2837        assert!(after.contains("return"), "{after}");
2838
2839        // Both functions are the same instructions, because the hint writes none of them and the
2840        // terminator underneath it writes none either.
2841        let text = asm(promised);
2842        let mine = text.split_once("\nf:\n").expect("a definition").1;
2843        let mine = mine.split_once("\t.size").expect("a definition").0;
2844        let plain = asm("int f(int x) { if (x) return 1; }\n");
2845        let plain = plain.split_once("\nf:\n").expect("a definition").1;
2846        let plain = plain.split_once("\t.size").expect("a definition").0;
2847        assert_eq!(mine, plain);
2848        assert!(mine.trim_end().ends_with("ret"), "{mine}");
2849        assert!(!mine.contains("ud2"), "{mine}");
2850    }
2851
2852    /// The two names stay apart, which is what having both of them is for.
2853    ///
2854    /// The one the program wrote is what the call is checked against and what a diagnostic about
2855    /// it says, and the one the library defines is what the call ends up carrying. A compiler
2856    /// that kept only the second would report this against `abort`, which is a function the
2857    /// program never mentions.
2858    #[test]
2859    fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
2860        let mut opts = options();
2861        opts.emit = EmitKind::Ir;
2862        let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
2863        assert!(
2864            messages.iter().any(|m| m.contains("__builtin_abort")),
2865            "expected the written name in {messages:?}"
2866        );
2867    }
2868
2869    /// A builtin nothing lowers is refused where it is written, rather than at the link.
2870    ///
2871    /// The names are one from each shape the table holds: a `__builtin_` with a prototype, one
2872    /// whose type comes from the call it was written in, and one from each of the two older
2873    /// families whose prefix is not `__builtin_`. What the message has to carry is the name,
2874    /// because the whole complaint about the link error this replaces is that the name in it was
2875    /// one the compiler chose.
2876    #[test]
2877    fn a_builtin_nothing_lowers_is_refused_by_name() {
2878        let mut opts = options();
2879        opts.emit = EmitKind::Ir;
2880        for (builtin, call) in [
2881            ("__builtin_return_address", "(int)(long)__builtin_return_address(0)"),
2882            ("__builtin_alloca", "(int)(long)__builtin_alloca(8)"),
2883            ("__atomic_exchange_n", "__atomic_exchange_n(&counter, 1, 0)"),
2884            ("__sync_fetch_and_add", "(int)__sync_fetch_and_add(&counter, 1)"),
2885        ] {
2886            let source = format!("int counter;\nint f(void) {{ return {call}; }}\n");
2887            let messages = run(&opts, &source).messages;
2888            let named = messages.iter().any(|m| m.contains(builtin) && m.contains("E0686"));
2889            assert!(named, "expected {builtin} to be refused by name in {messages:?}");
2890        }
2891    }
2892
2893    /// The refusal is about a call and not about the name, so the rest of what C does with one
2894    /// still works.
2895    ///
2896    /// `sizeof` does not evaluate its operand, so nothing is called and there is nothing to
2897    /// refuse; the type of the call is what it asks for and that comes from the front end. A
2898    /// program that defines the name itself gets the function it wrote, which is not what this
2899    /// is for but is what a definition in front of us means.
2900    #[test]
2901    fn what_is_refused_is_the_call_and_not_the_name() {
2902        let text = ir("unsigned long n = sizeof(__builtin_return_address(0));\n");
2903        assert!(text.contains("global @n : i64 = 8,"), "{text}");
2904
2905        let text = ir(concat!(
2906            "void *__builtin_return_address(unsigned x) { return 0; }\n",
2907            "void *f(void) { return __builtin_return_address(0); }\n",
2908        ));
2909        assert!(text.contains("call @__builtin_return_address"), "{text}");
2910    }
2911
2912    /// A `static` function nothing refers to is not emitted, and one that is refered to is.
2913    ///
2914    /// The pair is written as one program so that the two answers come out of one walk. What
2915    /// makes the difference is the call in `main` and nothing else about either definition.
2916    #[test]
2917    fn a_static_function_nothing_refers_to_is_not_emitted() {
2918        let text = ir("static int dropped(void) { return 1; }\n\
2919                       static int kept(void) { return 2; }\n\
2920                       int main(void) { return kept(); }\n");
2921        assert!(text.contains("func @kept"), "{text}");
2922        assert!(!text.contains("dropped"), "{text}");
2923    }
2924
2925    /// The set is transitive, so two of them that only call each other are both dropped.
2926    ///
2927    /// Counting the references to a name would keep this pair, since each is named once, and
2928    /// that is the mistake this is here to catch: what decides it is whether a root reaches the
2929    /// definition, and a root is something the file has a reason to emit on its own.
2930    #[test]
2931    fn two_static_functions_that_only_call_each_other_are_both_dropped() {
2932        let text = ir("static int ping(void);\n\
2933                       static int pong(void) { return ping(); }\n\
2934                       static int ping(void) { return pong(); }\n\
2935                       int main(void) { return 0; }\n");
2936        assert!(!text.contains("ping"), "{text}");
2937        assert!(!text.contains("pong"), "{text}");
2938    }
2939
2940    /// Everything that names a function keeps it, whether or not the name is being called.
2941    ///
2942    /// An address taken in a body, an image that holds one, and a body that is only reached
2943    /// through another `static` function are three different ways for a definition to be needed
2944    /// and none of them is a call at the top level of a reachable function.
2945    #[test]
2946    fn naming_a_static_function_anywhere_keeps_it() {
2947        let text = ir("static int by_address(void) { return 1; }\n\
2948                       static int in_an_image(void) { return 2; }\n\
2949                       static int deeper(void) { return 3; }\n\
2950                       static int reaches_deeper(void) { return deeper(); }\n\
2951                       static int (*table[1])(void) = {in_an_image};\n\
2952                       int main(void) {\n\
2953                         int (*p)(void) = by_address;\n\
2954                         return p() + table[0]() + reaches_deeper();\n\
2955                       }\n");
2956        for kept in ["by_address", "in_an_image", "deeper", "reaches_deeper"] {
2957            assert!(text.contains(&format!("func @{kept}")), "expected {kept} in:\n{text}");
2958        }
2959    }
2960
2961    /// An attribute that says something outside the file reaches it keeps the definition.
2962    ///
2963    /// None of the five is implemented as anything else yet, and this is the part of each of
2964    /// them that a program notices first: a symbol a linker script names or a function the
2965    /// run-up to `main` calls is not written about anywhere a C file can see.
2966    #[test]
2967    fn an_attribute_keeps_a_static_function_nothing_refers_to() {
2968        for attribute in ["used", "retain", "constructor", "destructor", "__used__"] {
2969            let source = format!(
2970                "__attribute__(({attribute})) static int kept(void) {{ return 1; }}\n\
2971                 int main(void) {{ return 0; }}\n"
2972            );
2973            let text = ir(&source);
2974            assert!(text.contains("func @kept"), "for {attribute}:\n{text}");
2975        }
2976    }
2977
2978    /// A function with external linkage is emitted whatever this file does with it, because
2979    /// another one may call it, and that is what external linkage is.
2980    #[test]
2981    fn a_function_anything_could_call_is_emitted_without_being_called() {
2982        let text =
2983            ir("int nobody_here_calls_it(void) { return 1; }\nint main(void) { return 0; }\n");
2984        assert!(text.contains("func @nobody_here_calls_it"), "{text}");
2985    }
2986
2987    /// Four of the classification builtins are operators C already has, and become those.
2988    ///
2989    /// What the standard's macro promises over the operator is that it does not raise the
2990    /// invalid operation exception on a quiet NaN. This compiler does not model floating point
2991    /// exceptions, so there is nothing left for a node of its own to carry and a second way of
2992    /// spelling a comparison would be a second thing every pass has to know about.
2993    #[test]
2994    fn a_classification_c_has_an_operator_for_is_that_operator() {
2995        for (builtin, operator) in [
2996            ("__builtin_isgreater", "binary >"),
2997            ("__builtin_isgreaterequal", "binary >="),
2998            ("__builtin_isless", "binary <"),
2999            ("__builtin_islessequal", "binary <="),
3000        ] {
3001            let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
3002            let text = tast(&source);
3003            assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
3004        }
3005    }
3006
3007    /// The rest of the family are comparisons in the IR and never a call to anything.
3008    ///
3009    /// `math.h` defines the macro of each of these names as the builtin of the same name, so
3010    /// there is no function under any of them for a call to reach. `isunordered` and
3011    /// `islessgreater` are predicates the IR's comparison already has, `isnan` is the value that
3012    /// is unordered with itself, and the two that ask about a magnitude are written against the
3013    /// infinities. `signbit` is the one that is not a question about the value, since a negative
3014    /// zero compares equal to a positive one, so its answer comes from the bits.
3015    #[test]
3016    fn the_classification_builtins_are_comparisons_and_not_calls() {
3017        let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
3018        assert_eq!(
3019            text,
3020            "block0(%0: f64, %1: f64):\n    %2 = fcmp uno %0, %1\n    %3 = zext.i32 \
3021                          %2\n    return %3\n"
3022        );
3023
3024        // Not `x != y`, which is true when the two are unordered and so is true of a NaN.
3025        let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
3026        assert!(text.contains("fcmp one %0, %1"), "{text}");
3027
3028        let text = body("int f(double x) { return __builtin_isnan(x); }\n");
3029        assert!(text.contains("fcmp uno %0, %0"), "{text}");
3030
3031        let text = body("int f(double x) { return __builtin_isinf(x); }\n");
3032        assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
3033        assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
3034        assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
3035        assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
3036        assert!(text.contains("%5 = or %3, %4"), "{text}");
3037
3038        // Strictly between the two infinities, which a NaN is not, because an ordered comparison
3039        // against either of them is false. That is what makes this one test rather than two.
3040        let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
3041        assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
3042        assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
3043        assert!(text.contains("%5 = and %3, %4"), "{text}");
3044
3045        let text = body("int f(double x) { return __builtin_signbit(x); }\n");
3046        assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
3047        assert!(text.contains("icmp slt %1, %2"), "{text}");
3048
3049        // The same question of a value in the target's widest format, where the bits are eighty
3050        // and the object they sit in is sixteen bytes.
3051        let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
3052        assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
3053
3054        // The operand is evaluated once however many times it is compared, which is the whole
3055        // reason these are nodes rather than a rewriting into the operators.
3056        let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
3057        assert_eq!(text.matches("call @g()").count(), 1, "{text}");
3058    }
3059
3060    /// A spelling that names a width converts its argument before it asks.
3061    ///
3062    /// gcc gives `__builtin_isinff` a `float` parameter and `__builtin_isinf` no parameter type
3063    /// at all, and the difference is visible rather than academic: `1e300` does not fit in a
3064    /// `float`, so converting it first is an infinity and not converting it is not. Both numbers
3065    /// here are what gcc 16 gives.
3066    #[test]
3067    fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
3068        let text = ir(concat!(
3069            "int a = __builtin_isinff(1e300);\n",
3070            "int b = __builtin_isinf(1e300);\n",
3071            // Folded here rather than compared at run time, because a question about a value has
3072            // an answer as soon as the value is a constant, and an initializer for an object
3073            // with static storage duration has to have one.
3074            "int c = __builtin_isnan(0.0);\n",
3075            "int d = __builtin_signbit(-0.0);\n",
3076            "int e = __builtin_islessgreater(1.0, 2.0);\n",
3077        ));
3078        assert!(text.contains("global @a : i32 = 1,"), "{text}");
3079        assert!(text.contains("global @b : i32 = 0,"), "{text}");
3080        assert!(text.contains("global @c : i32 = 0,"), "{text}");
3081        assert!(text.contains("global @d : i32 = 1,"), "{text}");
3082        assert!(text.contains("global @e : i32 = 1,"), "{text}");
3083    }
3084
3085    /// An argument that is not floating point is refused, in gcc's words.
3086    #[test]
3087    fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
3088        let mut opts = options();
3089        opts.emit = EmitKind::Ir;
3090        let source = concat!(
3091            "int a(int x) { return __builtin_isnan(x); }\n",
3092            "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
3093            "int c(double x) { return __builtin_isnan(x, x); }\n",
3094        );
3095        let messages = run(&opts, source).messages;
3096        assert_eq!(
3097            messages,
3098            [
3099                "/main.c:1:23: error: non-floating-point argument in call to function \
3100                 '__builtin_isnan' [E0685]",
3101                "/main.c:2:30: error: non-floating-point arguments in call to function \
3102                 '__builtin_isunordered' [E0685]",
3103                "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
3104            ]
3105        );
3106    }
3107
3108    /// The three of the family that need a constant of the format other than an infinity.
3109    ///
3110    /// `isnormal` is the one that needs the smallest normal, and it is asked of the magnitude, so
3111    /// the sign comes off first and what is left is the same shape as `isfinite`. `isinf_sign` is
3112    /// the one whose answer is a number: the two comparisons `isinf` builds, subtracted rather
3113    /// than combined. `fpclassify` is four questions of one value and five answers to pick from,
3114    /// and the picking is a mask because all five are constants and neither of them can have an
3115    /// effect.
3116    #[test]
3117    fn the_last_three_classification_builtins_are_comparisons_and_not_calls() {
3118        let text = body("int f(double x) { return __builtin_isnormal(x); }\n");
3119        // The sign off, which is the magnitude, and then the range, asked of the bits rather than
3120        // of the number, since the encoding of a value whose sign bit is clear rises with the
3121        // value in every format this compiles for.
3122        assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
3123        assert!(text.contains("%2 = iconst.i64 9223372036854775807"), "{text}");
3124        assert!(text.contains("%3 = and %1, %2"), "{text}");
3125        assert!(text.contains("%4 = iconst.i64 4503599627370496"), "{text}");
3126        assert!(text.contains("%5 = iconst.i64 9218868437227405312"), "{text}");
3127        assert!(text.contains("%6 = icmp uge %3, %4"), "{text}");
3128        assert!(text.contains("%7 = icmp ult %3, %5"), "{text}");
3129        assert!(text.contains("%8 = and %6, %7"), "{text}");
3130
3131        // The same question in the target's widest format, where the smallest normal has the
3132        // leading significand bit stored rather than implied, so its encoding is two bits and not
3133        // one.
3134        let text = body("int f(long double x) { return __builtin_isnormal(x); }\n");
3135        assert!(text.contains("%4 = iconst.i80 27670116110564327424"), "{text}");
3136        assert!(text.contains("%5 = iconst.i80 604453686435277732577280"), "{text}");
3137
3138        let text = body("int f(double x) { return __builtin_isinf_sign(x); }\n");
3139        assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
3140        assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
3141        assert!(text.contains("%7 = sub %5, %6"), "{text}");
3142
3143        let text = body("int f(double x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n");
3144        assert!(text.contains("fcmp uno %0, %0"), "{text}");
3145        assert!(text.contains("fcmp oeq %0, %6"), "{text}");
3146        // Four questions, each of them a bit widened into the type of the answer and then spread
3147        // into a mask that picks between the answer and whatever the questions after it settled
3148        // on. Nothing sign extends, because no rule lowers a sign extension out of one bit.
3149        assert_eq!(text.matches(" = zext.i32 ").count(), 4, "{text}");
3150        assert_eq!(text.matches(" = xor ").count(), 4, "{text}");
3151        assert!(!text.contains("call"), "{text}");
3152
3153        // The value is evaluated once however many questions are asked of it, which is the whole
3154        // reason `fpclassify` is a node rather than the chain of tests it turns into.
3155        let text = body(concat!(
3156            "double g(void);\n",
3157            "int f(void) { return __builtin_fpclassify(0, 1, 2, 3, 4, g()); }\n",
3158        ));
3159        assert_eq!(text.matches("call @g()").count(), 1, "{text}");
3160    }
3161
3162    /// Each of the three answers a constant where its operand is one.
3163    ///
3164    /// glibc's `fpclassify` macro is exactly this builtin, so a program that writes
3165    /// `fpclassify(0.0)` in a static initializer is writing this, and it has to have a value at
3166    /// translation time or the program is refused rather than merely compiled slowly. Every
3167    /// number here is what gcc 16 gives.
3168    #[test]
3169    fn the_last_three_classification_builtins_fold_where_their_operand_is_a_constant() {
3170        let text = ir(concat!(
3171            "int a = __builtin_isnormal(1.0);\n",
3172            "int b = __builtin_isnormal(0.0);\n",
3173            "int c = __builtin_isnormal(1.0 / 0.0);\n",
3174            "int d = __builtin_isinf_sign(-1.0 / 0.0);\n",
3175            "int e = __builtin_isinf_sign(1.0);\n",
3176            "int g = __builtin_fpclassify(0, 1, 2, 3, 4, 0.0);\n",
3177            "int h = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0);\n",
3178            "int i = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0 / 0.0);\n",
3179        ));
3180        assert!(text.contains("global @a : i32 = 1,"), "{text}");
3181        assert!(text.contains("global @b : i32 = 0,"), "{text}");
3182        assert!(text.contains("global @c : i32 = 0,"), "{text}");
3183        assert!(text.contains("global @d : i32 = -1,"), "{text}");
3184        assert!(text.contains("global @e : i32 = 0,"), "{text}");
3185        assert!(text.contains("global @g : i32 = 4,"), "{text}");
3186        assert!(text.contains("global @h : i32 = 2,"), "{text}");
3187        assert!(text.contains("global @i : i32 = 1,"), "{text}");
3188    }
3189
3190    /// `fpclassify` refuses what gcc refuses, in gcc's words.
3191    ///
3192    /// The five answers have to be integer constant expressions, because what the builtin does is
3193    /// pick one of them and a pick between values that are not known here would be a chain of
3194    /// conditionals over expressions the call has already evaluated.
3195    #[test]
3196    fn fpclassify_refuses_an_answer_that_is_not_an_integer_constant() {
3197        let mut opts = options();
3198        opts.emit = EmitKind::Ir;
3199        let source = concat!(
3200            "int a(double x, int n) { return __builtin_fpclassify(0, 1, n, 3, 4, x); }\n",
3201            "int b(double x) { return __builtin_fpclassify(0, 1, 2, 3, x); }\n",
3202            "int c(int x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n",
3203        );
3204        let messages = run(&opts, source).messages;
3205        assert_eq!(
3206            messages,
3207            [
3208                "/main.c:1:60: error: non-const integer argument 3 in call to function \
3209                 '__builtin_fpclassify' [E0687]",
3210                "/main.c:2:26: error: too few arguments to function '__builtin_fpclassify' \
3211                 [E0511]",
3212                "/main.c:3:23: error: non-floating-point argument in call to function \
3213                 '__builtin_fpclassify' [E0685]",
3214            ]
3215        );
3216    }
3217
3218    /// A builtin whose answer is a constant is one, and is not a call to the library.
3219    ///
3220    /// This is the reason the family is answered in the front end at all. `double x =
3221    /// __builtin_inf();` at file scope initializes an object with static storage duration, so
3222    /// there is no point in the program at which a call could be made, and a compiler that
3223    /// lowered it to one would reject a program gcc accepts. Every number here is the encoding
3224    /// gcc 16 gives on x86-64.
3225    #[test]
3226    fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
3227        let text = ir(concat!(
3228            "double a = __builtin_inf();\n",
3229            "float b = __builtin_huge_valf();\n",
3230            "long double c = __builtin_infl();\n",
3231            "double d = __builtin_huge_val();\n",
3232        ));
3233        assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
3234        assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
3235        assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
3236        assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
3237        assert!(!text.contains("call"), "{text}");
3238    }
3239
3240    /// A nan is written with the payload the program asked for.
3241    ///
3242    /// The string is read the way `strtoull` reads a number, which is what the library function
3243    /// of the same name does with it, and a string that is not one at all leaves the call for the
3244    /// library to answer at run time. A quiet nan has the high fraction bit set and a signalling
3245    /// one does not, except that a signalling nan with nothing in it would be an infinity, so it
3246    /// gets the next bit down instead. Every encoding here was measured against gcc 16, the two
3247    /// `long double` ones on a machine with the x87 format.
3248    #[test]
3249    fn a_nan_is_written_with_the_payload_the_program_asked_for() {
3250        let text = ir(concat!(
3251            "double a = __builtin_nan(\"\");\n",
3252            "double b = __builtin_nan(\"0x1\");\n",
3253            // Octal, since there is a leading zero, so this is eight and not ten.
3254            "double c = __builtin_nan(\"010\");\n",
3255            "double d = __builtin_nans(\"\");\n",
3256            "double e = __builtin_nans(\"0x1\");\n",
3257            "float f = __builtin_nanf(\"0x1\");\n",
3258            "float g = __builtin_nansf(\"\");\n",
3259            "long double h = __builtin_nansl(\"\");\n",
3260        ));
3261        assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
3262        assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
3263        assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
3264        assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
3265        assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
3266        assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
3267        assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
3268        assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
3269
3270        // A payload that is not a number, and one that is not known until run time, are both
3271        // left to the library, which is the same thing gcc emits for either of them.
3272        let text = ir(concat!(
3273            "double f(const char *p) { return __builtin_nan(p); }\n",
3274            "double g(void) { return __builtin_nans(\"1x\"); }\n",
3275        ));
3276        assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
3277        assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
3278    }
3279
3280    /// The length and the order of a string literal are known here.
3281    ///
3282    /// A program that asks for either of them is asking about something the translation already
3283    /// has in front of it, and folding is not only an optimization: `execute/921007-1.c` in the
3284    /// torture suite calls `__builtin_strcmp` in a file that defines its own `strcmp` with a
3285    /// different signature, so leaving the call behind is a name collision that gcc does not
3286    /// have. The comparison is over `unsigned char`, which is why the second one is negative.
3287    #[test]
3288    fn the_length_and_the_order_of_a_string_literal_are_known_here() {
3289        let text = ir(concat!(
3290            "unsigned long a = __builtin_strlen(\"hello\");\n",
3291            "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
3292            "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
3293            "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
3294            "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
3295        ));
3296        assert!(text.contains("global @a : i64 = 5,"), "{text}");
3297        assert!(text.contains("global @b : i64 = 1,"), "{text}");
3298        assert!(text.contains("global @c : i32 = 1,"), "{text}");
3299        assert!(text.contains("global @d : i32 = 0,"), "{text}");
3300        assert!(text.contains("global @e : i32 = 1,"), "{text}");
3301        assert!(!text.contains("call"), "{text}");
3302
3303        // An argument that is not a literal is the library's to answer, as it has to be.
3304        let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
3305        assert!(text.contains("call @strlen("), "{text}");
3306    }
3307
3308    /// A sign builtin is a mask over the bits, and is not a call.
3309    ///
3310    /// `fabs` and `copysign` are in the math library rather than the C one, so a program that
3311    /// only ever wrote the prefixed spelling never asked for `-lm` and a call left behind here
3312    /// would not link. Neither needs anything the library has: one clears the sign bit and the
3313    /// other takes it from the second operand, and every other bit goes through untouched.
3314    #[test]
3315    fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
3316        let text = body("double f(double x) { return __builtin_fabs(x); }\n");
3317        assert!(text.contains("bitcast.i64 %0"), "{text}");
3318        assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
3319        assert!(text.contains("and %1, %2"), "{text}");
3320        assert!(text.contains("bitcast.f64 %3"), "{text}");
3321        assert!(!text.contains("call"), "{text}");
3322
3323        let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
3324        assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
3325        assert!(text.contains("%8 = or %4, %7"), "{text}");
3326        assert!(!text.contains("call"), "{text}");
3327
3328        // The x87 format, whose value is eighty bits sitting in an object of sixteen. The mask is
3329        // as wide as the value and not as wide as the object, so the padding is not part of it.
3330        let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
3331        assert!(text.contains("bitcast.i80 %0"), "{text}");
3332        assert!(text.contains("bitcast.f80"), "{text}");
3333
3334        // The width a name does not spell out is `double`, so a `float` argument widens first and
3335        // the answer is a `double`, which is what gcc's declaration of it says.
3336        let text = body("double f(float x) { return __builtin_fabs(x); }\n");
3337        assert!(text.contains("fpext.f64 %0"), "{text}");
3338        assert!(text.contains("bitcast.i64 %1"), "{text}");
3339    }
3340
3341    /// The sign builtins answer a zero and a nan the way the bits say.
3342    ///
3343    /// This is why they are described over the bits rather than written with comparisons and
3344    /// negation. A negative zero compares equal to a positive one and has a sign bit to clear,
3345    /// and a nan compares equal to nothing at all and keeps its payload through both operations.
3346    /// `execute/ieee/copysign1.c` in the torture suite is the test that notices, because it
3347    /// compares its answers with `memcmp`. Every number here is what gcc 16 gives, the two in the
3348    /// x87 format measured on a machine that has it.
3349    #[test]
3350    fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
3351        let text = ir(concat!(
3352            "double a = __builtin_fabs(-3.5);\n",
3353            "double b = __builtin_copysign(1.0, -0.0);\n",
3354            "double c = __builtin_copysign(0.0, -2.0);\n",
3355            // The payload survives both, and only the sign bit moves.
3356            "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
3357            "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
3358            "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
3359            "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
3360            "long double i = __builtin_fabsl(-__builtin_infl());\n",
3361        ));
3362        assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
3363        assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
3364        assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
3365        assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
3366        assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
3367        assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
3368        assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
3369        assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
3370    }
3371
3372    /// A `constexpr` object is a named constant, which is the whole reason the keyword exists.
3373    ///
3374    /// C23 6.6p8 puts two of them on the list an integer constant expression is built from: one
3375    /// of an arithmetic type, and a member of one of a structure or union type. A subscript of
3376    /// one is not on the list and is a variably modified type in gcc 16 as well, and every
3377    /// number here is what gcc 16 gives on x86-64.
3378    #[test]
3379    fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
3380        let text = ir(concat!(
3381            "constexpr int side = 4;\n",
3382            "constexpr int wider = side + 1;\n",
3383            "constexpr double half = 1.5;\n",
3384            "struct point { int x; int y; };\n",
3385            "constexpr struct point origin = { 5, 6 };\n",
3386            "int square[side * side];\n",
3387            "int rectangle[wider];\n",
3388            "int rounded[(int)half * 2];\n",
3389            "int across[origin.y];\n",
3390            "enum named { four = side };\n",
3391            "int e = four;\n",
3392        ));
3393        assert!(text.contains("global @square : bytes 64 ="), "{text}");
3394        assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
3395        assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
3396        assert!(text.contains("global @across : bytes 24 ="), "{text}");
3397        assert!(text.contains("global @e : i32 = 4,"), "{text}");
3398
3399        // A `const` object is not one of them, which is what makes `int a[n];` a variable
3400        // length array in C and is the distinction the keyword was added to draw.
3401        let mut opts = options();
3402        opts.emit = EmitKind::Ir;
3403        let konst = "const int n = 1;\nint a[n];\n";
3404        let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
3405        assert_eq!(run(&opts, konst).messages, [message]);
3406
3407        // Nor is a subscript of one, which gcc 16 refuses in the same words.
3408        let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
3409        assert_eq!(run(&opts, subscript).messages, [message]);
3410
3411        // And `constexpr` implies `const`, so the address of one is an address of a `const`.
3412        let address = "constexpr int c = 3;\nint *p = &c;\n";
3413        let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
3414             pointer target type [E0514]";
3415        assert_eq!(run(&opts, address).messages, [warning]);
3416    }
3417
3418    /// A definition that names its parameters and then declares them under the list.
3419    ///
3420    /// The declarations say what the types are, 6.9.1p6, and what the function takes is those
3421    /// types with the default argument promotions over them, which is what a caller of an
3422    /// unprototyped function hands over. A prototype already in scope overrules the promoted
3423    /// types, since a header saying `int narrow(char);` over a definition written this way is
3424    /// the pairing all the code written this way relies on and 6.7.6.3p15 is read that way by
3425    /// every compiler.
3426    #[test]
3427    fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
3428        // C17, since the default dialect is the one that warns about the form and this is
3429        // about what it means rather than about the warning.
3430        let mut opts = options();
3431        opts.std = Std::C17;
3432        let source = concat!(
3433            "int add(a, b)\n",
3434            "int a;\n",
3435            "int b;\n",
3436            "{ return a + b; }\n",
3437            "int promoted(c)\n",
3438            "char c;\n",
3439            "{ return c; }\n",
3440            "int narrow(char);\n",
3441            "int narrow(c)\n",
3442            "char c;\n",
3443            "{ return c; }\n",
3444            "int first(a)\n",
3445            "int a[4];\n",
3446            "{ return a[0]; }\n",
3447        );
3448        let result = run(&opts, source);
3449        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
3450        let text = result.text();
3451        assert!(text.contains("add : int(int, int) function external defined"), "{text}");
3452        assert!(text.contains("promoted : int(int) function external defined"), "{text}");
3453        // The body still sees the `char` it was declared as, whatever the caller hands over.
3454        assert!(text.contains("c : char object automatic defined"), "{text}");
3455        assert!(text.contains("narrow : int(char) function external defined"), "{text}");
3456        // An array parameter is a pointer here as much as it is in a prototype.
3457        assert!(text.contains("first : int(int *) function external defined"), "{text}");
3458    }
3459
3460    /// What the two halves of an old-style parameter list can disagree about.
3461    ///
3462    /// Each of these is a sentence gcc 16 has, and every message below is the one it prints,
3463    /// read off it on x86-64 rather than reasoned about. The last two are the dialect: a name
3464    /// with no declaration is an `int` in C89 and a diagnostic from C99 on, and the whole form
3465    /// left the language in C23, where gcc still takes it and warns.
3466    #[test]
3467    fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
3468        let mut opts = options();
3469        opts.std = Std::C17;
3470        for (source, message) in [
3471            ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
3472            (
3473                "int f(a)\nint a;\nint b;\n{ return a; }\n",
3474                "3:5: error: declaration for parameter 'b' but no such parameter",
3475            ),
3476            ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
3477            ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
3478            (
3479                "int f(a)\nstatic int a;\n{ return a; }\n",
3480                "2:12: error: storage class specified for parameter 'a'",
3481            ),
3482            (
3483                "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
3484                "2:7: error: argument 'a' doesn't match prototype",
3485            ),
3486        ] {
3487            let result = run(&opts, source);
3488            assert!(result.failed(), "expected this to fail:\n{source}");
3489            assert!(result.messages[0].contains(message), "{:?}", result.messages);
3490        }
3491
3492        // A name the declarations never mention. C89 gave it an `int` and gcc still takes it
3493        // in that dialect, and every dialect after it made the same line a diagnostic.
3494        let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
3495        let mut older = options();
3496        older.std = Std::C89;
3497        assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
3498        let result = run(&opts, implicit);
3499        assert!(
3500            result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
3501            "{:?}",
3502            result.messages
3503        );
3504
3505        // C23 took the form out of the language and gcc kept accepting it with a warning, and
3506        // a warning is what this is, because the code written this way is not going to be
3507        // rewritten and refusing it would put the compiler out of reach of it.
3508        let mut newer = options();
3509        newer.std = Std::C23;
3510        let plain = "int f(a)\nint a;\n{ return a; }\n";
3511        let result = run(&newer, plain);
3512        assert!(!result.failed(), "{:?}", result.messages);
3513        assert_eq!(
3514            result.messages,
3515            ["/main.c:1:5: warning: old-style function definition [E0412]"]
3516        );
3517        assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
3518    }
3519
3520    /// A type nothing is ever an object of is a type `sizeof` still has to answer about, which
3521    /// is what `991014-1.c` in the gcc.c-torture execution suite asks.
3522    ///
3523    /// The limit is `PTRDIFF_MAX` and it is the same one for an array and for a record, so a
3524    /// record of every byte an object may have is laid out and one byte more is refused. All
3525    /// four numbers are what gcc 16 gives on x86-64.
3526    #[test]
3527    fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
3528        let text = ir(concat!(
3529            "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
3530            "struct brim { char buf[9223372036854775807L]; };\n",
3531            "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
3532            "unsigned long h = sizeof(struct huge_struct);\n",
3533            "unsigned long b = sizeof(struct brim);\n",
3534            "unsigned long y = sizeof(struct bitty);\n",
3535        ));
3536        assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
3537        assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
3538        assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
3539
3540        let mut opts = options();
3541        opts.emit = EmitKind::Ir;
3542        let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
3543        let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
3544        assert_eq!(run(&opts, over).messages, [message]);
3545        let array = "struct wide { short buf[1L << 62]; };\n";
3546        let message = "/main.c:1:25: error: size of array 'buf' exceeds \
3547             maximum object size '9223372036854775807' [E0537]";
3548        assert_eq!(run(&opts, array).messages[0], message);
3549    }
3550
3551    /// A byte in the source that is not part of a character, which only a literal may hold.
3552    ///
3553    /// The source cannot be a `&str` here, which is the whole point: a file is bytes and only
3554    /// mostly text.
3555    fn compile_bytes(source: &[u8]) -> Compiled {
3556        let mut opts = options();
3557        opts.emit = EmitKind::Ir;
3558        let mut fs = MemoryFileSystem::new();
3559        fs.insert("/main.c", source.to_vec());
3560        compile(&opts, "/main.c", &fs)
3561    }
3562
3563    /// A raw byte inside a string literal is that byte, which gcc has always taken and which is
3564    /// the only place in a source file where a byte does not have to be part of a character.
3565    /// Replacing it would give the object three bytes rather than one, since the replacement
3566    /// character is three bytes of UTF-8, so the object would not be the one that was written
3567    /// even where the diagnostic is ignored. Anywhere else the byte is still a mistake, which
3568    /// is where gcc draws the same line.
3569    #[test]
3570    fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
3571        let mut source = b"char s[] = \"a".to_vec();
3572        source.push(0xff);
3573        source.extend_from_slice(b"b\";\nchar c = '");
3574        source.push(0xff);
3575        source.extend_from_slice(b"';\n");
3576        let result = compile_bytes(&source);
3577        assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
3578        assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
3579        // Plain `char` is signed on this target, so the constant is minus one rather than 255.
3580        assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
3581
3582        let mut stray = b"int a".to_vec();
3583        stray.push(0xff);
3584        stray.extend_from_slice(b" = 1;\n");
3585        let result = compile_bytes(&stray);
3586        assert!(
3587            result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
3588            "{:?}",
3589            result.messages
3590        );
3591    }
3592
3593    #[test]
3594    fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
3595        let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
3596        assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
3597        let expected = "\
3598func @add(i32, i32) -> i32, linkage(external) {
3599block0(%0: i32, %1: i32):
3600    %2 = add.nsw %0, %1
3601    return %2
3602}
3603";
3604        assert!(text.contains(expected), "{text}");
3605    }
3606
3607    #[test]
3608    fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
3609        let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
3610        assert!(!text.contains("alloca"), "{text}");
3611        assert!(!text.contains("load"), "{text}");
3612        assert!(!text.contains("store"), "{text}");
3613    }
3614
3615    #[test]
3616    fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
3617        let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
3618        let expected = "\
3619block0:
3620    %0 = alloca, size 4, align 4
3621    %1 = iconst.i32 1
3622    store %1 -> %0, align 4
3623    %2 = call @g(%0) : (ptr) -> i32
3624    return %2
3625";
3626        assert_eq!(text, expected);
3627    }
3628
3629    #[test]
3630    fn a_loop_carries_what_it_changes_as_block_parameters() {
3631        // The whole point of building SSA during the walk rather than after it: `i` and
3632        // `total` are values that arrive on an edge, and neither has ever been in memory.
3633        let text = body(
3634            "int f(int n) {\n  int total = 0;\n  for (int i = 0; i < n; i++) total += i;\n  \
3635             return total;\n}\n",
3636        );
3637        assert!(!text.contains("alloca"), "{text}");
3638        assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
3639        assert!(text.contains("jump block1("), "{text}");
3640    }
3641
3642    #[test]
3643    fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
3644        let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
3645        assert!(text.contains("icmp slt %0, %1"), "{text}");
3646        assert!(!text.contains("zext"), "{text}");
3647    }
3648
3649    #[test]
3650    fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
3651        let text = body("int f(int a, int b) { return a && b; }\n");
3652        let expected = "\
3653block0(%0: i32, %1: i32):
3654    %2 = iconst.i32 0
3655    %3 = icmp ne %0, %2
3656    %4 = iconst.i1 0
3657    br_if %3, block1, block2(%4)
3658
3659block1:
3660    %5 = iconst.i32 0
3661    %6 = icmp ne %1, %5
3662    jump block2(%6)
3663
3664block2(%7: i1):
3665    %8 = zext.i32 %7
3666    return %8
3667";
3668        assert_eq!(text, expected);
3669    }
3670
3671    #[test]
3672    fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
3673        let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
3674        // Three blocks, the test and the two arms. The join the `return 3` would need is
3675        // never created, because a block nothing branches to is not a block.
3676        assert!(!text.contains("block3"), "{text}");
3677        assert!(!text.contains("iconst.i32 3"), "{text}");
3678    }
3679
3680    #[test]
3681    fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
3682        assert!(body("int main(void) { }\n").contains("iconst.i32 0\n    return"));
3683        assert_eq!(body("void f(void) { }\n"), "block0:\n    return\n");
3684        assert!(body("int f(void) { }\n").contains("unreachable"));
3685    }
3686
3687    #[test]
3688    fn a_structure_is_copied_rather_than_held_in_a_value() {
3689        let text = body(
3690            "struct point { int x, y; };\n\
3691             int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
3692        );
3693        assert!(text.contains("memcpy"), "{text}");
3694    }
3695
3696    #[test]
3697    fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
3698        let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
3699        assert!(text.contains("memset"), "{text}");
3700    }
3701
3702    #[test]
3703    fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
3704        let text = body(
3705            "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
3706             default: r = 4; } return r; }\n",
3707        );
3708        let expected = "\
3709block0(%0: i32):
3710    %1 = iconst.i32 0
3711    switch %0, block1, [1 => block2, 2 => block3(%1)]
3712
3713block1:
3714    %2 = iconst.i32 4
3715    jump block4(%2)
3716
3717block2:
3718    %3 = iconst.i32 1
3719    jump block3(%3)
3720
3721block3(%4: i32):
3722    %5 = iconst.i32 2
3723    %6 = add.nsw %4, %5
3724    jump block4(%6)
3725
3726block4(%7: i32):
3727    return %7
3728";
3729        assert_eq!(text, expected);
3730    }
3731
3732    #[test]
3733    fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
3734        // GNU's `case 1 ... 9`. Nine table entries would be nine here and four billion for the
3735        // range a program is allowed to write, so it is a subtraction and one unsigned compare.
3736        let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
3737        assert!(text.contains("%2 = sub %0, %1"), "{text}");
3738        assert!(text.contains("icmp ule"), "{text}");
3739        assert!(!text.contains("switch"), "{text}");
3740    }
3741
3742    #[test]
3743    fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
3744        let text = body(
3745            "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
3746             case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
3747        );
3748        // The `continue` goes to the step and the `break` goes to the `t++` after the switch,
3749        // which is also where the default falls out to.
3750        assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
3751        assert!(text.contains("block5:\n    jump block7("), "{text}");
3752        assert!(text.contains("block6:\n    jump block8("), "{text}");
3753    }
3754
3755    #[test]
3756    fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
3757        assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n    return\n");
3758    }
3759
3760    #[test]
3761    fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
3762        // A branch into the middle of a loop that nothing else reaches, the Duff's device shape.
3763        // The `while` is not reached in order, so the walk starts a block nothing branches to and
3764        // builds it from there. What comes out is the loop with an edge straight into its body,
3765        // and the header that nothing arrives at is pruned.
3766        let text = body(
3767            "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
3768             return n; }\n",
3769        );
3770        // `case 2` lands on the body, `case 1` and the default land on the return, and the test
3771        // at the bottom of the loop comes back round to the body.
3772        assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
3773        assert!(text.contains("block3(%3: i32):\n    %4 = iconst.i32 1"), "{text}");
3774        assert!(text.contains("block4:\n    jump block3("), "{text}");
3775    }
3776
3777    #[test]
3778    fn a_goto_into_a_loop_body_enters_it_without_the_test() {
3779        // The same thing through a `goto`. The first pass through the body runs whatever the
3780        // label is on, and only then does the loop reach its own test.
3781        let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
3782        assert!(text.starts_with("block0(%0: i32, %1: i32):\n    jump block1(%1)"), "{text}");
3783        assert!(text.contains("block1(%2: i32):\n    %3 = iconst.i32 1"), "{text}");
3784        assert!(text.contains("br_if %6, block2, block3"), "{text}");
3785    }
3786
3787    #[test]
3788    fn a_goto_is_a_jump_to_the_block_the_label_starts() {
3789        let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
3790        // Both edges into `out` carry what `r` holds on the way, and neither is a stack slot. The
3791        // block the `goto` jumps out of is empty and hands its edge on, which is what moves `out`
3792        // up the block list to second place.
3793        assert!(!text.contains("alloca"), "{text}");
3794        assert!(text.contains("block2(%4: i32):\n    return %4"), "{text}");
3795        assert_eq!(text.matches("jump block2(").count(), 2, "{text}");
3796    }
3797
3798    #[test]
3799    fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
3800        let text =
3801            body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
3802        assert!(!text.contains("alloca"), "{text}");
3803        assert!(text.contains("block1(%2: i32):"), "{text}");
3804        assert!(text.contains("jump block1(%5)"), "{text}");
3805    }
3806
3807    #[test]
3808    fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
3809        // A block nothing branches to is not a legal function, and which labels are dead is not
3810        // known until the last statement has been walked, since the `goto` is allowed to be it.
3811        assert_eq!(
3812            body("int f(int x) { return x; spare: return 0; }\n"),
3813            "block0(%0: i32):\n    return %0\n"
3814        );
3815    }
3816
3817    #[test]
3818    fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
3819        let text = body(
3820            "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
3821        );
3822        // One byte holds both fields, and the signed one needs no mask: shifting it down
3823        // arithmetically is what says its top bit is a sign.
3824        assert_eq!(
3825            text,
3826            "\
3827block0(%0: ptr):
3828    %1 = load.i8 %0, align 1
3829    %2 = iconst.i8 3
3830    %3 = ashr %1, %2
3831    %4 = sext.i32 %3
3832    return %4
3833"
3834        );
3835    }
3836
3837    #[test]
3838    fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
3839        // C11 says an ordinary member beside a bit-field is a memory location of its own, so
3840        // the four byte store this would take is a data race in a program that has none. The
3841        // three bytes of `a` go in as two and one, and `c` is not touched.
3842        let text =
3843            body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
3844        assert_eq!(
3845            text,
3846            "\
3847block0(%0: ptr, %1: i32):
3848    %2 = iconst.i32 16777215
3849    %3 = and %1, %2
3850    %4 = trunc.i16 %3
3851    store %4 -> %0, align 2
3852    %5 = iconst.i32 16
3853    %6 = lshr %3, %5
3854    %7 = trunc.i8 %6
3855    %8 = iconst.i64 2
3856    %9 = ptr_add %0, %8
3857    store %7 -> %9, align 1
3858    return
3859"
3860        );
3861    }
3862
3863    #[test]
3864    fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
3865        let text =
3866            body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
3867        // 33 does not fit in five bits, and 1 is both what goes in the field and what the
3868        // assignment is worth.
3869        assert!(text.contains("%3 = iconst.i8 31\n    %4 = and %2, %3"), "{text}");
3870        assert!(text.ends_with("%9 = zext.i32 %4\n    return %9\n"), "{text}");
3871    }
3872
3873    #[test]
3874    fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
3875        // The value of an assignment to a bit-field takes a shift to build, and a statement
3876        // has no use for it. Nothing here reads back what was stored.
3877        let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
3878        assert_eq!(text.matches("ashr").count(), 0, "{text}");
3879        assert!(text.ends_with("store %8 -> %0, align 1\n    return\n"), "{text}");
3880    }
3881
3882    #[test]
3883    fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
3884        // A bit-field writes part of a byte and leaves the rest of it alone, so the object has
3885        // to be zero before it goes in or what the initializer did not name is whatever the
3886        // stack held.
3887        let text = body(
3888            "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
3889        );
3890        assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
3891    }
3892
3893    #[test]
3894    fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
3895        // Two fields in one byte are not two entries in the image, because an image is written
3896        // in bytes: they are the byte they are both in.
3897        let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
3898        assert!(
3899            text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
3900            "{text}"
3901        );
3902    }
3903
3904    #[test]
3905    fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
3906        // `sizeof` answers without the array and the definition has to hold what was written, so
3907        // the object is the size of its image. gcc 16 gives these four, three and two bytes and
3908        // so does this. The image used to be written at the size the type had, which left the
3909        // verifier looking at twenty bytes going into four.
3910        let text = ir(concat!(
3911            "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
3912            "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
3913            "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
3914            "char s[2] = \"hi\";\n",
3915        ));
3916        assert!(
3917            text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
3918            "{text}"
3919        );
3920        assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
3921        assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
3922        // The array with a length of its own still cuts the literal down to it, which is the
3923        // one case in C where a string initializer drops its terminator.
3924        assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
3925    }
3926
3927    #[test]
3928    fn a_definition_takes_a_parameter_it_left_unnamed() {
3929        // The entry block's parameters are the definition's, and one the front end dropped for
3930        // having no name left the two lists different lengths, which the walk read as an
3931        // old-style definition and refused. gcc has taken these for far longer than C23 has.
3932        let text = ir("int f(int a, int) { return a; }\n");
3933        assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
3934        assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
3935
3936        // The unnamed one first, so that the named one is the second parameter of the entry
3937        // block and not the first: the list says the order and not only how many there are.
3938        let text = ir("int g(int, int n) { return n; }\n");
3939        assert!(text.contains("block0(%0: i32, %1: i32):\n    return %1\n"), "{text}");
3940    }
3941
3942    #[test]
3943    fn an_assignment_of_a_structure_is_the_object_it_wrote() {
3944        // `d = e = c` used to be refused, because the middle assignment is a value of structure
3945        // type and the walk had nowhere to read one from. What an assignment is worth is the
3946        // value it stored, so the object it stored into is the answer and the chain is three
3947        // copies out of the one source with no temporary in it.
3948        let text = body(concat!(
3949            "struct s { int f; int g; };\n",
3950            "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
3951            "{ *d = *e = a[0] = *c; }\n",
3952        ));
3953        assert_eq!(text.matches("memcpy").count(), 3, "{text}");
3954        assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
3955        assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
3956        assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
3957    }
3958
3959    #[test]
3960    fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
3961        // The excess used to be laid into the object anyway, so the row after was written over
3962        // and the image refused the entry that came to it. C 6.7.10p14 says the terminator goes
3963        // in only if there is room for it, and gcc discards the rest of a literal that is longer
3964        // still, which is what the first of these is and why it warns.
3965        let mut opts = options();
3966        opts.emit = EmitKind::Ir;
3967        let result = run(
3968            &opts,
3969            concat!(
3970                "const char a[2][3] = { \"1234\", \"xyz\" };\n",
3971                "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
3972                "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
3973                "const union u c = { { \"1234\", \"567\" } };\n",
3974            ),
3975        );
3976        let text = result.text();
3977        assert_eq!(
3978            result.messages,
3979            ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
3980              (5 chars into 3 available) [E0637]"]
3981        );
3982        assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
3983        assert!(
3984            text.contains(
3985                "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
3986                 bytes \"9\\00\", zero 3 }"
3987            ),
3988            "{text}"
3989        );
3990        // The eight bytes are four, three and a terminator, and then the byte the shorter
3991        // literal left for the string in the other member of the union to end at.
3992        assert!(
3993            text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
3994            "{text}"
3995        );
3996    }
3997
3998    #[test]
3999    fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
4000        // gcc accepts one and does nothing with it, which sema already had. Lowering asked for
4001        // the object under it and had no arm for a cast, so `(struct s)x` in an initializer was
4002        // refused with E0519. It is one copy out of the object named, not two.
4003        let text = body(concat!(
4004            "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
4005            "void g(struct v *);\n",
4006            "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
4007        ));
4008        assert_eq!(text.matches("memcpy").count(), 1, "{text}");
4009    }
4010
4011    #[test]
4012    fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
4013        // C 6.7.11p4 says a compound literal at file scope has static storage duration, which
4014        // makes it a constant element, and tcc and c-testsuite both write one. Sema used to call
4015        // it a non constant because reading it is a node of its own and the read was what it
4016        // looked at, and lowering had no way to put an object where it wanted a number.
4017        let text = ir(concat!(
4018            "struct s { int x; };\n",
4019            "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
4020            "int n = (int){ 7 };\n",
4021            "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
4022        ));
4023        assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
4024        assert!(text.contains("global @n : i32 = 7,"), "{text}");
4025        // The second literal names nothing, so what it puts in is the zeros of its own size and
4026        // not the tail of the object it went in, which would have been the same bytes by luck.
4027        assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
4028    }
4029
4030    #[test]
4031    fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
4032        // Nothing declares a compound literal, so the reference is the only thing that can ask
4033        // for it to be emitted. The image named `.Lanon.0` and the module defined no such
4034        // symbol, which the link would have been the first to find out.
4035        let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
4036        assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
4037        assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
4038    }
4039
4040    #[test]
4041    fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
4042        // A zero length array, which gcc allows and real code uses as the tail of a structure.
4043        // The image is there and holds nothing, which is not the global that has no image at
4044        // all, and the IR reader used to stop on the empty one.
4045        let text = ir("unsigned char foo[1][0];\n");
4046        assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
4047    }
4048
4049    #[test]
4050    fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
4051        // `NULL` in a static initializer, which every program has. The IR type is `ptr` and a
4052        // `ptr` has no width of its own, so the width the bits are cut to is the target's.
4053        let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
4054        assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
4055        assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
4056    }
4057
4058    #[test]
4059    fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
4060        // Which the verifier used to refuse, having read a declaration as a definition with
4061        // nothing in it. `extern const` is how a program names something in the library's read
4062        // only data, and glibc and Darwin both have one in a header a real program includes.
4063        let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
4064        assert!(
4065            text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
4066            "{text}"
4067        );
4068    }
4069
4070    #[test]
4071    fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
4072        // A structure is not a value in the IR, so the two arms cannot be joined as one. The
4073        // addresses can, and the answer is the address of whichever arm was taken rather than
4074        // a copy of it into a third place: both arms outlive the expression, so a copy would
4075        // be one nothing could observe. SQLite's parser writes one of these.
4076        let text = body(
4077            "\
4078struct s { int a, b; };
4079struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
4080",
4081        );
4082        // The join takes an address, each arm hands it the one it has, and nothing is copied.
4083        assert!(text.contains("block3(%7: ptr)"), "{text}");
4084        assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
4085        assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
4086    }
4087
4088    #[test]
4089    fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
4090        // `struct pair` is two eightbytes on SysV, one of them integer, so the signature says
4091        // one `i64` in each direction and the body takes the object apart and puts it back
4092        // together around the call.
4093        let text = ir("\
4094struct pair { int a, b; };
4095struct pair make(int a, int b);
4096struct pair twice(struct pair p) { return make(p.a, p.b); }
4097");
4098        assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
4099        assert!(text.contains("func @twice(i64) -> i64"), "{text}");
4100    }
4101
4102    #[test]
4103    fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
4104        // Over two eightbytes the caller passes the bytes in the argument area, which is
4105        // `byval`, and passes somewhere to write the return value, which is `sret`. Neither is
4106        // a parameter the program wrote and both are parameters the function has.
4107        let text = ir("\
4108struct big { double v[8]; };
4109struct big grow(struct big b);
4110struct big twice(struct big b) { return grow(grow(b)); }
4111");
4112        assert!(
4113            text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
4114            "{text}"
4115        );
4116        assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
4117        // The inner call writes into a slot and the outer one reads the same slot, so the
4118        // object between the two calls is never copied anywhere.
4119        assert_eq!(text.matches("call @grow").count(), 2, "{text}");
4120    }
4121
4122    #[test]
4123    fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
4124        // The bytes travel in the argument area the same way they would for a parameter, and
4125        // `printf` has no parameter there to say it on, so the call says it instead. The one
4126        // that fits in registers says nothing, because travelling as the registers it fits in
4127        // is what an argument does when nothing says otherwise.
4128        let text = ir("\
4129struct big { double v[8]; };
4130struct pair { int a, b; };
4131int p(const char *, ...);
4132int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
4133");
4134        assert!(
4135            text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
4136            "{text}"
4137        );
4138    }
4139
4140    #[test]
4141    fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
4142        // `make(1, 2).b` has no object to read a member of until one is made, and what makes it
4143        // is a slot the returned registers are written to.
4144        let body = body(
4145            "\
4146struct pair { int a, b; };
4147struct pair make(int a, int b);
4148int second(void) { return make(1, 2).b; }
4149",
4150        );
4151        assert!(body.starts_with("block0:\n    %0 = alloca, size 8, align 4\n"), "{body}");
4152        assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
4153    }
4154
4155    #[test]
4156    fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
4157        // The same declaration, classified by a different ABI: three `float` members are an
4158        // eightbyte of two of them and a half eightbyte of the third on SysV, and three vector
4159        // registers on AAPCS64.
4160        let source = "\
4161struct hfa { float x, y, z; };
4162int take(struct hfa h);
4163int give(struct hfa h) { return take(h); }
4164";
4165        assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
4166        let mut opts = options();
4167        opts.emit = EmitKind::Ir;
4168        opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
4169        let result = run(&opts, source);
4170        assert_eq!(result.messages, Vec::<String>::new());
4171        assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
4172    }
4173
4174    #[test]
4175    fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
4176        // The size is a multiplication rather than a number, the slot is taken from the stack
4177        // where the declaration is, and the scope it was declared in gives it back.
4178        let source = "\
4179int use(int *);
4180void f(int n) {
4181  {
4182    int a[n];
4183    use(a);
4184  }
4185  use(0);
4186}
4187";
4188        let body = body(source);
4189        assert!(body.contains("mul.nsw"), "{body}");
4190        assert!(body.contains("stacksave"), "{body}");
4191        assert!(body.contains("alloca %"), "{body}");
4192        assert!(body.contains("stackrestore"), "{body}");
4193    }
4194
4195    #[test]
4196    fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
4197        // The label is outside the block the array is in, so arriving there means the array is
4198        // gone, and the restore that says so goes in front of the branch. The `goto` is written
4199        // before the walk knows where the label is, which is why the restore is put there at
4200        // the end rather than built where the branch was.
4201        let source = "\
4202int use(int *);
4203int f(int n) {
4204  {
4205    int a[n];
4206    if (use(a)) goto out;
4207    use(0);
4208  }
4209out:
4210  return 0;
4211}
4212";
4213        let body = body(source);
4214        // Two ways out of the block and a restore on each: the jump and the end of the block.
4215        assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
4216        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
4217        assert!(after.starts_with(" %4\n    jump block"), "{body}");
4218    }
4219
4220    #[test]
4221    fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
4222        // The label is after the declaration and in the same block, so control that arrives
4223        // there arrives somewhere the array exists. Giving it back would be giving back an
4224        // object the next statement reads.
4225        let source = "\
4226int use(int *);
4227int f(int n) {
4228  int a[n];
4229again:
4230  if (use(a)) goto again;
4231  return 0;
4232}
4233";
4234        let body = body(source);
4235        assert!(body.contains("stacksave"), "{body}");
4236        assert!(!body.contains("stackrestore"), "{body}");
4237    }
4238
4239    #[test]
4240    fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
4241        // A loop written out of a `goto`, with the array made inside it. The label is in the
4242        // same block as the declaration and before it, which is a place where the array does
4243        // not exist yet, so the jump there leaves its scope and has to give the stack back. A
4244        // compiler that skips this restore grows the stack once per iteration.
4245        let source = "\
4246int use(int *);
4247int f(int n) {
4248again:
4249  {
4250    int a[n];
4251    if (use(a)) goto again;
4252  }
4253  return 0;
4254}
4255";
4256        let body = body(source);
4257        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
4258        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
4259        assert!(after.starts_with(" %4\n    jump block1\n"), "{body}");
4260    }
4261
4262    #[test]
4263    fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
4264        // The scope opened for `for (int a[n];;)` used to stay open, and a scope left open is
4265        // not one mark nobody reads. The marks are a stack, so the next close took this one
4266        // instead of its own, and the body of the loop gave back nothing while the block after
4267        // the loop restored a pointer saved inside it. The verifier refused that, which is how
4268        // it was found.
4269        let source = "\
4270int f(void);
4271void t(void) {
4272  int count = 10;
4273  for (; count--;) {
4274    int b[f()];
4275    int i;
4276    for (i = 0; i < f(); i++) {
4277      b[i] = count;
4278    }
4279  }
4280}
4281";
4282        let body = body(source);
4283        // One save, in the body, and one restore for it, also in the body: the block the
4284        // restore is in is the one the inner loop leaves through, and it goes back round the
4285        // outer loop rather than out of it.
4286        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
4287        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
4288        // The rest of the block the restore is in, which is the last block here, so there is not
4289        // always another one after it to split on.
4290        let next = after.split("\n\n").next().expect("the block the restore is in");
4291        assert!(next.contains("jump block1("), "{body}");
4292    }
4293
4294    #[test]
4295    fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
4296        // What C says about the length being evaluated once: `sizeof a` after `n` changed is
4297        // still as long as the array is, which is what `n` was when the array came into being.
4298        let source = "\
4299unsigned long f(int n) {
4300  int a[n];
4301  n = 0;
4302  return sizeof a;
4303}
4304";
4305        let body = body(source);
4306        // One read of the parameter, at the declaration, and the answer is built out of it.
4307        assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
4308    }
4309
4310    #[test]
4311    fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
4312        // GNU's statement expression: the statements happen where they are written and the last
4313        // one is the value, so the temporary in it never becomes a slot and never is copied.
4314        let source = "\
4315int use(int);
4316int f(int x) {
4317  return ({
4318    int t = use(x);
4319    t * t;
4320  });
4321}
4322";
4323        let expected = "\
4324block0(%0: i32):
4325    %1 = call @use(%0) : (i32) -> i32
4326    %2 = mul.nsw %1, %1
4327    return %2
4328";
4329        assert_eq!(body(source), expected);
4330    }
4331
4332    #[test]
4333    fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
4334        // A macro that always jumps, which is what this shape is in real code. The value is
4335        // never taken, and the block the rest of the expression would have been built in is
4336        // one nothing branches to, so it goes with the other unreachable blocks.
4337        let source = "int f(int x) { return ({ return x; 0; }); }\n";
4338        assert_eq!(body(source), "block0(%0: i32):\n    return %0\n");
4339    }
4340
4341    #[test]
4342    fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
4343        // What it becomes is the target's answer, and this is not where the target's answers
4344        // are, so the walk writes down which list and which type and leaves it at that. Two of
4345        // them are two instructions, since each moves the list on.
4346        let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
4347        let expected = "\
4348block0(%0: ptr):
4349    %1 = va_arg.f64 %0
4350    %2 = va_arg.f64 %0
4351    %3 = fadd %1, %2
4352    return %3
4353";
4354        assert_eq!(body(source), expected);
4355    }
4356
4357    #[test]
4358    fn one_that_reads_a_structure_answers_where_the_object_is() {
4359        // An aggregate is not a value, so there is nothing for the result of `va_arg` to be and
4360        // the object form is a second instruction. What it answers is an address, so it is a
4361        // place already and the walk copies nothing out of it: the copy here is the one the
4362        // initializer asks for, into the variable being declared. The size and the alignment
4363        // travel with it because they are what steps the list on and what a target that has to
4364        // put registers somewhere needs to know. So does the classification, which says the two
4365        // halves of this one arrived in general purpose registers: that is an answer about a C
4366        // type, and this is the last place that still has one.
4367        //
4368        // The slot is aligned to sixteen and the copy into it to eight, which is not a
4369        // disagreement. Sixteen is what a local aggregate of sixteen bytes gets whatever its
4370        // members ask for, and eight is what the type asks for and so what the copy may assume
4371        // about the object it is reading from.
4372        let source = "\
4373struct s { int a; long b; };
4374long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
4375";
4376        let expected = "\
4377block0(%0: ptr):
4378    %1 = alloca, size 16, align 16
4379    %2 = va_object %0, size 16, align 8, in(int 8 at 0, int 8 at 8)
4380    memcpy %1, %2, size 16, align 8
4381    %3 = iconst.i64 8
4382    %4 = ptr_add %1, %3
4383    %5 = load.i64 %4, align 8
4384    return %5
4385";
4386        assert_eq!(body(source), expected);
4387    }
4388
4389    /// Which register file each eightbyte arrived in is the whole of what the classification adds,
4390    /// and an object with no slots at all is one it sent to the caller's argument area, which is
4391    /// what everything over two eightbytes is whatever its members are.
4392    #[test]
4393    fn the_classification_says_which_registers_the_object_arrived_in() {
4394        let source = "\
4395struct s { double a; double b; };
4396double f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a; }
4397";
4398        assert!(
4399            body(source)
4400                .contains("va_object %0, size 16, align 8, in(float f64 at 0, float f64 at 8)"),
4401            "{}",
4402            body(source)
4403        );
4404
4405        let big = "\
4406struct s { long a[4]; };
4407long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a[0]; }
4408";
4409        assert!(body(big).contains("va_object %0, size 32, align 8\n"), "{}", body(big));
4410    }
4411
4412    #[test]
4413    fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
4414        // GNU's computed goto. Which label the address holds is not known here, so all of them
4415        // are listed, and the values arriving at one are passed on every edge the same way they
4416        // are on an ordinary branch.
4417        let source = "\
4418int f(int c) {
4419  void *p = c ? &&one : &&two;
4420  goto *p;
4421one:
4422  return 1;
4423two:
4424  return 2;
4425}
4426";
4427        let expected = "\
4428block0(%0: i32):
4429    %1 = iconst.i32 0
4430    %2 = icmp ne %0, %1
4431    br_if %2, block1, block2
4432
4433block1:
4434    %3 = block_addr block3
4435    jump block4(%3)
4436
4437block2:
4438    %4 = block_addr block5
4439    jump block4(%4)
4440
4441block3:
4442    %5 = iconst.i32 1
4443    return %5
4444
4445block4(%6: ptr):
4446    indirect_br %6, block3, block5
4447
4448block5:
4449    %7 = iconst.i32 2
4450    return %7
4451";
4452        assert_eq!(body(source), expected);
4453    }
4454
4455    #[test]
4456    fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
4457        // The address came from outside the function, and a jump to a label in another function
4458        // is undefined. The expression is still evaluated, since a call in it has to happen.
4459        let source = "void **next(void);
4460void f(void) { goto *next(); }
4461";
4462        let expected = "\
4463block0:
4464    %0 = call @next() : () -> ptr
4465    unreachable
4466";
4467        assert_eq!(body(source), expected);
4468    }
4469
4470    #[test]
4471    fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
4472        // Nothing reads a result, so the only thing that keeps it is that it is volatile, which
4473        // a basic asm implies.
4474        let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
4475        let expected = "\
4476block0:
4477    inline_asm.volatile \"mfence\", \"\", \"memory\"()
4478    return
4479";
4480        assert_eq!(body(source), expected);
4481    }
4482
4483    #[test]
4484    fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
4485        // The outputs first and then the inputs, which is the numbering `%0` and `%1` use. An
4486        // output in a register is a result, and one that is read as well is an argument too.
4487        let source = "\
4488int f(int x, int y) {
4489  int r;
4490  __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
4491  return r + y;
4492}
4493";
4494        let expected = "\
4495block0(%0: i32, %1: i32):
4496    %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
4497    %4 = add.nsw %2, %3
4498    return %4
4499";
4500        assert_eq!(body(source), expected);
4501    }
4502
4503    #[test]
4504    fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
4505        // The assembly is handed a pointer, so the object cannot live in a value, and the scan
4506        // that runs before the walk has to have known that or there would be nothing to point
4507        // at. A structure travels this way whatever else its constraint allows, since there is
4508        // no register that holds one.
4509        let source = "\
4510struct pair { int a, b; };
4511int f(int x) {
4512  int slot = x;
4513  struct pair p = { x, x };
4514  __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
4515  return slot + p.a;
4516}
4517";
4518        let text = body(source);
4519        assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
4520        assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
4521        assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
4522    }
4523
4524    #[test]
4525    fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
4526        // The output is only in scope where the instruction dominates, which is the fall through
4527        // block, so the edge to the label carries the value the object had before the assembly
4528        // ran. That is what document 11 asks for and it is what putting the fall through first
4529        // buys.
4530        let source = "\
4531int f(int x) {
4532  int r = 7;
4533  __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
4534  return r;
4535away:
4536  return r;
4537}
4538";
4539        let expected = "\
4540block0(%0: i32):
4541    %1 = iconst.i32 7
4542    %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
4543
4544block1:
4545    return %2
4546
4547block2:
4548    return %1
4549";
4550        assert_eq!(body(source), expected);
4551    }
4552
4553    #[test]
4554    fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
4555        // The operands are checked here rather than by the assembler, because by the time the
4556        // assembler sees the template the operands have become registers and it has nothing left
4557        // to say about the C that named them.
4558        let mut opts = options();
4559        opts.emit = EmitKind::Ir;
4560        for (source, expected) in [
4561            (
4562                "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
4563                "output operand constraint lacks '='",
4564            ),
4565            (
4566                "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
4567                "lvalue required in 'asm' statement",
4568            ),
4569            (
4570                "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
4571                "read-only variable 'g' used as 'asm' output",
4572            ),
4573            (
4574                "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
4575                "input operand constraint contains '='",
4576            ),
4577            (
4578                "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
4579                "memory input 0 is not directly addressable",
4580            ),
4581            ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
4582            (
4583                "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
4584                "duplicate asm operand name 'a'",
4585            ),
4586            ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
4587        ] {
4588            let result = run(&opts, source);
4589            assert!(result.failed(), "expected this to be reported:\n{source}");
4590            assert!(
4591                result.messages.iter().any(|m| m.contains(expected)),
4592                "{expected}\n{:?}",
4593                result.messages
4594            );
4595        }
4596    }
4597
4598    #[test]
4599    fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
4600        let mut opts = options();
4601        opts.emit = EmitKind::Ir;
4602        for source in [
4603            "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
4604            "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
4605        ] {
4606            let result = run(&opts, source);
4607            assert!(result.failed(), "expected this to be reported:\n{source}");
4608            assert!(
4609                result.messages.iter().any(|m| m.contains("not supported yet")),
4610                "{:?}",
4611                result.messages
4612            );
4613        }
4614    }
4615
4616    /// Compiles `source` to IR, reads that back as an input, and gives back both texts.
4617    fn round_trip(source: &str) -> (String, String) {
4618        let printed = ir(source);
4619        let mut opts = options();
4620        opts.emit = EmitKind::Ir;
4621        let mut fs = MemoryFileSystem::new();
4622        fs.insert("/main.ir", printed.clone().into_bytes());
4623        let result = compile_ir(&opts, "/main.ir", &fs);
4624        assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
4625        (printed, result.text().to_owned())
4626    }
4627
4628    #[test]
4629    fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
4630        // The other half of the round trip test below, through the driver rather than through
4631        // the library, which is what makes the property something to run over a real program
4632        // rather than over the modules a test builds.
4633        let (printed, again) = round_trip(
4634            "struct point { int x, y; };\n             static const char greeting[] = \"hi\";\n             int puts(const char *);\n             int f(int n) { struct point p = { n, 1 }; puts(greeting); return p.x; }\n",
4635        );
4636        assert_eq!(printed, again);
4637    }
4638
4639    #[test]
4640    fn ir_that_is_not_ir_says_which_line_stopped_it() {
4641        let mut opts = options();
4642        opts.emit = EmitKind::Ir;
4643        let mut fs = MemoryFileSystem::new();
4644        let text = "\
4645; ModuleID = 'a.c'
4646; format 0
4647target triple = \"x86_64-unknown-linux-gnu\"
4648target datalayout = \"e-p:64:64-i64:64-S128\"
4649
4650func @f(), linkage(external) {
4651block0:
4652    frobnicate
4653}
4654";
4655        fs.insert("/main.ir", text.as_bytes().to_vec());
4656        let result = compile_ir(&opts, "/main.ir", &fs);
4657        assert!(result.failed());
4658        assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
4659    }
4660
4661    #[test]
4662    fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
4663        // A module that a person edited has not been through the verifier, and the return of
4664        // an `i32` from a function that returns nothing is the kind of thing editing produces.
4665        let mut opts = options();
4666        opts.emit = EmitKind::Ir;
4667        let mut fs = MemoryFileSystem::new();
4668        let text = "\
4669; ModuleID = 'a.c'
4670; format 0
4671target triple = \"x86_64-unknown-linux-gnu\"
4672target datalayout = \"e-p:64:64-i64:64-S128\"
4673
4674func @f(), linkage(external) {
4675block0:
4676    %0 = iconst.i32 1
4677    return %0
4678}
4679";
4680        fs.insert("/main.ir", text.as_bytes().to_vec());
4681        let result = compile_ir(&opts, "/main.ir", &fs);
4682        assert!(result.failed());
4683        assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
4684    }
4685
4686    #[test]
4687    fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
4688        // The C that became this is not here any more, so there is nothing to print a tree of.
4689        let mut fs = MemoryFileSystem::new();
4690        fs.insert("/main.ir", Vec::new());
4691        let result = compile_ir(&options(), "/main.ir", &fs);
4692        assert!(result.failed());
4693        assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
4694    }
4695
4696    #[test]
4697    fn the_printed_ir_reads_back_as_the_same_module() {
4698        // The M2 exit criterion: the text is the module and nothing about it is lost by
4699        // writing it down. Anything the printer invents or the parser drops shows up here.
4700        let text = ir("\
4701struct point { int x, y; };
4702static const char greeting[] = \"hi\";
4703int table[4] = { 1, 2, 3 };
4704int puts(const char *);
4705double half(double x) { return x / 2.0; }
4706int f(int n) {
4707  int total = 0;
4708  for (int i = 0; i < n; i++) {
4709    if (i == 3) continue;
4710    total += table[i];
4711  }
4712  switch (n) {
4713    case 0: total = 1;
4714    case 1: total++; break;
4715    default: total = -total;
4716  }
4717  struct point p = { total, 1 };
4718  int *q = &p.y;
4719  puts(greeting);
4720  return p.x + *q;
4721}
4722int dispatch(int c) {
4723  void *p = c ? &&one : &&two;
4724  goto *p;
4725one:
4726  return 1;
4727two:
4728  return 2;
4729}
4730int assembly(int x, int *p) {
4731  int r;
4732  __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
4733  __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
4734  return r;
4735away:
4736  return 0;
4737}
4738");
4739        let mut names = Interner::new();
4740        let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
4741        assert_eq!(rucc_ir::print(&module, &names), text);
4742    }
4743}