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}
72
73impl Compiled {
74    /// Whether anything went wrong badly enough that the output should not be used.
75    #[must_use]
76    pub fn failed(&self) -> bool {
77        self.errors > 0
78    }
79
80    /// The text that was produced, and the empty string for anything that is not text.
81    ///
82    /// A caller that asked for one of the text kinds knows which it asked for, so this saves it
83    /// matching on a variant it has already ruled out.
84    #[must_use]
85    pub fn text(&self) -> &str {
86        match &self.artifact {
87            Artifact::Text(text) => text,
88            _ => "",
89        }
90    }
91}
92
93/// Compiles one file as far as `opts.emit` asks for and renders the result.
94///
95/// `name` is the path as the user wrote it, which is the name every diagnostic about the file
96/// uses. Every kind but the executable produces something today, and that one runs the same front
97/// end and gives back nothing, so that a file with a mistake in it is reported the same way
98/// whichever kind was asked for, rather than compiling silently until the part that is written
99/// notices.
100///
101/// The checking is skipped when the parse reported an error. The two poisoning rules mean a
102/// diagnosed expression produces no further complaints, but a declaration the parser had to skip
103/// past leaves no declaration behind at all, and every later use of that name would be reported
104/// as undeclared. One mistake is worth one message.
105#[must_use]
106pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
107    let mut sess = Session::new(opts.clone());
108    // Before anything else interns a name. The keyword symbols have to be one unbroken run for
109    // a lookup to be a subtraction, and the preprocessor interns every identifier it reads, so
110    // building this after the expansion would mean building it after `char` had been seen.
111    let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
112    let mut diagnostics: Vec<Diagnostic> = Vec::new();
113    // Filled in by the back end when there is one, and empty for every kind that stops before it.
114    let mut fired = Fired::new();
115
116    let bytes = match fs.read(Path::new(name)) {
117        Ok(bytes) => bytes,
118        Err(e) => return failure(format!("{name}: {e}")),
119    };
120    let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
121        return failure(format!("{name}: the source map has no room left for this file"));
122    };
123
124    // Phases 1 to 4. The expanded stream is turned into pp-tokens straight away, because the
125    // include context borrows the source map that rendering a diagnostic reads and the borrow
126    // has to end before anything is rendered.
127    let mut pp = rucc_pp::Preprocessor::new();
128    let predef = rucc_pp::Predef::for_options(opts);
129    let expanded: Vec<PpToken> = {
130        let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
131        cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
132        if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
133            return failure(format!("{name}: the source map has no room for the built in macros"));
134        }
135        pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
136    };
137    diagnostics.extend(pp.take_diagnostics());
138
139    // Phase 7, which is where a spelling becomes a keyword and a preprocessing number becomes
140    // a constant of a type.
141    let cx = Convert {
142        keywords: &keywords,
143        interner: &sess.interner,
144        target: &sess.target,
145        std: opts.std,
146        gnu: opts.gnu_extensions,
147        pedantic: opts.pedantic,
148    };
149    let (tokens, complaints) = convert(&expanded, &cx);
150    diagnostics.extend(complaints);
151
152    let parsed = rucc_parse::parse(
153        &tokens,
154        rucc_parse::Context {
155            interner: &sess.interner,
156            std: opts.std,
157            gnu: opts.gnu_extensions,
158            pedantic: opts.pedantic,
159            error_limit: opts.error_limit as usize,
160        },
161    );
162    let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
163    diagnostics.extend(parsed.diagnostics);
164
165    let mut artifact = Artifact::Nothing;
166    if !parse_failed {
167        let mut checker = Checker::new(
168            &parsed.ast,
169            CheckContext {
170                names: &sess.interner,
171                target: &sess.target,
172                std: opts.std,
173                gnu: opts.gnu_extensions,
174                pedantic: opts.pedantic,
175                error_limit: opts.error_limit as usize,
176            },
177        );
178        checker.check_unit();
179        let checked = checker.finish();
180        if !checked.failed() {
181            match opts.emit {
182                EmitKind::Tast => {
183                    artifact = Artifact::Text(rucc_sema::print(
184                        &checked.tast,
185                        &checked.types,
186                        &sess.interner,
187                    ));
188                }
189                EmitKind::Ir
190                | EmitKind::MirFinal
191                | EmitKind::Asm
192                | EmitKind::Object
193                | EmitKind::Executable => {
194                    let mut lowered = rucc_lower::lower(
195                        name,
196                        rucc_lower::Context {
197                            tast: &checked.tast,
198                            types: &checked.types,
199                            target: &sess.target,
200                            names: &mut sess.interner,
201                        },
202                    );
203                    // The walk reports what it cannot build, and what it did build is printed
204                    // anyway: a file with one construct missing from it is more use to read
205                    // than nothing at all, and the errors are what stop it being compiled.
206                    let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
207                    if !failed {
208                        // The verifier runs on everything the walk builds, always. It is the
209                        // one check that a bug in the walk cannot talk its way past, and a
210                        // wrong instruction found here costs a message rather than an hour
211                        // in front of a debugger over the assembly it turned into.
212                        if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
213                            for error in errors {
214                                diagnostics.push(internal(&format!("invalid IR, {error}")));
215                            }
216                        } else if opts.emit == EmitKind::Ir {
217                            artifact =
218                                Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
219                        } else {
220                            // The back end, which is every pass after the IR and which is
221                            // where a construct nothing has a rule for is finally noticed.
222                            match generate(
223                                &mut lowered.module,
224                                &mut sess.interner,
225                                &sess.target,
226                                opts,
227                                &mut fired,
228                            ) {
229                                Ok(made) => artifact = made,
230                                Err(complaints) => diagnostics.extend(complaints),
231                            }
232                        }
233                    }
234                    diagnostics.extend(lowered.diagnostics);
235                }
236                _ => {}
237            }
238        }
239        diagnostics.extend(checked.diagnostics);
240    }
241
242    let mut messages = Vec::with_capacity(diagnostics.len());
243    let mut errors = 0;
244    for diag in &diagnostics {
245        if diag.severity.is_fatal()
246            || (diag.severity == Severity::Warning && opts.warnings_are_errors)
247        {
248            errors += 1;
249        }
250        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
251    }
252    if errors > 0 {
253        // A tree built from a file that did not compile is not a tree anything should read.
254        artifact = Artifact::Nothing;
255    }
256    // Kept even when the compilation failed, because a rule that fired did fire and a report about
257    // which rules a corpus reaches should not lose the ones a file with a mistake in it reached.
258    Compiled { artifact, messages, errors, fired }
259}
260
261/// Reads one file of IR, checks it, and prints it back.
262///
263/// This is the compiler's own textual IR arriving as an input rather than leaving as an output,
264/// which is what makes the round trip in the M2 exit criterion something to run rather than
265/// something to believe: what the printer wrote is read back, verified, and written again, and
266/// the two files are either the same bytes or they are not.
267///
268/// The verifier runs here for the reason it runs after the walk. A module that was printed by
269/// this compiler has been through it once already, and one that a person edited has not.
270#[must_use]
271pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
272    let mut sess = Session::new(opts.clone());
273    if opts.emit != EmitKind::Ir {
274        return failure(format!(
275            "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
276             the C in front of it became",
277            opts.emit.as_str()
278        ));
279    }
280    let bytes = match fs.read(Path::new(name)) {
281        Ok(bytes) => bytes,
282        Err(e) => return failure(format!("{name}: {e}")),
283    };
284    let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
285        return failure(format!("{name}: this is not text, so it is not IR"));
286    };
287
288    let module = match rucc_ir::parse(text, &mut sess.interner) {
289        Ok(module) => module,
290        Err(error) => {
291            return failure(format!("{name}:{}: {}", error.line, error.message));
292        }
293    };
294    let mut diagnostics: Vec<Diagnostic> = Vec::new();
295    if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
296        for error in errors {
297            diagnostics.push(invalid(&format!("invalid IR, {error}")));
298        }
299    }
300    let mut messages = Vec::with_capacity(diagnostics.len());
301    for diag in &diagnostics {
302        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
303    }
304    let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
305    let artifact = if errors > 0 {
306        Artifact::Nothing
307    } else {
308        Artifact::Text(rucc_ir::print(&module, &sess.interner))
309    };
310    // Nothing here reaches the back end, so no rule fired and there is nothing to record.
311    Compiled { artifact, messages, errors, fired: Fired::new() }
312}
313
314/// Runs the back end over every function in `module` and writes what came out.
315///
316/// One machine function per definition in the module, in the order the module holds them, every
317/// register physical and every frame offset a constant. A declaration has no body and is skipped,
318/// because there is nothing in it to compile.
319///
320/// What the last step is, is the only thing `--emit=mir-final`, `-S` and `-c` disagree about. The
321/// three read the same functions and differ in whether they are printed as machine IR, printed as
322/// assembly, or encoded and put in a file, which is the point of section 11.1 of
323/// `spec/11-asm-objects-debug.md`: a listing that disagrees with the object file beside it is
324/// worse than no listing, and the way to make that impossible is to have one description of an
325/// instruction and two ways of writing it down.
326///
327/// # Errors
328///
329/// One diagnostic per function the back end could not compile, or one about the target when no
330/// back end covers it at all. Every function is attempted rather than stopping at the first, so a
331/// file with three constructs missing from the rule set reports three rather than one at a time.
332fn generate(
333    module: &mut rucc_ir::Module,
334    names: &mut Interner,
335    target: &TargetInfo,
336    opts: &Options,
337    fired: &mut Fired,
338) -> Result<Artifact, Vec<Diagnostic>> {
339    let Some(machine) = Machine::for_target(target) else {
340        return Err(vec![unsupported(&format!(
341            "there is no back end for {} in this compiler yet, so there is nothing to generate",
342            target.triple
343        ))]);
344    };
345    let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
346
347    let mut funcs = Vec::new();
348    let mut complaints = Vec::new();
349    for id in module.funcs() {
350        if module[id].is_declaration() {
351            continue;
352        }
353        match pipeline::compile_recording(&mut module[id], names, &machine, flags, fired) {
354            Ok(func) => funcs.push(func),
355            Err(why) => {
356                let name = names.resolve(module[id].name).to_owned();
357                // The function knows where the instruction came from, so the message lands on
358                // the line somebody wrote rather than on the file as a whole.
359                let span = why.inst().map_or(Span::DUMMY, |inst| module[id].span(inst));
360                let said = format!("cannot generate code for '{name}': {why}");
361                complaints.push(unsupported_at(&said, span));
362            }
363        }
364    }
365    if !complaints.is_empty() {
366        return Err(complaints);
367    }
368    // The variables the file defines, which go through the back end the way the functions did not:
369    // there is nothing in a variable to select instructions for, so the module is what says what
370    // one is right up to the point where it is written down.
371    let globals = match opts.emit {
372        EmitKind::Asm | EmitKind::Object | EmitKind::Executable => {
373            rucc_asm::globals(module, names).map_err(refused)?
374        }
375        _ => rucc_asm::Globals::default(),
376    };
377    // A failure in either of the last two is a bug here rather than a program this compiler is
378    // behind on, because every instruction in a function that got this far came out of the same
379    // description both of them read and every register in it has been allocated.
380    match opts.emit {
381        EmitKind::Asm => {
382            rucc_asm::print(&funcs, &globals, names, target).map(Artifact::Text).map_err(refused)
383        }
384        // An executable is an object as far as this gets: one is what each file of a link
385        // contributes, and the linker is what turns them into the other.
386        EmitKind::Object | EmitKind::Executable => {
387            let text = rucc_asm::assemble(&funcs, names, target).map_err(refused)?;
388            let data = globals.image();
389            // A format with no writer is a target this compiler is behind on and anything else
390            // the writer refused is a bug here, and the two are not the same news to get.
391            rucc_object::write(&text, &data, target).map(Artifact::Object).map_err(
392                |why| match why {
393                    rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
394                    rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
395                },
396            )
397        }
398        _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
399    }
400}
401
402/// What the assembler said, as the kind of news it is.
403///
404/// One of these is about a program and the rest are about this compiler. A thread-local variable
405/// is valid C that the back end does not build yet, and everything else the assembler refuses is
406/// something that should never have reached it.
407fn refused(why: rucc_asm::Error) -> Vec<Diagnostic> {
408    match why {
409        rucc_asm::Error::Thread { .. } => vec![unsupported(&why.to_string())],
410        _ => vec![internal(&why.to_string())],
411    }
412}
413
414/// A diagnostic about a program this compiler is not finished enough to compile.
415///
416/// Not an internal error, because nothing here is wrong: the program is valid C and the part of
417/// the back end that would handle it has not been written. The note says so, so that a report
418/// about one of these is filed against the milestone rather than as a miscompilation.
419fn unsupported(message: &str) -> Diagnostic {
420    unsupported_at(message, Span::DUMMY)
421}
422
423/// The same, about somewhere in the file rather than about the file.
424///
425/// The note names the issue tracker rather than `spec/17-milestones.md`, which is a document
426/// about the plan: a reader who follows it wants to know whether the construct in front of them
427/// is already written down as work, and the milestone list does not answer that.
428fn unsupported_at(message: &str, span: Span) -> Diagnostic {
429    Diagnostic::error(message.to_owned(), span)
430        .with_code("E0653")
431        .note("this construct is not lowered yet, see https://github.com/tamnd/rucc/issues", span)
432}
433
434/// A diagnostic about IR that was handed to us rather than built by us.
435fn invalid(message: &str) -> Diagnostic {
436    Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
437}
438
439/// A diagnostic about this compiler rather than about the program it was given.
440fn internal(message: &str) -> Diagnostic {
441    Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
442        .with_code("E0652")
443        .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
444}
445
446/// A result that is nothing but one message, for the failures that happen before there is
447/// anything to compile.
448fn failure(message: String) -> Compiled {
449    Compiled {
450        artifact: Artifact::Nothing,
451        messages: vec![format!("rucc: error: {message}")],
452        errors: 1,
453        fired: Fired::new(),
454    }
455}
456
457#[cfg(test)]
458mod tests {
459    use rucc_session::{MemoryFileSystem, Std};
460    use rucc_target::Triple;
461
462    use super::*;
463
464    fn options() -> Options {
465        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
466        opts.emit = EmitKind::Tast;
467        opts
468    }
469
470    fn run(opts: &Options, source: &str) -> Compiled {
471        let mut fs = MemoryFileSystem::new();
472        fs.insert("/main.c", source.to_owned().into_bytes());
473        compile(opts, "/main.c", &fs)
474    }
475
476    /// Options with the compiler's own headers on the search path and nothing else, which is
477    /// what a freestanding compilation is. There is no file system underneath these tests,
478    /// so a header that reached for one would fail to resolve and say so.
479    fn freestanding() -> Options {
480        let mut opts = options();
481        opts.hosted = false;
482        opts.search.push_system(rucc_session::runtime::DIR);
483        opts
484    }
485
486    /// The typed tree of a freestanding `source`, insisting that it compiled cleanly.
487    fn shipped(source: &str) -> String {
488        let result = run(&freestanding(), source);
489        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
490        result.text().to_owned()
491    }
492
493    /// The typed tree of `source`, insisting that it compiled cleanly.
494    fn tast(source: &str) -> String {
495        let result = run(&options(), source);
496        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
497        result.text().to_owned()
498    }
499
500    #[test]
501    fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
502        let text = shipped(concat!(
503            "#include <stdarg.h>\n",
504            "int sum(int n, ...) {\n",
505            "  va_list ap, copy;\n",
506            "  va_start(ap, n);\n",
507            "  va_copy(copy, ap);\n",
508            "  int total = va_arg(ap, int) + va_arg(copy, int);\n",
509            "  va_end(ap);\n",
510            "  va_end(copy);\n",
511            "  return total;\n",
512            "}\n",
513        ));
514        assert!(text.contains("va-start"), "{text}");
515        assert!(text.contains("va-copy"), "{text}");
516        assert!(text.contains("va-arg"), "{text}");
517        assert!(text.contains("va-end"), "{text}");
518    }
519
520    /// glibc includes `<stdarg.h>` this way from every header that declares a `vprintf`, and
521    /// what it wants is the type without the four macro names. Answering the whole header
522    /// would put `va_start` in the way of a program that has its own.
523    #[test]
524    fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
525        let text = shipped(concat!(
526            "#define __need___va_list\n",
527            "#include <stdarg.h>\n",
528            "int vprint(const char *f, __gnuc_va_list ap);\n",
529            "#ifdef va_start\n",
530            "#error va_start should not be defined\n",
531            "#endif\n",
532            "#ifdef _VA_LIST_DEFINED\n",
533            "#error va_list should not have been made\n",
534            "#endif\n",
535        ));
536        assert!(text.contains("vprint"), "{text}");
537    }
538
539    /// The same protocol on `<stddef.h>`, which glibc uses far more heavily: `<stdio.h>` asks
540    /// for `size_t` and `NULL` and would be wrong to receive `offsetof` as well.
541    #[test]
542    fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
543        let text = shipped(concat!(
544            "#define __need_size_t\n",
545            "#include <stddef.h>\n",
546            "#ifdef offsetof\n",
547            "#error offsetof should not be defined yet\n",
548            "#endif\n",
549            "#define __need_ptrdiff_t\n",
550            "#include <stddef.h>\n",
551            "#include <stddef.h>\n",
552            "size_t a;\n",
553            "ptrdiff_t b;\n",
554            "wchar_t c;\n",
555            "max_align_t d;\n",
556            "void *e = NULL;\n",
557            "struct P { int x; long y; };\n",
558            "size_t f = offsetof(struct P, y);\n",
559        ));
560        assert!(text.contains("decl #0 a : unsigned long"), "{text}");
561        assert!(text.contains("decl #1 b : long"), "{text}");
562    }
563
564    #[test]
565    fn the_shipped_limits_and_float_are_the_targets_own_answers() {
566        let text = shipped(concat!(
567            "#include <limits.h>\n",
568            "#include <float.h>\n",
569            "int bits = CHAR_BIT;\n",
570            "long big = LONG_MAX;\n",
571            "int low = INT_MIN;\n",
572            "int radix = FLT_RADIX;\n",
573            "int digits = DBL_MANT_DIG;\n",
574        ));
575        assert!(text.contains("const 8 : int"), "{text}");
576        assert!(text.contains("const 9223372036854775807 : long"), "{text}");
577        assert!(text.contains("const 2 : int"), "{text}");
578        assert!(text.contains("const 53 : int"), "{text}");
579    }
580
581    /// Freestanding, so there is no library header to chain to and `<stdint.h>` writes the
582    /// whole set out itself. The widths are the ones the target picked, which is the only
583    /// reason this header is the compiler's.
584    #[test]
585    fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
586        let text = shipped(concat!(
587            "#include <stdint.h>\n",
588            "int64_t a = INT64_C(1);\n",
589            "uint_least16_t b;\n",
590            "intptr_t c;\n",
591            "uintmax_t d = UINTMAX_MAX;\n",
592            "int wide = sizeof(int_fast64_t);\n",
593        ));
594        assert!(text.contains("decl #0 a : long"), "{text}");
595        assert!(text.contains("decl #1 b : unsigned short"), "{text}");
596        assert!(text.contains("decl #2 c : long"), "{text}");
597    }
598
599    #[test]
600    fn the_three_formality_headers_still_have_to_work() {
601        let text = shipped(concat!(
602            "#include <stdbool.h>\n",
603            "#include <stdalign.h>\n",
604            "#include <iso646.h>\n",
605            "#include <stdnoreturn.h>\n",
606            "int t = true and not false;\n",
607            "_Alignas(16) char buf[16];\n",
608            "int a = alignof(long);\n",
609        ));
610        assert!(text.contains("decl #0 t : int"), "{text}");
611        assert!(text.contains("const 8 : unsigned long"), "{text}");
612    }
613
614    /// Including everything twice has to change nothing, because that is what happens in any
615    /// program large enough to matter and a guard that is wrong shows up nowhere else.
616    #[test]
617    fn every_shipped_header_can_be_included_twice() {
618        let mut source = String::new();
619        for _ in 0..2 {
620            for name in rucc_session::runtime::names() {
621                source.push_str(&format!("#include <{name}>\n"));
622            }
623        }
624        source.push_str("int x;\n");
625        let text = shipped(&source);
626        assert!(text.starts_with("decl #0 x : int"), "{text}");
627    }
628
629    #[test]
630    fn a_file_that_is_not_there_says_so_and_produces_nothing() {
631        let fs = MemoryFileSystem::new();
632        let result = compile(&options(), "/nope.c", &fs);
633        assert!(result.failed());
634        assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
635        assert!(result.text().is_empty());
636    }
637
638    #[test]
639    fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
640        let text = tast("int x = 1;\n");
641        let expected = "\
642decl #0 x : int object external static defined
643  init
644    +0
645      const 1 : int
646";
647        assert_eq!(text, expected);
648    }
649
650    #[test]
651    fn the_macros_are_expanded_before_anything_is_parsed() {
652        // The whole pipeline in one line. The bound came out of a macro, so it was expanded,
653        // converted from a preprocessing number to a constant of a type, parsed as an
654        // expression, and folded to the number the array type carries.
655        let text = tast("#define N 2\nint a[N];\n");
656        assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
657    }
658
659    /// A pragma survives the preprocessor on purpose, since what one means is not its
660    /// business, and nothing after it has a place for a `#` in the grammar. `pack` is the one
661    /// the parser reads and every other line is walked past. Both spellings are here because
662    /// they arrive by different routes and only one of them was ever on a line of its own in
663    /// the source.
664    #[test]
665    fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
666        let text = tast(concat!(
667            "#pragma pack(4)\n",
668            "struct s { int a; };\n",
669            "#pragma pack()\n",
670            "int b;\n",
671            "_Pragma(\"GCC visibility push(default)\") int c;\n",
672        ));
673        assert!(text.contains("decl #0 b : int"), "{text}");
674        assert!(text.contains("decl #1 c : int"), "{text}");
675    }
676
677    /// Every number in these two tests was read off gcc 16 on x86-64 under `-std=gnu23`
678    /// rather than reasoned about, which is why they are written as assertions the program
679    /// makes about itself: a compilation with no messages is every one of them holding.
680    ///
681    /// This half is the attributes. `packed` takes the padding out, on the record or on one
682    /// member, `aligned` raises and never lowers, and the two written together are the
683    /// combination that packs and then aligns the whole thing.
684    #[test]
685    fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
686        tast(concat!(
687            "struct A { char c; int i; } __attribute__((packed));\n",
688            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
689            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
690            // `aligned` with nothing in the parentheses is the largest alignment the target
691            // has, which gcc calls BIGGEST_ALIGNMENT and which is sixteen everywhere here.
692            "struct B { char c; int i; } __attribute__((aligned));\n",
693            "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
694            "struct C { char c; int i __attribute__((packed)); };\n",
695            "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
696            "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
697            "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
698            "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
699            "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
700            "struct E { char c; _Alignas(8) int i; };\n",
701            "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
702            "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
703            "struct F { char c; int i __attribute__((aligned(8))); };\n",
704            "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
705            // Two the record already had, so the attribute asks for nothing new, and two
706            // where four was already there, so the attribute is ignored rather than obeyed.
707            "struct G { char c; short s; } __attribute__((aligned(2)));\n",
708            "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
709            "struct H { char c; int i; } __attribute__((aligned(2)));\n",
710            "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
711            // `packed` on a member takes the padding out in front of that member alone, so on
712            // the first one it does nothing and on the second one it does all of it.
713            "struct I { [[gnu::packed]] char c; int i; };\n",
714            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
715            "struct J { char c; [[gnu::packed]] int i; };\n",
716            "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
717            "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
718            "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
719            "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
720            "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
721            "union L { char c; int i; } __attribute__((packed));\n",
722            "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
723            // The armoured spellings, which are the ones a system header writes, since a
724            // program is entitled to a macro called `packed` and is not entitled to one called
725            // `__packed__`. The two names are one attribute and the layout is the same one.
726            "struct O { char c; int i; } __attribute__((__packed__));\n",
727            "_Static_assert(sizeof(struct O) == 5 && _Alignof(struct O) == 1, \"O\");\n",
728            "struct P { char c; int i; } __attribute__((__aligned__(8)));\n",
729            "_Static_assert(sizeof(struct P) == 8 && _Alignof(struct P) == 8, \"P\");\n",
730        ));
731    }
732
733    /// Where a bit-field goes, which packing decides and which is the part of all this that
734    /// is not what the names suggest. A bit-field goes at the next free bit unless that would
735    /// make it span more storage than its own type occupies, and then it moves to the next
736    /// boundary of its alignment. Any packing at all takes that rule out, and `#pragma pack`
737    /// counts even where it lowers nothing, which is the fourth and seventh cases here.
738    ///
739    /// Nothing in the language can be asked where a bit-field is, since `offsetof` refuses one
740    /// and every size below comes out the same either way, so what is asked is the byte a read
741    /// of the field loads from.
742    #[test]
743    fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
744        // A `char` field after twelve bits, which will not straddle unpacked and does packed.
745        assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
746        assert_eq!(
747            bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
748            1
749        );
750        assert_eq!(
751            bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
752            1
753        );
754        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
755        // A thirty bit field after a byte, which is the case the rule was written for.
756        assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
757        assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
758        // Four is what an `int` asked for anyway, so this caps nothing and still counts.
759        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
760        assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
761    }
762
763    /// The byte a read of `s.y` loads from, which is where the bit-field was placed.
764    fn bit_field_byte(record: &str) -> u64 {
765        let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
766        let body = body(&source);
767        let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
768        let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
769        constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
770    }
771
772    /// An attribute in the middle of a specifier list, which is where a member usually carries
773    /// one and which was read and then thrown away. The `[[...]]` spelling and whatever was
774    /// written in front of the declaration are collected as the list is walked and the
775    /// `__attribute__` spelling is put straight on the specifiers, and the two were assigned
776    /// over each other rather than joined.
777    #[test]
778    fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
779        tast(concat!(
780            "struct a { char c; __attribute__((aligned(8))) int i; };\n",
781            "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
782            "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
783            "struct b { char c; __attribute__((packed)) int i; };\n",
784            "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
785            "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
786            "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
787            "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
788        ));
789    }
790
791    /// The other half, which is `#pragma pack`. It caps a member's alignment where `packed`
792    /// drops it, so `pack(2)` leaves a `short` where it was and moves an `int`, and it caps a
793    /// member the program asked to align as well, which is where the two differ. It is read
794    /// at the closing brace of the body, so a line written in the middle of one settles the
795    /// whole record rather than the members after it, and `push` and `pop` nest.
796    #[test]
797    fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
798        tast(concat!(
799            "#pragma pack(1)\n",
800            "struct A { char c; int i; };\n",
801            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
802            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
803            "#pragma pack()\n",
804            "struct B { char c; int i; };\n",
805            "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
806            "#pragma pack(2)\n",
807            "struct C { char c; int i; double d; };\n",
808            "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
809            "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
810            // A member the program aligned, which `pack` caps and `packed` would not.
811            "struct K { char c; int i __attribute__((aligned(8))); };\n",
812            "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
813            "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
814            // The record's own `aligned` is not a member's, so it is not capped.
815            "struct J { char c; int i; } __attribute__((aligned(8)));\n",
816            "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
817            "#pragma pack()\n",
818            "#pragma pack(push, 1)\n",
819            "struct D { char c; short s; };\n",
820            "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
821            "#pragma pack(pop)\n",
822            "struct E { char c; short s; };\n",
823            "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
824            // Written in the middle of a body, and it still settles the whole record.
825            "struct H { char c;\n",
826            "#pragma pack(1)\n",
827            "  int i; };\n",
828            "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
829            "#pragma pack(1)\n",
830            "struct I { char c;\n",
831            "#pragma pack()\n",
832            "  int i; };\n",
833            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
834            "#pragma pack()\n",
835            // Nested pushes, each one giving back what the one under it had.
836            "#pragma pack(push, 8)\n",
837            "#pragma pack(push, 1)\n",
838            "struct P { char c; int i; };\n",
839            "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
840            "#pragma pack(pop)\n",
841            "struct Q { char c; int i; };\n",
842            "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
843            "#pragma pack(pop)\n",
844            // A cap above what every member already asks for changes nothing at all.
845            "#pragma pack(16)\n",
846            "struct R { char c; int i; };\n",
847            "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
848            "#pragma pack()\n",
849            "#pragma pack(1)\n",
850            "struct S { char c; int i : 5; int j : 20; };\n",
851            "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
852            "union T { char c; int i; };\n",
853            "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
854            "#pragma pack()\n",
855        ));
856    }
857
858    /// A line the reader cannot make sense of is a warning and the line is dropped, which is
859    /// what GCC does with one, and these are its words for each of them. The last line is the
860    /// one nothing else would reach, since it stands after every record in the file.
861    #[test]
862    fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
863        let result = run(
864            &options(),
865            concat!(
866                "#pragma pack 4\n",
867                "#pragma pack(pop)\n",
868                "#pragma pack(3)\n",
869                "#pragma pack(1) junk\n",
870                "#pragma pack(push, 1\n",
871                "#pragma pack(x)\n",
872                // These two are well formed and say nothing. Zero is how a line asks for the
873                // target's own alignments back without writing empty parentheses.
874                "#pragma pack(0)\n",
875                "#pragma pack(push)\n",
876                "struct s { char c; int i; };\n",
877                "#pragma pack(pop)\n",
878                "#pragma pack(pop, foo)\n",
879            ),
880        );
881        let expected = [
882            "missing `(` after `#pragma pack` - ignored",
883            "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
884            "alignment must be a small power of two, not 3",
885            "junk at end of `#pragma pack`",
886            "malformed `#pragma pack(push[, id][, <n>])` - ignored",
887            "unknown action `x` for `#pragma pack` - ignored",
888            "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
889        ];
890        assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
891        for (message, want) in result.messages.iter().zip(expected) {
892            assert!(message.contains(want), "expected {want:?} in {message:?}");
893        }
894    }
895
896    /// The two typedef spellings of the 128 bit types. gcc offers them as keywords rather
897    /// than as typedefs in a header, which is the only way a program that includes nothing at
898    /// all can still use them, and Apple's `<mach/arm/_structs.h>` is one such program.
899    #[test]
900    fn the_wide_integer_answers_to_all_three_of_its_names() {
901        let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
902        assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
903        assert!(text.contains("decl #1 b : __int128"), "{text}");
904        assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
905    }
906
907    #[test]
908    fn every_conversion_the_language_performs_is_a_node_in_the_output() {
909        // The point of a typed tree. The source has one operator and the output has the
910        // widening that operator asked for, spelled out, so that nothing downstream has to
911        // work out the conversion rules a second time.
912        let text = tast("long f(int a, long b) { return a + b; }\n");
913        assert!(text.contains("convert arithmetic"), "{text}");
914    }
915
916    #[test]
917    fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
918        for source in [
919            "#error stop\n",
920            "int f(void) { return 1 + ; }\n",
921            "int f(void) { return undeclared; }\n",
922        ] {
923            let result = run(&options(), source);
924            assert!(result.failed(), "expected this to fail:\n{source}");
925            assert!(
926                result.text().is_empty(),
927                "a file that did not compile wrote a tree:\n{source}"
928            );
929        }
930    }
931
932    #[test]
933    fn one_undeclared_name_is_one_message_and_not_one_per_use() {
934        // The poisoning rule from `spec/06-lexer-and-parser.md` section 6.8, seen from the
935        // outside. Three uses of a name that was never declared, and the operators over them
936        // say nothing at all.
937        let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
938        assert_eq!(result.errors, 1, "{:?}", result.messages);
939    }
940
941    #[test]
942    fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
943        // The reason the checking is skipped after a failed parse. The parser gave up on the
944        // first line and there is no `x` in the tree, so a checker run over it would report
945        // every use of `x` below as undeclared, which is a second message about one mistake.
946        let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
947        assert_eq!(result.errors, 1, "{:?}", result.messages);
948    }
949
950    #[test]
951    fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
952        let source = "int f(void) { char c = 300; return c; }\n";
953        let plain = run(&options(), source);
954        assert_eq!(plain.errors, 0, "{:?}", plain.messages);
955        assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
956        assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
957
958        let mut opts = options();
959        opts.warnings_are_errors = true;
960        let strict = run(&opts, source);
961        assert!(strict.failed());
962        assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
963        for message in &strict.messages {
964            assert!(!message.contains("warning:"), "{message}");
965        }
966    }
967
968    #[test]
969    fn the_dialect_reaches_the_keywords_and_the_checking() {
970        // `typeof` is C23's and GNU's, so the same source is a declaration under one dialect
971        // and a mistake under the other, which is the keyword table being built per dialect.
972        let source = "typeof(1) x;\n";
973        let mut opts = options();
974        opts.std = Std::C23;
975        opts.gnu_extensions = false;
976        assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
977
978        opts.std = Std::C17;
979        assert!(run(&opts, source).failed());
980    }
981
982    #[test]
983    fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
984        let mut opts = options();
985        opts.emit = EmitKind::Object;
986        let result = run(&opts, "int x = 1;\n");
987        assert!(!result.failed(), "{:?}", result.messages);
988        assert!(result.text().is_empty());
989        // And it still finds what the checking finds, so a later kind on a broken file is not
990        // a silent success.
991        assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
992    }
993
994    /// The machine code of `source`, insisting that it compiled cleanly.
995    fn mir(source: &str) -> String {
996        let mut opts = options();
997        opts.emit = EmitKind::MirFinal;
998        let result = run(&opts, source);
999        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1000        result.text().to_owned()
1001    }
1002
1003    /// The whole compiler in one assertion, which is what this emit kind is for.
1004    ///
1005    /// C in, machine instructions out, every register a real one and every frame offset a
1006    /// number. Everything between the two is checked somewhere else, one pass at a time. What is
1007    /// checked here is that the passes are joined up and that the driver runs them.
1008    #[test]
1009    fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
1010        let text = mir("int add(int a, int b) { return a + b; }\n");
1011        assert!(text.starts_with("mfunc @add {"), "{text}");
1012        assert!(text.contains("x64.add_rr_32"), "{text}");
1013        assert!(text.contains("x64.ret"), "{text}");
1014        // A virtual register is what the allocator was there to remove, so one left in the
1015        // output is the difference between code and something that looks like code.
1016        assert!(!text.contains('%'), "{text}");
1017    }
1018
1019    /// A declaration has no body, so there is nothing to generate for one and nothing is.
1020    #[test]
1021    fn a_function_with_no_body_produces_no_machine_function() {
1022        let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1023        assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1024        assert!(text.contains("mfunc @f {"), "{text}");
1025        assert!(text.contains("x64.call"), "{text}");
1026    }
1027
1028    /// Two functions come out in the order the module holds them, which is source order.
1029    #[test]
1030    fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1031        let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1032        let first = text.find("mfunc @a").expect("the first function");
1033        let second = text.find("mfunc @b").expect("the second function");
1034        assert!(first < second, "{text}");
1035    }
1036
1037    /// The target reaches the back end, so the same C is different instructions on Windows.
1038    #[test]
1039    fn the_target_decides_which_convention_the_generated_code_follows() {
1040        let mut opts = options();
1041        opts.emit = EmitKind::MirFinal;
1042        let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1043        assert!(linux.contains("$rdi"), "{linux}");
1044
1045        opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1046        let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1047        assert!(windows.contains("$rcx"), "{windows}");
1048        assert!(!windows.contains("$rdi"), "{windows}");
1049    }
1050
1051    /// A target with no back end says so rather than generating something for another machine.
1052    #[test]
1053    fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1054        let mut opts = options();
1055        opts.emit = EmitKind::MirFinal;
1056        opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1057        let result = run(&opts, "int f(int a) { return a; }\n");
1058        assert!(result.failed());
1059        assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1060        assert!(result.text().is_empty());
1061    }
1062
1063    /// A construct the rule set does not reach yet is named, along with the function it is in.
1064    ///
1065    /// The message is about this compiler being unfinished rather than about the program, which
1066    /// is valid C either way, so it carries the note that says where the work is tracked. Both
1067    /// functions are attempted, so a file that is ahead of the back end in three places says so
1068    /// three times rather than one recompilation at a time.
1069    #[test]
1070    fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1071        let mut opts = options();
1072        opts.emit = EmitKind::MirFinal;
1073        let source = "long double a(long double x) { return x; }\n\
1074                      long double b(long double x) { return x; }\n";
1075        let result = run(&opts, source);
1076        assert!(result.failed());
1077        assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1078        assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1079        assert!(result.messages[0].contains("x87 stack"), "{:?}", result);
1080        assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1081        assert!(result.text().is_empty());
1082    }
1083
1084    /// An opcode the rule language has no word for is named anyway, and pointed at.
1085    ///
1086    /// The rule language's spelling is the better name when there is one, but an opcode it has
1087    /// no word for is exactly the opcode no rule lowers, so falling back to the opcode and the
1088    /// type is what makes the message say anything at all in the cases that happen. The span is
1089    /// the instruction's own, so the message lands on the line rather than on the file.
1090    #[test]
1091    fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1092        let mut opts = options();
1093        opts.emit = EmitKind::MirFinal;
1094        let result = run(&opts, "int f(int a) {\n  __int128 wide = a;\n  return (int) wide;\n}\n");
1095        assert!(result.failed());
1096        assert!(
1097            result.messages[0].contains("no rule lowers a `sext` producing a `i128`"),
1098            "{result:?}"
1099        );
1100        assert!(result.messages[0].contains(":2:"), "the line the widening is on: {result:?}");
1101        assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1102    }
1103
1104    /// The note names the issue tracker, which is where a reader finds out whether it is known.
1105    #[test]
1106    fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1107        let mut opts = options();
1108        opts.emit = EmitKind::MirFinal;
1109        let result = run(&opts, "int f(int a) { __int128 wide = a; return (int) wide; }\n");
1110        assert!(result.failed());
1111        let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1112        assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1113        assert!(!note.contains("spec/17-milestones.md"), "{note}");
1114    }
1115
1116    /// The two frame flags reach the frame, which is the only thing either of them does.
1117    #[test]
1118    fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1119        let source = "int f(int a) { return a; }\n";
1120        assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1121
1122        let mut opts = options();
1123        opts.emit = EmitKind::MirFinal;
1124        opts.frame_pointer = true;
1125        let kept = run(&opts, source).text().to_owned();
1126        assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1127    }
1128
1129    /// The assembly of `source`, insisting that it compiled cleanly.
1130    fn asm(source: &str) -> String {
1131        let mut opts = options();
1132        opts.emit = EmitKind::Asm;
1133        let result = run(&opts, source);
1134        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1135        result.text().to_owned()
1136    }
1137
1138    /// `-S`, which is the same compiler as the kind above it with a different last step.
1139    ///
1140    /// What the assembly says is checked in `rucc-asm`, one instruction at a time and against the
1141    /// target's own description of what an instruction is. What is checked here is that a C file
1142    /// goes all the way to a listing an assembler would take, which means the directives around
1143    /// the function as well as the instructions in it.
1144    #[test]
1145    fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1146        let text = asm("int add(int a, int b) { return a + b; }\n");
1147        assert!(text.contains("\t.globl\tadd\n"), "{text}");
1148        assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1149        assert!(text.contains("\nadd:\n"), "{text}");
1150        assert!(text.contains("\taddl\t"), "{text}");
1151        assert!(text.contains("\tret\n"), "{text}");
1152        assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1153        // Without this the stack the program runs on is executable, which is not a default
1154        // anybody chose and is not a thing a reader would notice missing.
1155        assert!(text.contains(".note.GNU-stack"), "{text}");
1156    }
1157
1158    /// A call through a function pointer, which is a different instruction from a call to a name.
1159    ///
1160    /// Both are in the one function on purpose. What is being read is that the two calls are told
1161    /// apart all the way down: one carries a name the linker resolves and one carries a register,
1162    /// and neither turns into the other on the way.
1163    #[test]
1164    fn a_call_through_a_function_pointer_goes_through_the_register_it_is_in() {
1165        let text = asm("int g(int);\nint f(int (*p)(int), int a) { return p(a) + g(a); }\n");
1166        assert!(text.contains("\tcall\t*%"), "{text}");
1167        assert!(text.contains("\tcall\tg\n"), "{text}");
1168        // The address arrived in the first argument register and the argument the call passes has
1169        // to end up there, so the two cannot be the same register and the compiler has to have
1170        // moved one of them.
1171        assert!(text.contains("%rdi"), "{text}");
1172    }
1173
1174    /// A name at file scope, which is the one address a function cannot compute for itself.
1175    #[test]
1176    fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1177        let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1178        assert!(text.contains("\tleaq\tcounter(%rip), "), "{text}");
1179    }
1180
1181    /// A cast between a pointer and an integer as wide as one, which is every one C writes here.
1182    #[test]
1183    fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1184        let text = asm("long f(void *p) { return (long)p; }\n");
1185        // Every instruction in the body is a full width move or the return. The copies are the
1186        // allocator taking no hints, and what matters here is what is not among them: nothing
1187        // narrows the value and nothing widens it again, which is what a cast that did something
1188        // would look like.
1189        for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1190            let mnemonic = line.split_whitespace().next().unwrap_or("");
1191            assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1192        }
1193    }
1194
1195    /// The arguments past the sixth arrive in the caller's memory rather than in a register, and
1196    /// where that memory is depends on what the prologue did, so this is checked at the end of the
1197    /// pipeline rather than in the middle of it.
1198    #[test]
1199    fn an_argument_past_the_last_register_is_read_out_of_the_caller_s_stack() {
1200        let six = "long a, long b, long c, long d, long e, long f";
1201        let text = asm(&format!("long f({six}, long g, long h) {{ return g + h; }}\n"));
1202
1203        // Nothing is pushed and no frame is taken, so the only thing between the stack pointer and
1204        // the caller's arguments is the return address the call pushed. Which is where gcc 16.2.0
1205        // reads them from too, at `-O0`, in the same two instructions.
1206        assert!(text.contains("\tmovq\t8(%rsp), "), "{text}");
1207        assert!(text.contains("\tmovq\t16(%rsp), "), "{text}");
1208
1209        // A narrower one is read at its own width, because the bits above it are bits the
1210        // convention says nothing about, and one in the other register file with the other file's
1211        // instruction.
1212        let narrow = asm(&format!("int f({six}, int g) {{ return g; }}\n"));
1213        assert!(narrow.contains("\tmovl\t8(%rsp), "), "{narrow}");
1214        let eight =
1215            "double a, double b, double c, double d, double e, double f, double g, double h";
1216        let float = asm(&format!("double f({eight}, double i) {{ return i; }}\n"));
1217        assert!(float.contains("\tmovsd\t8(%rsp), "), "{float}");
1218    }
1219
1220    /// The other end of the same thing. What the caller writes is at the stack pointer, because
1221    /// that is the bottom of its frame and the bottom of its frame is where the callee looks.
1222    #[test]
1223    fn a_call_writes_the_arguments_with_no_register_left_at_the_stack_pointer() {
1224        let six = "1, 2, 3, 4, 5, 6";
1225        let decl = "long g(long, long, long, long, long, long, long, long);\n";
1226        let text = asm(&format!("{decl}long f(void) {{ return g({six}, 7, 8); }}\n"));
1227
1228        assert!(text.contains("\tmovq\t%"), "{text}");
1229        assert!(text.contains(", (%rsp)\n"), "{text}");
1230        assert!(text.contains(", 8(%rsp)\n"), "{text}");
1231        // And it reserved the bytes it wrote into, so nothing else in the frame is on top of them.
1232        assert!(text.contains("\tsubq\t$"), "{text}");
1233
1234        // A narrower one is written at its own width, matching what the callee reads it back with.
1235        let narrow = "int g(int, int, int, int, int, int, int);\n";
1236        let text = asm(&format!("{narrow}int f(void) {{ return g({six}, 7); }}\n"));
1237        assert!(text.contains("\tmovl\t%"), "{text}");
1238        assert!(text.contains(", (%rsp)\n"), "{text}");
1239    }
1240
1241    /// The count a variadic callee on this convention reads is a count of vector registers, so a
1242    /// float that ran out of them and went to memory is not in it.
1243    #[test]
1244    fn a_variadic_call_counts_registers_and_not_arguments() {
1245        let nine = "1., 2., 3., 4., 5., 6., 7., 8., 9.";
1246        let decl = "int g(int, ...);\n";
1247        let text = asm(&format!("{decl}int f(void) {{ return g(0, {nine}); }}\n"));
1248
1249        assert!(text.contains("\tmovl\t$8, "), "eight registers, not nine: {text}");
1250        assert!(text.contains("\tmovsd\t%"), "{text}");
1251        assert!(text.contains(", (%rsp)\n"), "{text}");
1252    }
1253
1254    /// The callee's half of the same convention. Every argument register it was handed is written
1255    /// into its frame on the way in, because which of them hold anything is a thing only the caller
1256    /// knew, and the ones the signature does name are left out because `va_start` sets the offsets
1257    /// past them and nothing ever reads their slots.
1258    #[test]
1259    fn a_variadic_function_writes_the_argument_registers_it_was_handed_into_its_frame() {
1260        let body =
1261            "__builtin_va_list ap; __builtin_va_start(ap, n); __builtin_va_end(ap); return n;";
1262        let text = asm(&format!("int f(int n, ...) {{ {body} }}\n"));
1263
1264        // Five general purpose registers and eight vector ones, since the one parameter the
1265        // signature names took the first of the six.
1266        let stores = |mnemonic: &str| text.matches(&format!("\t{mnemonic}\t%")).count();
1267        assert!(text.contains(", 8(%r"), "the second slot, not the first: {text}");
1268        assert!(!text.contains(", 0(%r"), "{text}");
1269        assert_eq!(stores("movsd"), 8, "every vector register: {text}");
1270
1271        // And the area is one of the function's own stack objects, so the frame holds it.
1272        assert!(text.contains("\tsubq\t$"), "{text}");
1273    }
1274
1275    /// What `va_start` writes is the four fields of the list, and the two numbers among them are
1276    /// where the arguments the signature names left the walk over each file's registers.
1277    #[test]
1278    fn va_start_writes_the_four_fields_the_psabi_describes() {
1279        let start = "__builtin_va_list ap; __builtin_va_start(ap, d);";
1280        let params = "int a, int b, int c, double d";
1281        let text = asm(&format!("int f({params}, ...) {{ {start} return a; }}\n"));
1282
1283        // Three integers took three of the six general purpose registers, and one double took one
1284        // of the eight vector ones, so the walk starts at twenty four bytes into the first half and
1285        // sixteen bytes into the second, which begins at forty eight.
1286        assert!(text.contains("	movl	$24, "), "{text}");
1287        assert!(text.contains("	movl	$64, "), "{text}");
1288        // The other two fields are addresses rather than numbers, so each is stored as a word and
1289        // each is a `lea` away. One of them reaches above the frame, which is where the caller's
1290        // arguments are and is the only thing in this function that is not below the stack pointer.
1291        assert!(text.contains(", 8(%r"), "{text}");
1292        assert!(text.contains(", 16(%r"), "{text}");
1293        let frame: u32 = text
1294            .lines()
1295            .find_map(|line| line.trim().strip_prefix("subq	$")?.split(',').next()?.parse().ok())
1296            .expect("a variadic function takes a frame for the save area");
1297        let above = |line: &str| {
1298            let at: u32 = line.trim().strip_prefix("leaq	")?.split('(').next()?.parse().ok()?;
1299            Some(at > frame)
1300        };
1301        assert!(text.lines().filter_map(above).any(|it| it), "{frame}: {text}");
1302    }
1303
1304    /// A `va_arg` is a branch on whether the argument it wants is still in the save area, and which
1305    /// of the two halves it walks is the type's answer.
1306    #[test]
1307    fn va_arg_branches_on_whether_the_argument_is_still_in_the_save_area() {
1308        let read = "__builtin_va_list ap; __builtin_va_start(ap, n);";
1309        let ints = format!("int f(int n, ...) {{ {read} return __builtin_va_arg(ap, int); }}\n");
1310        let text = asm(&ints);
1311
1312        // The last general purpose slot begins at forty, so an offset above it is an argument the
1313        // caller left in its own memory instead.
1314        assert!(text.contains("$40, "), "{text}");
1315        assert!(text.contains("	cmpl	"), "{text}");
1316        assert!(text.contains("	setbe	"), "unsigned, since an offset is a count of bytes: {text}");
1317
1318        let arg = "__builtin_va_arg(ap, double)";
1319        let text = asm(&format!("double f(int n, ...) {{ {read} return {arg}; }}\n"));
1320        assert!(text.contains("$160, "), "the last vector slot: {text}");
1321    }
1322
1323    /// A structure assigned is a copy of a known size, and a copy of a known size is a run of
1324    /// moves rather than a call to a library this compiler has no way to reach yet.
1325    #[test]
1326    fn a_structure_assignment_is_a_move_for_each_word_of_it() {
1327        let decl = "struct pair { long a, b; };\n";
1328        let body = "struct pair p = *q; return p.a + p.b;";
1329        let text = asm(&format!("{decl}long f(struct pair *q) {{ {body} }}\n"));
1330
1331        assert!(!text.contains("memcpy"), "nothing calls the library: {text}");
1332        assert!(!text.contains("\tcall"), "{text}");
1333        // Sixteen bytes aligned to eight is two words, and each is a load and a store.
1334        assert!(text.matches("\tmovq\t").count() >= 4, "two words each way: {text}");
1335    }
1336
1337    /// A word is as wide as the object is aligned to and no wider, so a character array is copied
1338    /// a byte at a time and a structure of longs eight bytes at a time.
1339    #[test]
1340    fn how_wide_a_word_of_a_copy_is_follows_the_alignment() {
1341        let decl = "struct bytes { char a[8]; };\n";
1342        let body = "struct bytes p = *q; return p.a[0];";
1343        let text = asm(&format!("{decl}int f(struct bytes *q) {{ {body} }}\n"));
1344
1345        // Eight bytes aligned to one is eight words, and each is a load and a store.
1346        assert!(text.matches("\tmovb\t").count() >= 16, "a byte at a time: {text}");
1347    }
1348
1349    /// What an initialiser does not name is zero, which the front end writes as a fill and this
1350    /// writes as the byte spread across each word.
1351    #[test]
1352    fn the_part_of_an_initialiser_that_names_nothing_is_stored_as_zero() {
1353        let decl = "struct wide { long a, b, c; };\n";
1354        let text = asm(&format!("{decl}long f(void) {{ struct wide w = {{ 7 }}; return w.c; }}\n"));
1355
1356        assert!(!text.contains("memset"), "nothing calls the library: {text}");
1357        assert!(text.contains("\tmovq\t$0, ") || text.contains("$0, %"), "the zero: {text}");
1358    }
1359
1360    /// A copy too large to be worth unrolling is a call to the runtime, which is the C library on
1361    /// a hosted target and `rucc-builtins` on a freestanding one.
1362    #[test]
1363    fn a_copy_too_large_to_unroll_calls_the_runtime() {
1364        let decl = "struct huge { char a[4096]; };\n";
1365        let mut opts = options();
1366        opts.emit = EmitKind::Asm;
1367        let source = format!("{decl}void f(struct huge *p, struct huge *q) {{ *p = *q; }}\n");
1368        let result = run(&opts, &source);
1369        assert!(!result.failed(), "{:?}", result.messages);
1370        let text = result.text();
1371        assert!(text.contains("call") && text.contains("memcpy"), "{text}");
1372        // The size in the register the convention passes the third argument in, which is what
1373        // says the call was built from the convention and not from the shape of the IR.
1374        assert!(text.contains("4096"), "the size travels: {text}");
1375    }
1376
1377    /// A frame that had to force its own alignment cannot say how far away the caller's stack
1378    /// pointer was, so it reaches back through the frame pointer instead.
1379    #[test]
1380    fn a_realigned_frame_reads_them_through_the_frame_pointer() {
1381        let six = "long a, long b, long c, long d, long e, long f";
1382        let body = "_Alignas(32) long wide[4]; wide[0] = g; return wide[0];";
1383        let text = asm(&format!("long f({six}, long g) {{ {body} }}\n"));
1384
1385        // The frame pointer is saved and pointed at where it was saved before the alignment is
1386        // forced, so the caller's arguments stay a constant distance from it: one word for the
1387        // saved frame pointer and one for the return address.
1388        assert!(text.contains("\tandq\t$-32, %rsp"), "{text}");
1389        assert!(text.contains("\tmovq\t16(%rbp), "), "{text}");
1390        assert!(!text.contains("\tmovq\t16(%rsp), "), "{text}");
1391    }
1392
1393    /// The object format decides the directives, and the target decides the object format.
1394    #[test]
1395    fn the_target_decides_how_the_assembly_is_spelled() {
1396        let mut opts = options();
1397        opts.emit = EmitKind::Asm;
1398        opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1399        let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1400        assert!(text.contains("__TEXT,__text"), "{text}");
1401        assert!(text.contains("\n_f:\n"), "{text}");
1402        assert!(!text.contains(".note.GNU-stack"), "{text}");
1403    }
1404
1405    /// The object file of `source`, insisting that it compiled cleanly.
1406    fn obj(source: &str) -> Vec<u8> {
1407        let mut opts = options();
1408        opts.emit = EmitKind::Object;
1409        let result = run(&opts, source);
1410        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1411        match result.artifact {
1412            Artifact::Object(bytes) => bytes,
1413            other => panic!("expected an object, got {other:?}"),
1414        }
1415    }
1416
1417    /// `-c`, which is the last step of the three the back end can end with.
1418    ///
1419    /// What is in the file is checked in `rucc-object`, a field at a time. What is checked here is
1420    /// that a C file goes all the way to one, which is the whole compiler in one line and the
1421    /// thing that stops working when a layer between them changes its mind about something.
1422    #[test]
1423    fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1424        let bytes = obj("int add(int a, int b) { return a + b; }\n");
1425        assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1426        let text = asm("int add(int a, int b) { return a + b; }\n");
1427        assert!(
1428            text.contains("\taddl\t"),
1429            "and the listing of it is the same instructions:\n{text}"
1430        );
1431    }
1432
1433    /// A variable this file defines, which is what a reference to one has to resolve against.
1434    #[test]
1435    fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
1436        let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
1437        assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
1438        assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
1439        assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
1440        // A zeroed variable carries its size and none of its bytes, and a `static` one is not
1441        // announced to the linker at all, which is the whole of what `static` means here.
1442        assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
1443        assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
1444        assert!(!text.contains(".globl\thidden"), "{text}");
1445        // Nothing writes through it, so it goes in a page the loader can map read only and every
1446        // process running the program can share.
1447        assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1448    }
1449
1450    /// A string literal, which is a variable the program never named.
1451    #[test]
1452    fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
1453        let text = asm("const char *f(void) { return \"hi\"; }\n");
1454        assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
1455        assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1456        let label = text
1457            .lines()
1458            .find(|line| line.starts_with(".Lstr"))
1459            .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
1460        assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
1461    }
1462
1463    /// A variable holding the address of another one, which is the only hole an image has in it.
1464    #[test]
1465    fn an_address_in_an_initializer_is_left_to_the_linker() {
1466        let source = "int counter;\nint *p = &counter;\n";
1467        let text = asm(source);
1468        assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
1469        // And in the object it is eight zero bytes and a relocation, which is what the two paths
1470        // being one description is for.
1471        let bytes = obj(source);
1472        assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
1473    }
1474
1475    /// A thread-local variable, which is valid C that the back end does not build yet.
1476    #[test]
1477    fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
1478        let mut opts = options();
1479        opts.emit = EmitKind::Asm;
1480        let result = run(&opts, "_Thread_local int x = 1;\n");
1481        assert!(result.failed(), "every thread sharing one variable is worse than a message");
1482        assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
1483        // Not an internal error: nothing here is wrong and the note says where the work is.
1484        assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
1485    }
1486
1487    /// Not a rewording of the check above: what the two paths agree about is the point.
1488    #[test]
1489    fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
1490        // A call, because it is the one thing whose spelling in the two differs completely: the
1491        // listing writes a name and the object writes four zero bytes and a relocation asking the
1492        // linker for the same name. If either path had lost the callee, one of these would fail.
1493        let source = "int callee(void); int g(void) { return callee(); }\n";
1494        let bytes = obj(source);
1495        assert!(
1496            bytes.windows(7).any(|w| w == b"callee\0"),
1497            "the object has to name the callee for the linker to find it"
1498        );
1499        let text = asm(source);
1500        assert!(text.contains("\tcall\tcallee\n"), "{text}");
1501    }
1502
1503    /// What a file of a link contributes is an object, and the default emit is a link.
1504    ///
1505    /// This is here because getting it wrong is silent in the worst way: an empty file is a valid
1506    /// empty linker script, so a link fed one gets as far as reporting every symbol of the file as
1507    /// undefined and says nothing about the compilation that produced nothing.
1508    #[test]
1509    fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
1510        let mut opts = options();
1511        // What a command line with no `-c` and no `-S` on it asks for.
1512        opts.emit = EmitKind::Executable;
1513        let result = run(&opts, "int main(void) { return 0; }\n");
1514        assert_eq!(result.messages, Vec::<String>::new());
1515        match result.artifact {
1516            Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
1517            other => panic!("expected an object, got {other:?}"),
1518        }
1519    }
1520
1521    /// A target with a back end but no object writer says so rather than writing the wrong file.
1522    #[test]
1523    fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
1524        let mut opts = options();
1525        opts.emit = EmitKind::Object;
1526        opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1527        let result = run(&opts, "int f(void) { return 0; }\n");
1528        assert!(result.failed(), "an object nobody can read is worse than a message");
1529        assert!(
1530            result.messages.iter().any(|m| m.contains("no object writer")),
1531            "{:?}",
1532            result.messages
1533        );
1534    }
1535
1536    /// The IR of `source`, insisting that it compiled cleanly.
1537    fn ir(source: &str) -> String {
1538        let mut opts = options();
1539        opts.emit = EmitKind::Ir;
1540        let result = run(&opts, source);
1541        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1542        result.text().to_owned()
1543    }
1544
1545    /// The body of the one function in `source`, which is what most of these are about.
1546    fn body(source: &str) -> String {
1547        let text = ir(source);
1548        let (_, rest) = text.split_once("{\n").expect("a function definition");
1549        let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
1550        body.to_owned()
1551    }
1552
1553    /// `__builtin_constant_p` is answered in the front end and never reaches the IR.
1554    ///
1555    /// gcc folds it after optimization, so its answer for an argument that is not written as a
1556    /// constant can differ between `-O0` and `-O2`. What is checked here is the front end's
1557    /// answer, which is the same at every level, and the four cases where gcc gives the same
1558    /// answer at both levels are the ones measured on gcc 16: a literal is one, a variable is
1559    /// zero, a string literal is one and the address of an object is zero.
1560    #[test]
1561    fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
1562        let text = ir(concat!(
1563            "int g;\n",
1564            "int a = __builtin_constant_p(1);\n",
1565            "int b = __builtin_constant_p(g);\n",
1566            "int c = __builtin_constant_p(\"abc\");\n",
1567            "int d = __builtin_constant_p(&g);\n",
1568            "int e = __builtin_constant_p(1.5);\n",
1569            "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
1570        ));
1571        assert!(text.contains("global @a : i32 = 1,"), "{text}");
1572        assert!(text.contains("global @b : i32 = 0,"), "{text}");
1573        assert!(text.contains("global @c : i32 = 1,"), "{text}");
1574        assert!(text.contains("global @d : i32 = 0,"), "{text}");
1575        assert!(text.contains("global @e : i32 = 1,"), "{text}");
1576        assert!(text.contains("global @h : i32 = 11,"), "{text}");
1577        assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
1578
1579        // The argument is not evaluated, which is what gcc does with it as well, so `i` is
1580        // still zero. The second constant is the answer, which nothing reads and which the
1581        // first pass that looks for dead code will take out.
1582        let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
1583        assert_eq!(text, "block0:\n    %0 = iconst.i32 0\n    %1 = iconst.i32 0\n    return %0\n");
1584    }
1585
1586    /// A library builtin is the library function of the same name, and the call says so.
1587    ///
1588    /// A program writes `__builtin_strlen` rather than `strlen` to reach the function the C
1589    /// library promises where its own name has been taken by a macro, and to say that the usual
1590    /// meaning is the one intended. So the name in the program and the name in the object file
1591    /// are two different names and the call carries the second one. gcc folds several of these
1592    /// when the arguments allow it, which is an optimization on top of a call that is already
1593    /// right rather than instead of it, so nothing here depends on any folding happening.
1594    #[test]
1595    fn a_call_to_a_library_builtin_reaches_the_library_function() {
1596        let text = body("void f(void) { __builtin_abort(); }\n");
1597        assert_eq!(text, "block0:\n    call @abort() : ()\n    return\n");
1598
1599        // Nothing declared either of these and nothing had to: the prefix is what says the name
1600        // belongs to the implementation, and the type comes out of `features.toml`.
1601        let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
1602        assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
1603        assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
1604        assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
1605    }
1606
1607    /// The hint builtins are their first argument, and nothing is left of the hint.
1608    ///
1609    /// Which way a branch is expected to go is the whole of what they say, and there is nothing
1610    /// here that reads a branch weight yet, so what reaches the IR is the value and the hint is
1611    /// gone. The one thing the prototype has to keep doing is converting: gcc gives both of them
1612    /// a `long` result, so `sizeof(__builtin_expect((char)1, 1))` is eight and a narrower argument
1613    /// widens before it is answered with.
1614    ///
1615    /// The arguments after the first are checked and then dropped, so a side effect in one does
1616    /// not happen. That is what gcc does with them too, measured on gcc 16.2.0: the `i` below
1617    /// comes back zero there as well.
1618    #[test]
1619    fn the_hint_builtins_are_their_first_argument_and_the_hint_leaves_no_trace() {
1620        let text = ir(concat!(
1621            "long a = __builtin_expect(7, 1);\n",
1622            "long b = __builtin_expect_with_probability(9, 1, 0.9);\n",
1623            "unsigned long c = sizeof(__builtin_expect((char)1, 1));\n",
1624        ));
1625        assert!(text.contains("global @a : i64 = 7,"), "{text}");
1626        assert!(text.contains("global @b : i64 = 9,"), "{text}");
1627        assert!(text.contains("global @c : i64 = 8,"), "{text}");
1628        assert!(!text.contains("__builtin_expect"), "it is not a call to anything:\n{text}");
1629
1630        // A narrower argument is widened by the prototype before it is handed back, and it is
1631        // widened with its sign, since the parameter is a signed `long`.
1632        let text = body("long f(char c) { return __builtin_expect(c, 1); }\n");
1633        assert!(text.contains("sext"), "{text}");
1634
1635        // The second argument is not evaluated, so `i` is still zero, and neither is the third.
1636        // What is left of each statement is the first argument widened, which nothing reads and
1637        // which the first pass that looks for dead code will take out.
1638        let one = "block0:\n    %0 = iconst.i32 0\n    %1 = iconst.i32 1\n    %2 = sext.i64 %1\n    return %0\n";
1639        assert_eq!(body("int f(void) { int i = 0; __builtin_expect(1, i++); return i; }\n"), one);
1640        let source = "int g(void) { int i = 0; __builtin_expect_with_probability(1, i++, 0.5); return i; }\n";
1641        assert_eq!(body(source), one);
1642    }
1643
1644    /// A point control does not arrive at, in both of the ways the compiler has one.
1645    ///
1646    /// `__builtin_unreachable()` is the promise written down, and a function whose body can run
1647    /// off the bottom is the walk arriving at the same place on its own. Neither writes an
1648    /// instruction, which is what gcc 16.2.0 does at `-O0`: it emits the epilogue and the `ret`
1649    /// for both of the functions below and nothing else, and the two of them come out byte for
1650    /// byte the same there.
1651    ///
1652    /// The `ret` is the part worth holding on to. It is not there because anything runs it, it is
1653    /// there because a function whose last instruction is not a return is one that falls into
1654    /// whatever the assembler puts after it.
1655    #[test]
1656    fn a_promise_that_control_does_not_arrive_writes_no_instruction() {
1657        let promised = "int f(int x) { if (x) return 1; __builtin_unreachable(); }\n";
1658        let text = ir(promised);
1659        assert!(text.contains("    unreachable_hint\n"), "{text}");
1660        assert!(!text.contains("call"), "it is not a call to anything:\n{text}");
1661
1662        // The statement after it is still lowered. Continuing to translate a path the program
1663        // promised is dead is one of the things a compiler may do with undefined behaviour, and
1664        // it is the one that keeps a program built at `-O0` behaving the way it was watched to.
1665        let after = body("int g(int x) { __builtin_unreachable(); return x; }\n");
1666        assert!(after.contains("return"), "{after}");
1667
1668        // Both functions are the same instructions, because the hint writes none of them and the
1669        // terminator underneath it writes none either.
1670        let text = asm(promised);
1671        let mine = text.split_once("\nf:\n").expect("a definition").1;
1672        let mine = mine.split_once("\t.size").expect("a definition").0;
1673        let plain = asm("int f(int x) { if (x) return 1; }\n");
1674        let plain = plain.split_once("\nf:\n").expect("a definition").1;
1675        let plain = plain.split_once("\t.size").expect("a definition").0;
1676        assert_eq!(mine, plain);
1677        assert!(mine.trim_end().ends_with("ret"), "{mine}");
1678        assert!(!mine.contains("ud2"), "{mine}");
1679    }
1680
1681    /// The two names stay apart, which is what having both of them is for.
1682    ///
1683    /// The one the program wrote is what the call is checked against and what a diagnostic about
1684    /// it says, and the one the library defines is what the call ends up carrying. A compiler
1685    /// that kept only the second would report this against `abort`, which is a function the
1686    /// program never mentions.
1687    #[test]
1688    fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
1689        let mut opts = options();
1690        opts.emit = EmitKind::Ir;
1691        let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
1692        assert!(
1693            messages.iter().any(|m| m.contains("__builtin_abort")),
1694            "expected the written name in {messages:?}"
1695        );
1696    }
1697
1698    /// A builtin nothing lowers is refused where it is written, rather than at the link.
1699    ///
1700    /// The names are one from each shape the table holds: a `__builtin_` with a prototype, one
1701    /// whose type comes from the call it was written in, and one from each of the two older
1702    /// families whose prefix is not `__builtin_`. What the message has to carry is the name,
1703    /// because the whole complaint about the link error this replaces is that the name in it was
1704    /// one the compiler chose.
1705    #[test]
1706    fn a_builtin_nothing_lowers_is_refused_by_name() {
1707        let mut opts = options();
1708        opts.emit = EmitKind::Ir;
1709        for (builtin, call) in [
1710            ("__builtin_clz", "__builtin_clz(1u)"),
1711            ("__builtin_alloca", "(int)(long)__builtin_alloca(8)"),
1712            ("__atomic_load_n", "__atomic_load_n(&counter, 0)"),
1713            ("__sync_fetch_and_add", "(int)__sync_fetch_and_add(&counter, 1)"),
1714        ] {
1715            let source = format!("int counter;\nint f(void) {{ return {call}; }}\n");
1716            let messages = run(&opts, &source).messages;
1717            let named = messages.iter().any(|m| m.contains(builtin) && m.contains("E0686"));
1718            assert!(named, "expected {builtin} to be refused by name in {messages:?}");
1719        }
1720    }
1721
1722    /// The refusal is about a call and not about the name, so the rest of what C does with one
1723    /// still works.
1724    ///
1725    /// `sizeof` does not evaluate its operand, so nothing is called and there is nothing to
1726    /// refuse; the type of the call is what it asks for and that comes from the front end. A
1727    /// program that defines the name itself gets the function it wrote, which is not what this
1728    /// is for but is what a definition in front of us means.
1729    #[test]
1730    fn what_is_refused_is_the_call_and_not_the_name() {
1731        let text = ir("unsigned long n = sizeof(__builtin_clz(1u));\n");
1732        assert!(text.contains("global @n : i64 = 4,"), "{text}");
1733
1734        let text = ir(
1735            "int __builtin_clz(unsigned x) { return 1; }\nint f(void) { return __builtin_clz(2u); }\n",
1736        );
1737        assert!(text.contains("call @__builtin_clz"), "{text}");
1738    }
1739
1740    /// A `static` function nothing refers to is not emitted, and one that is refered to is.
1741    ///
1742    /// The pair is written as one program so that the two answers come out of one walk. What
1743    /// makes the difference is the call in `main` and nothing else about either definition.
1744    #[test]
1745    fn a_static_function_nothing_refers_to_is_not_emitted() {
1746        let text = ir("static int dropped(void) { return 1; }\n\
1747                       static int kept(void) { return 2; }\n\
1748                       int main(void) { return kept(); }\n");
1749        assert!(text.contains("func @kept"), "{text}");
1750        assert!(!text.contains("dropped"), "{text}");
1751    }
1752
1753    /// The set is transitive, so two of them that only call each other are both dropped.
1754    ///
1755    /// Counting the references to a name would keep this pair, since each is named once, and
1756    /// that is the mistake this is here to catch: what decides it is whether a root reaches the
1757    /// definition, and a root is something the file has a reason to emit on its own.
1758    #[test]
1759    fn two_static_functions_that_only_call_each_other_are_both_dropped() {
1760        let text = ir("static int ping(void);\n\
1761                       static int pong(void) { return ping(); }\n\
1762                       static int ping(void) { return pong(); }\n\
1763                       int main(void) { return 0; }\n");
1764        assert!(!text.contains("ping"), "{text}");
1765        assert!(!text.contains("pong"), "{text}");
1766    }
1767
1768    /// Everything that names a function keeps it, whether or not the name is being called.
1769    ///
1770    /// An address taken in a body, an image that holds one, and a body that is only reached
1771    /// through another `static` function are three different ways for a definition to be needed
1772    /// and none of them is a call at the top level of a reachable function.
1773    #[test]
1774    fn naming_a_static_function_anywhere_keeps_it() {
1775        let text = ir("static int by_address(void) { return 1; }\n\
1776                       static int in_an_image(void) { return 2; }\n\
1777                       static int deeper(void) { return 3; }\n\
1778                       static int reaches_deeper(void) { return deeper(); }\n\
1779                       static int (*table[1])(void) = {in_an_image};\n\
1780                       int main(void) {\n\
1781                         int (*p)(void) = by_address;\n\
1782                         return p() + table[0]() + reaches_deeper();\n\
1783                       }\n");
1784        for kept in ["by_address", "in_an_image", "deeper", "reaches_deeper"] {
1785            assert!(text.contains(&format!("func @{kept}")), "expected {kept} in:\n{text}");
1786        }
1787    }
1788
1789    /// An attribute that says something outside the file reaches it keeps the definition.
1790    ///
1791    /// None of the five is implemented as anything else yet, and this is the part of each of
1792    /// them that a program notices first: a symbol a linker script names or a function the
1793    /// run-up to `main` calls is not written about anywhere a C file can see.
1794    #[test]
1795    fn an_attribute_keeps_a_static_function_nothing_refers_to() {
1796        for attribute in ["used", "retain", "constructor", "destructor", "__used__"] {
1797            let source = format!(
1798                "__attribute__(({attribute})) static int kept(void) {{ return 1; }}\n\
1799                 int main(void) {{ return 0; }}\n"
1800            );
1801            let text = ir(&source);
1802            assert!(text.contains("func @kept"), "for {attribute}:\n{text}");
1803        }
1804    }
1805
1806    /// A function with external linkage is emitted whatever this file does with it, because
1807    /// another one may call it, and that is what external linkage is.
1808    #[test]
1809    fn a_function_anything_could_call_is_emitted_without_being_called() {
1810        let text =
1811            ir("int nobody_here_calls_it(void) { return 1; }\nint main(void) { return 0; }\n");
1812        assert!(text.contains("func @nobody_here_calls_it"), "{text}");
1813    }
1814
1815    /// Four of the classification builtins are operators C already has, and become those.
1816    ///
1817    /// What the standard's macro promises over the operator is that it does not raise the
1818    /// invalid operation exception on a quiet NaN. This compiler does not model floating point
1819    /// exceptions, so there is nothing left for a node of its own to carry and a second way of
1820    /// spelling a comparison would be a second thing every pass has to know about.
1821    #[test]
1822    fn a_classification_c_has_an_operator_for_is_that_operator() {
1823        for (builtin, operator) in [
1824            ("__builtin_isgreater", "binary >"),
1825            ("__builtin_isgreaterequal", "binary >="),
1826            ("__builtin_isless", "binary <"),
1827            ("__builtin_islessequal", "binary <="),
1828        ] {
1829            let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
1830            let text = tast(&source);
1831            assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
1832        }
1833    }
1834
1835    /// The rest of the family are comparisons in the IR and never a call to anything.
1836    ///
1837    /// `math.h` defines the macro of each of these names as the builtin of the same name, so
1838    /// there is no function under any of them for a call to reach. `isunordered` and
1839    /// `islessgreater` are predicates the IR's comparison already has, `isnan` is the value that
1840    /// is unordered with itself, and the two that ask about a magnitude are written against the
1841    /// infinities. `signbit` is the one that is not a question about the value, since a negative
1842    /// zero compares equal to a positive one, so its answer comes from the bits.
1843    #[test]
1844    fn the_classification_builtins_are_comparisons_and_not_calls() {
1845        let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
1846        assert_eq!(
1847            text,
1848            "block0(%0: f64, %1: f64):\n    %2 = fcmp uno %0, %1\n    %3 = zext.i32 \
1849                          %2\n    return %3\n"
1850        );
1851
1852        // Not `x != y`, which is true when the two are unordered and so is true of a NaN.
1853        let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
1854        assert!(text.contains("fcmp one %0, %1"), "{text}");
1855
1856        let text = body("int f(double x) { return __builtin_isnan(x); }\n");
1857        assert!(text.contains("fcmp uno %0, %0"), "{text}");
1858
1859        let text = body("int f(double x) { return __builtin_isinf(x); }\n");
1860        assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
1861        assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
1862        assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1863        assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1864        assert!(text.contains("%5 = or %3, %4"), "{text}");
1865
1866        // Strictly between the two infinities, which a NaN is not, because an ordered comparison
1867        // against either of them is false. That is what makes this one test rather than two.
1868        let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
1869        assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
1870        assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
1871        assert!(text.contains("%5 = and %3, %4"), "{text}");
1872
1873        let text = body("int f(double x) { return __builtin_signbit(x); }\n");
1874        assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1875        assert!(text.contains("icmp slt %1, %2"), "{text}");
1876
1877        // The same question of a value in the target's widest format, where the bits are eighty
1878        // and the object they sit in is sixteen bytes.
1879        let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
1880        assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
1881
1882        // The operand is evaluated once however many times it is compared, which is the whole
1883        // reason these are nodes rather than a rewriting into the operators.
1884        let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
1885        assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1886    }
1887
1888    /// A spelling that names a width converts its argument before it asks.
1889    ///
1890    /// gcc gives `__builtin_isinff` a `float` parameter and `__builtin_isinf` no parameter type
1891    /// at all, and the difference is visible rather than academic: `1e300` does not fit in a
1892    /// `float`, so converting it first is an infinity and not converting it is not. Both numbers
1893    /// here are what gcc 16 gives.
1894    #[test]
1895    fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
1896        let text = ir(concat!(
1897            "int a = __builtin_isinff(1e300);\n",
1898            "int b = __builtin_isinf(1e300);\n",
1899            // Folded here rather than compared at run time, because a question about a value has
1900            // an answer as soon as the value is a constant, and an initializer for an object
1901            // with static storage duration has to have one.
1902            "int c = __builtin_isnan(0.0);\n",
1903            "int d = __builtin_signbit(-0.0);\n",
1904            "int e = __builtin_islessgreater(1.0, 2.0);\n",
1905        ));
1906        assert!(text.contains("global @a : i32 = 1,"), "{text}");
1907        assert!(text.contains("global @b : i32 = 0,"), "{text}");
1908        assert!(text.contains("global @c : i32 = 0,"), "{text}");
1909        assert!(text.contains("global @d : i32 = 1,"), "{text}");
1910        assert!(text.contains("global @e : i32 = 1,"), "{text}");
1911    }
1912
1913    /// An argument that is not floating point is refused, in gcc's words.
1914    #[test]
1915    fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
1916        let mut opts = options();
1917        opts.emit = EmitKind::Ir;
1918        let source = concat!(
1919            "int a(int x) { return __builtin_isnan(x); }\n",
1920            "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
1921            "int c(double x) { return __builtin_isnan(x, x); }\n",
1922        );
1923        let messages = run(&opts, source).messages;
1924        assert_eq!(
1925            messages,
1926            [
1927                "/main.c:1:23: error: non-floating-point argument in call to function \
1928                 '__builtin_isnan' [E0685]",
1929                "/main.c:2:30: error: non-floating-point arguments in call to function \
1930                 '__builtin_isunordered' [E0685]",
1931                "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
1932            ]
1933        );
1934    }
1935
1936    /// The three of the family that need a constant of the format other than an infinity.
1937    ///
1938    /// `isnormal` is the one that needs the smallest normal, and it is asked of the magnitude, so
1939    /// the sign comes off first and what is left is the same shape as `isfinite`. `isinf_sign` is
1940    /// the one whose answer is a number: the two comparisons `isinf` builds, subtracted rather
1941    /// than combined. `fpclassify` is four questions of one value and five answers to pick from,
1942    /// and the picking is a mask because all five are constants and neither of them can have an
1943    /// effect.
1944    #[test]
1945    fn the_last_three_classification_builtins_are_comparisons_and_not_calls() {
1946        let text = body("int f(double x) { return __builtin_isnormal(x); }\n");
1947        // The sign off, which is the magnitude, and then the range, asked of the bits rather than
1948        // of the number, since the encoding of a value whose sign bit is clear rises with the
1949        // value in every format this compiles for.
1950        assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
1951        assert!(text.contains("%2 = iconst.i64 9223372036854775807"), "{text}");
1952        assert!(text.contains("%3 = and %1, %2"), "{text}");
1953        assert!(text.contains("%4 = iconst.i64 4503599627370496"), "{text}");
1954        assert!(text.contains("%5 = iconst.i64 9218868437227405312"), "{text}");
1955        assert!(text.contains("%6 = icmp uge %3, %4"), "{text}");
1956        assert!(text.contains("%7 = icmp ult %3, %5"), "{text}");
1957        assert!(text.contains("%8 = and %6, %7"), "{text}");
1958
1959        // The same question in the target's widest format, where the smallest normal has the
1960        // leading significand bit stored rather than implied, so its encoding is two bits and not
1961        // one.
1962        let text = body("int f(long double x) { return __builtin_isnormal(x); }\n");
1963        assert!(text.contains("%4 = iconst.i80 27670116110564327424"), "{text}");
1964        assert!(text.contains("%5 = iconst.i80 604453686435277732577280"), "{text}");
1965
1966        let text = body("int f(double x) { return __builtin_isinf_sign(x); }\n");
1967        assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
1968        assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
1969        assert!(text.contains("%7 = sub %5, %6"), "{text}");
1970
1971        let text = body("int f(double x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n");
1972        assert!(text.contains("fcmp uno %0, %0"), "{text}");
1973        assert!(text.contains("fcmp oeq %0, %6"), "{text}");
1974        // Four questions, each of them a bit widened into the type of the answer and then spread
1975        // into a mask that picks between the answer and whatever the questions after it settled
1976        // on. Nothing sign extends, because no rule lowers a sign extension out of one bit.
1977        assert_eq!(text.matches(" = zext.i32 ").count(), 4, "{text}");
1978        assert_eq!(text.matches(" = xor ").count(), 4, "{text}");
1979        assert!(!text.contains("call"), "{text}");
1980
1981        // The value is evaluated once however many questions are asked of it, which is the whole
1982        // reason `fpclassify` is a node rather than the chain of tests it turns into.
1983        let text = body(concat!(
1984            "double g(void);\n",
1985            "int f(void) { return __builtin_fpclassify(0, 1, 2, 3, 4, g()); }\n",
1986        ));
1987        assert_eq!(text.matches("call @g()").count(), 1, "{text}");
1988    }
1989
1990    /// Each of the three answers a constant where its operand is one.
1991    ///
1992    /// glibc's `fpclassify` macro is exactly this builtin, so a program that writes
1993    /// `fpclassify(0.0)` in a static initializer is writing this, and it has to have a value at
1994    /// translation time or the program is refused rather than merely compiled slowly. Every
1995    /// number here is what gcc 16 gives.
1996    #[test]
1997    fn the_last_three_classification_builtins_fold_where_their_operand_is_a_constant() {
1998        let text = ir(concat!(
1999            "int a = __builtin_isnormal(1.0);\n",
2000            "int b = __builtin_isnormal(0.0);\n",
2001            "int c = __builtin_isnormal(1.0 / 0.0);\n",
2002            "int d = __builtin_isinf_sign(-1.0 / 0.0);\n",
2003            "int e = __builtin_isinf_sign(1.0);\n",
2004            "int g = __builtin_fpclassify(0, 1, 2, 3, 4, 0.0);\n",
2005            "int h = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0);\n",
2006            "int i = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0 / 0.0);\n",
2007        ));
2008        assert!(text.contains("global @a : i32 = 1,"), "{text}");
2009        assert!(text.contains("global @b : i32 = 0,"), "{text}");
2010        assert!(text.contains("global @c : i32 = 0,"), "{text}");
2011        assert!(text.contains("global @d : i32 = -1,"), "{text}");
2012        assert!(text.contains("global @e : i32 = 0,"), "{text}");
2013        assert!(text.contains("global @g : i32 = 4,"), "{text}");
2014        assert!(text.contains("global @h : i32 = 2,"), "{text}");
2015        assert!(text.contains("global @i : i32 = 1,"), "{text}");
2016    }
2017
2018    /// `fpclassify` refuses what gcc refuses, in gcc's words.
2019    ///
2020    /// The five answers have to be integer constant expressions, because what the builtin does is
2021    /// pick one of them and a pick between values that are not known here would be a chain of
2022    /// conditionals over expressions the call has already evaluated.
2023    #[test]
2024    fn fpclassify_refuses_an_answer_that_is_not_an_integer_constant() {
2025        let mut opts = options();
2026        opts.emit = EmitKind::Ir;
2027        let source = concat!(
2028            "int a(double x, int n) { return __builtin_fpclassify(0, 1, n, 3, 4, x); }\n",
2029            "int b(double x) { return __builtin_fpclassify(0, 1, 2, 3, x); }\n",
2030            "int c(int x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n",
2031        );
2032        let messages = run(&opts, source).messages;
2033        assert_eq!(
2034            messages,
2035            [
2036                "/main.c:1:60: error: non-const integer argument 3 in call to function \
2037                 '__builtin_fpclassify' [E0687]",
2038                "/main.c:2:26: error: too few arguments to function '__builtin_fpclassify' \
2039                 [E0511]",
2040                "/main.c:3:23: error: non-floating-point argument in call to function \
2041                 '__builtin_fpclassify' [E0685]",
2042            ]
2043        );
2044    }
2045
2046    /// A builtin whose answer is a constant is one, and is not a call to the library.
2047    ///
2048    /// This is the reason the family is answered in the front end at all. `double x =
2049    /// __builtin_inf();` at file scope initializes an object with static storage duration, so
2050    /// there is no point in the program at which a call could be made, and a compiler that
2051    /// lowered it to one would reject a program gcc accepts. Every number here is the encoding
2052    /// gcc 16 gives on x86-64.
2053    #[test]
2054    fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
2055        let text = ir(concat!(
2056            "double a = __builtin_inf();\n",
2057            "float b = __builtin_huge_valf();\n",
2058            "long double c = __builtin_infl();\n",
2059            "double d = __builtin_huge_val();\n",
2060        ));
2061        assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
2062        assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
2063        assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
2064        assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
2065        assert!(!text.contains("call"), "{text}");
2066    }
2067
2068    /// A nan is written with the payload the program asked for.
2069    ///
2070    /// The string is read the way `strtoull` reads a number, which is what the library function
2071    /// of the same name does with it, and a string that is not one at all leaves the call for the
2072    /// library to answer at run time. A quiet nan has the high fraction bit set and a signalling
2073    /// one does not, except that a signalling nan with nothing in it would be an infinity, so it
2074    /// gets the next bit down instead. Every encoding here was measured against gcc 16, the two
2075    /// `long double` ones on a machine with the x87 format.
2076    #[test]
2077    fn a_nan_is_written_with_the_payload_the_program_asked_for() {
2078        let text = ir(concat!(
2079            "double a = __builtin_nan(\"\");\n",
2080            "double b = __builtin_nan(\"0x1\");\n",
2081            // Octal, since there is a leading zero, so this is eight and not ten.
2082            "double c = __builtin_nan(\"010\");\n",
2083            "double d = __builtin_nans(\"\");\n",
2084            "double e = __builtin_nans(\"0x1\");\n",
2085            "float f = __builtin_nanf(\"0x1\");\n",
2086            "float g = __builtin_nansf(\"\");\n",
2087            "long double h = __builtin_nansl(\"\");\n",
2088        ));
2089        assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
2090        assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
2091        assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
2092        assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
2093        assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
2094        assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
2095        assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
2096        assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
2097
2098        // A payload that is not a number, and one that is not known until run time, are both
2099        // left to the library, which is the same thing gcc emits for either of them.
2100        let text = ir(concat!(
2101            "double f(const char *p) { return __builtin_nan(p); }\n",
2102            "double g(void) { return __builtin_nans(\"1x\"); }\n",
2103        ));
2104        assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
2105        assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
2106    }
2107
2108    /// The length and the order of a string literal are known here.
2109    ///
2110    /// A program that asks for either of them is asking about something the translation already
2111    /// has in front of it, and folding is not only an optimization: `execute/921007-1.c` in the
2112    /// torture suite calls `__builtin_strcmp` in a file that defines its own `strcmp` with a
2113    /// different signature, so leaving the call behind is a name collision that gcc does not
2114    /// have. The comparison is over `unsigned char`, which is why the second one is negative.
2115    #[test]
2116    fn the_length_and_the_order_of_a_string_literal_are_known_here() {
2117        let text = ir(concat!(
2118            "unsigned long a = __builtin_strlen(\"hello\");\n",
2119            "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
2120            "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
2121            "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
2122            "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
2123        ));
2124        assert!(text.contains("global @a : i64 = 5,"), "{text}");
2125        assert!(text.contains("global @b : i64 = 1,"), "{text}");
2126        assert!(text.contains("global @c : i32 = 1,"), "{text}");
2127        assert!(text.contains("global @d : i32 = 0,"), "{text}");
2128        assert!(text.contains("global @e : i32 = 1,"), "{text}");
2129        assert!(!text.contains("call"), "{text}");
2130
2131        // An argument that is not a literal is the library's to answer, as it has to be.
2132        let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
2133        assert!(text.contains("call @strlen("), "{text}");
2134    }
2135
2136    /// A sign builtin is a mask over the bits, and is not a call.
2137    ///
2138    /// `fabs` and `copysign` are in the math library rather than the C one, so a program that
2139    /// only ever wrote the prefixed spelling never asked for `-lm` and a call left behind here
2140    /// would not link. Neither needs anything the library has: one clears the sign bit and the
2141    /// other takes it from the second operand, and every other bit goes through untouched.
2142    #[test]
2143    fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
2144        let text = body("double f(double x) { return __builtin_fabs(x); }\n");
2145        assert!(text.contains("bitcast.i64 %0"), "{text}");
2146        assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
2147        assert!(text.contains("and %1, %2"), "{text}");
2148        assert!(text.contains("bitcast.f64 %3"), "{text}");
2149        assert!(!text.contains("call"), "{text}");
2150
2151        let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
2152        assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
2153        assert!(text.contains("%8 = or %4, %7"), "{text}");
2154        assert!(!text.contains("call"), "{text}");
2155
2156        // The x87 format, whose value is eighty bits sitting in an object of sixteen. The mask is
2157        // as wide as the value and not as wide as the object, so the padding is not part of it.
2158        let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
2159        assert!(text.contains("bitcast.i80 %0"), "{text}");
2160        assert!(text.contains("bitcast.f80"), "{text}");
2161
2162        // The width a name does not spell out is `double`, so a `float` argument widens first and
2163        // the answer is a `double`, which is what gcc's declaration of it says.
2164        let text = body("double f(float x) { return __builtin_fabs(x); }\n");
2165        assert!(text.contains("fpext.f64 %0"), "{text}");
2166        assert!(text.contains("bitcast.i64 %1"), "{text}");
2167    }
2168
2169    /// The sign builtins answer a zero and a nan the way the bits say.
2170    ///
2171    /// This is why they are described over the bits rather than written with comparisons and
2172    /// negation. A negative zero compares equal to a positive one and has a sign bit to clear,
2173    /// and a nan compares equal to nothing at all and keeps its payload through both operations.
2174    /// `execute/ieee/copysign1.c` in the torture suite is the test that notices, because it
2175    /// compares its answers with `memcmp`. Every number here is what gcc 16 gives, the two in the
2176    /// x87 format measured on a machine that has it.
2177    #[test]
2178    fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
2179        let text = ir(concat!(
2180            "double a = __builtin_fabs(-3.5);\n",
2181            "double b = __builtin_copysign(1.0, -0.0);\n",
2182            "double c = __builtin_copysign(0.0, -2.0);\n",
2183            // The payload survives both, and only the sign bit moves.
2184            "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
2185            "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
2186            "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
2187            "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
2188            "long double i = __builtin_fabsl(-__builtin_infl());\n",
2189        ));
2190        assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
2191        assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
2192        assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
2193        assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
2194        assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
2195        assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
2196        assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
2197        assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
2198    }
2199
2200    /// A `constexpr` object is a named constant, which is the whole reason the keyword exists.
2201    ///
2202    /// C23 6.6p8 puts two of them on the list an integer constant expression is built from: one
2203    /// of an arithmetic type, and a member of one of a structure or union type. A subscript of
2204    /// one is not on the list and is a variably modified type in gcc 16 as well, and every
2205    /// number here is what gcc 16 gives on x86-64.
2206    #[test]
2207    fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
2208        let text = ir(concat!(
2209            "constexpr int side = 4;\n",
2210            "constexpr int wider = side + 1;\n",
2211            "constexpr double half = 1.5;\n",
2212            "struct point { int x; int y; };\n",
2213            "constexpr struct point origin = { 5, 6 };\n",
2214            "int square[side * side];\n",
2215            "int rectangle[wider];\n",
2216            "int rounded[(int)half * 2];\n",
2217            "int across[origin.y];\n",
2218            "enum named { four = side };\n",
2219            "int e = four;\n",
2220        ));
2221        assert!(text.contains("global @square : bytes 64 ="), "{text}");
2222        assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
2223        assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
2224        assert!(text.contains("global @across : bytes 24 ="), "{text}");
2225        assert!(text.contains("global @e : i32 = 4,"), "{text}");
2226
2227        // A `const` object is not one of them, which is what makes `int a[n];` a variable
2228        // length array in C and is the distinction the keyword was added to draw.
2229        let mut opts = options();
2230        opts.emit = EmitKind::Ir;
2231        let konst = "const int n = 1;\nint a[n];\n";
2232        let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
2233        assert_eq!(run(&opts, konst).messages, [message]);
2234
2235        // Nor is a subscript of one, which gcc 16 refuses in the same words.
2236        let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
2237        assert_eq!(run(&opts, subscript).messages, [message]);
2238
2239        // And `constexpr` implies `const`, so the address of one is an address of a `const`.
2240        let address = "constexpr int c = 3;\nint *p = &c;\n";
2241        let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
2242             pointer target type [E0514]";
2243        assert_eq!(run(&opts, address).messages, [warning]);
2244    }
2245
2246    /// A definition that names its parameters and then declares them under the list.
2247    ///
2248    /// The declarations say what the types are, 6.9.1p6, and what the function takes is those
2249    /// types with the default argument promotions over them, which is what a caller of an
2250    /// unprototyped function hands over. A prototype already in scope overrules the promoted
2251    /// types, since a header saying `int narrow(char);` over a definition written this way is
2252    /// the pairing all the code written this way relies on and 6.7.6.3p15 is read that way by
2253    /// every compiler.
2254    #[test]
2255    fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
2256        // C17, since the default dialect is the one that warns about the form and this is
2257        // about what it means rather than about the warning.
2258        let mut opts = options();
2259        opts.std = Std::C17;
2260        let source = concat!(
2261            "int add(a, b)\n",
2262            "int a;\n",
2263            "int b;\n",
2264            "{ return a + b; }\n",
2265            "int promoted(c)\n",
2266            "char c;\n",
2267            "{ return c; }\n",
2268            "int narrow(char);\n",
2269            "int narrow(c)\n",
2270            "char c;\n",
2271            "{ return c; }\n",
2272            "int first(a)\n",
2273            "int a[4];\n",
2274            "{ return a[0]; }\n",
2275        );
2276        let result = run(&opts, source);
2277        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2278        let text = result.text();
2279        assert!(text.contains("add : int(int, int) function external defined"), "{text}");
2280        assert!(text.contains("promoted : int(int) function external defined"), "{text}");
2281        // The body still sees the `char` it was declared as, whatever the caller hands over.
2282        assert!(text.contains("c : char object automatic defined"), "{text}");
2283        assert!(text.contains("narrow : int(char) function external defined"), "{text}");
2284        // An array parameter is a pointer here as much as it is in a prototype.
2285        assert!(text.contains("first : int(int *) function external defined"), "{text}");
2286    }
2287
2288    /// What the two halves of an old-style parameter list can disagree about.
2289    ///
2290    /// Each of these is a sentence gcc 16 has, and every message below is the one it prints,
2291    /// read off it on x86-64 rather than reasoned about. The last two are the dialect: a name
2292    /// with no declaration is an `int` in C89 and a diagnostic from C99 on, and the whole form
2293    /// left the language in C23, where gcc still takes it and warns.
2294    #[test]
2295    fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
2296        let mut opts = options();
2297        opts.std = Std::C17;
2298        for (source, message) in [
2299            ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
2300            (
2301                "int f(a)\nint a;\nint b;\n{ return a; }\n",
2302                "3:5: error: declaration for parameter 'b' but no such parameter",
2303            ),
2304            ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
2305            ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
2306            (
2307                "int f(a)\nstatic int a;\n{ return a; }\n",
2308                "2:12: error: storage class specified for parameter 'a'",
2309            ),
2310            (
2311                "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
2312                "2:7: error: argument 'a' doesn't match prototype",
2313            ),
2314        ] {
2315            let result = run(&opts, source);
2316            assert!(result.failed(), "expected this to fail:\n{source}");
2317            assert!(result.messages[0].contains(message), "{:?}", result.messages);
2318        }
2319
2320        // A name the declarations never mention. C89 gave it an `int` and gcc still takes it
2321        // in that dialect, and every dialect after it made the same line a diagnostic.
2322        let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
2323        let mut older = options();
2324        older.std = Std::C89;
2325        assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
2326        let result = run(&opts, implicit);
2327        assert!(
2328            result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
2329            "{:?}",
2330            result.messages
2331        );
2332
2333        // C23 took the form out of the language and gcc kept accepting it with a warning, and
2334        // a warning is what this is, because the code written this way is not going to be
2335        // rewritten and refusing it would put the compiler out of reach of it.
2336        let mut newer = options();
2337        newer.std = Std::C23;
2338        let plain = "int f(a)\nint a;\n{ return a; }\n";
2339        let result = run(&newer, plain);
2340        assert!(!result.failed(), "{:?}", result.messages);
2341        assert_eq!(
2342            result.messages,
2343            ["/main.c:1:5: warning: old-style function definition [E0412]"]
2344        );
2345        assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
2346    }
2347
2348    /// A type nothing is ever an object of is a type `sizeof` still has to answer about, which
2349    /// is what `991014-1.c` in the gcc.c-torture execution suite asks.
2350    ///
2351    /// The limit is `PTRDIFF_MAX` and it is the same one for an array and for a record, so a
2352    /// record of every byte an object may have is laid out and one byte more is refused. All
2353    /// four numbers are what gcc 16 gives on x86-64.
2354    #[test]
2355    fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
2356        let text = ir(concat!(
2357            "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
2358            "struct brim { char buf[9223372036854775807L]; };\n",
2359            "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
2360            "unsigned long h = sizeof(struct huge_struct);\n",
2361            "unsigned long b = sizeof(struct brim);\n",
2362            "unsigned long y = sizeof(struct bitty);\n",
2363        ));
2364        assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
2365        assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
2366        assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
2367
2368        let mut opts = options();
2369        opts.emit = EmitKind::Ir;
2370        let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
2371        let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
2372        assert_eq!(run(&opts, over).messages, [message]);
2373        let array = "struct wide { short buf[1L << 62]; };\n";
2374        let message = "/main.c:1:25: error: size of array 'buf' exceeds \
2375             maximum object size '9223372036854775807' [E0537]";
2376        assert_eq!(run(&opts, array).messages[0], message);
2377    }
2378
2379    /// A byte in the source that is not part of a character, which only a literal may hold.
2380    ///
2381    /// The source cannot be a `&str` here, which is the whole point: a file is bytes and only
2382    /// mostly text.
2383    fn compile_bytes(source: &[u8]) -> Compiled {
2384        let mut opts = options();
2385        opts.emit = EmitKind::Ir;
2386        let mut fs = MemoryFileSystem::new();
2387        fs.insert("/main.c", source.to_vec());
2388        compile(&opts, "/main.c", &fs)
2389    }
2390
2391    /// A raw byte inside a string literal is that byte, which gcc has always taken and which is
2392    /// the only place in a source file where a byte does not have to be part of a character.
2393    /// Replacing it would give the object three bytes rather than one, since the replacement
2394    /// character is three bytes of UTF-8, so the object would not be the one that was written
2395    /// even where the diagnostic is ignored. Anywhere else the byte is still a mistake, which
2396    /// is where gcc draws the same line.
2397    #[test]
2398    fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
2399        let mut source = b"char s[] = \"a".to_vec();
2400        source.push(0xff);
2401        source.extend_from_slice(b"b\";\nchar c = '");
2402        source.push(0xff);
2403        source.extend_from_slice(b"';\n");
2404        let result = compile_bytes(&source);
2405        assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
2406        assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
2407        // Plain `char` is signed on this target, so the constant is minus one rather than 255.
2408        assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
2409
2410        let mut stray = b"int a".to_vec();
2411        stray.push(0xff);
2412        stray.extend_from_slice(b" = 1;\n");
2413        let result = compile_bytes(&stray);
2414        assert!(
2415            result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
2416            "{:?}",
2417            result.messages
2418        );
2419    }
2420
2421    #[test]
2422    fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
2423        let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
2424        assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
2425        let expected = "\
2426func @add(i32, i32) -> i32, linkage(external) {
2427block0(%0: i32, %1: i32):
2428    %2 = add.nsw %0, %1
2429    return %2
2430}
2431";
2432        assert!(text.contains(expected), "{text}");
2433    }
2434
2435    #[test]
2436    fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
2437        let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
2438        assert!(!text.contains("alloca"), "{text}");
2439        assert!(!text.contains("load"), "{text}");
2440        assert!(!text.contains("store"), "{text}");
2441    }
2442
2443    #[test]
2444    fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
2445        let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
2446        let expected = "\
2447block0:
2448    %0 = alloca, size 4, align 4
2449    %1 = iconst.i32 1
2450    store %1 -> %0, align 4
2451    %2 = call @g(%0) : (ptr) -> i32
2452    return %2
2453";
2454        assert_eq!(text, expected);
2455    }
2456
2457    #[test]
2458    fn a_loop_carries_what_it_changes_as_block_parameters() {
2459        // The whole point of building SSA during the walk rather than after it: `i` and
2460        // `total` are values that arrive on an edge, and neither has ever been in memory.
2461        let text = body(
2462            "int f(int n) {\n  int total = 0;\n  for (int i = 0; i < n; i++) total += i;\n  \
2463             return total;\n}\n",
2464        );
2465        assert!(!text.contains("alloca"), "{text}");
2466        assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
2467        assert!(text.contains("jump block1("), "{text}");
2468    }
2469
2470    #[test]
2471    fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
2472        let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
2473        assert!(text.contains("icmp slt %0, %1"), "{text}");
2474        assert!(!text.contains("zext"), "{text}");
2475    }
2476
2477    #[test]
2478    fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
2479        let text = body("int f(int a, int b) { return a && b; }\n");
2480        let expected = "\
2481block0(%0: i32, %1: i32):
2482    %2 = iconst.i32 0
2483    %3 = icmp ne %0, %2
2484    %4 = iconst.i1 0
2485    br_if %3, block1, block2(%4)
2486
2487block1:
2488    %5 = iconst.i32 0
2489    %6 = icmp ne %1, %5
2490    jump block2(%6)
2491
2492block2(%7: i1):
2493    %8 = zext.i32 %7
2494    return %8
2495";
2496        assert_eq!(text, expected);
2497    }
2498
2499    #[test]
2500    fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
2501        let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
2502        // Three blocks, the test and the two arms. The join the `return 3` would need is
2503        // never created, because a block nothing branches to is not a block.
2504        assert!(!text.contains("block3"), "{text}");
2505        assert!(!text.contains("iconst.i32 3"), "{text}");
2506    }
2507
2508    #[test]
2509    fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
2510        assert!(body("int main(void) { }\n").contains("iconst.i32 0\n    return"));
2511        assert_eq!(body("void f(void) { }\n"), "block0:\n    return\n");
2512        assert!(body("int f(void) { }\n").contains("unreachable"));
2513    }
2514
2515    #[test]
2516    fn a_structure_is_copied_rather_than_held_in_a_value() {
2517        let text = body(
2518            "struct point { int x, y; };\n\
2519             int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
2520        );
2521        assert!(text.contains("memcpy"), "{text}");
2522    }
2523
2524    #[test]
2525    fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
2526        let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
2527        assert!(text.contains("memset"), "{text}");
2528    }
2529
2530    #[test]
2531    fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
2532        let text = body(
2533            "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
2534             default: r = 4; } return r; }\n",
2535        );
2536        let expected = "\
2537block0(%0: i32):
2538    %1 = iconst.i32 0
2539    switch %0, block1, [1 => block2, 2 => block3(%1)]
2540
2541block1:
2542    %2 = iconst.i32 4
2543    jump block4(%2)
2544
2545block2:
2546    %3 = iconst.i32 1
2547    jump block3(%3)
2548
2549block3(%4: i32):
2550    %5 = iconst.i32 2
2551    %6 = add.nsw %4, %5
2552    jump block4(%6)
2553
2554block4(%7: i32):
2555    return %7
2556";
2557        assert_eq!(text, expected);
2558    }
2559
2560    #[test]
2561    fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
2562        // GNU's `case 1 ... 9`. Nine table entries would be nine here and four billion for the
2563        // range a program is allowed to write, so it is a subtraction and one unsigned compare.
2564        let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
2565        assert!(text.contains("%2 = sub %0, %1"), "{text}");
2566        assert!(text.contains("icmp ule"), "{text}");
2567        assert!(!text.contains("switch"), "{text}");
2568    }
2569
2570    #[test]
2571    fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
2572        let text = body(
2573            "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
2574             case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
2575        );
2576        // The `continue` goes to the step and the `break` goes to the `t++` after the switch,
2577        // which is also where the default falls out to.
2578        assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
2579        assert!(text.contains("block5:\n    jump block7("), "{text}");
2580        assert!(text.contains("block6:\n    jump block8("), "{text}");
2581    }
2582
2583    #[test]
2584    fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
2585        assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n    return\n");
2586    }
2587
2588    #[test]
2589    fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
2590        // A branch into the middle of a loop that nothing else reaches, the Duff's device shape.
2591        // The `while` is not reached in order, so the walk starts a block nothing branches to and
2592        // builds it from there. What comes out is the loop with an edge straight into its body,
2593        // and the header that nothing arrives at is pruned.
2594        let text = body(
2595            "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
2596             return n; }\n",
2597        );
2598        // `case 2` lands on the body, `case 1` and the default land on the return, and the test
2599        // at the bottom of the loop comes back round to the body.
2600        assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
2601        assert!(text.contains("block3(%3: i32):\n    %4 = iconst.i32 1"), "{text}");
2602        assert!(text.contains("block5:\n    jump block3("), "{text}");
2603    }
2604
2605    #[test]
2606    fn a_goto_into_a_loop_body_enters_it_without_the_test() {
2607        // The same thing through a `goto`. The first pass through the body runs whatever the
2608        // label is on, and only then does the loop reach its own test.
2609        let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
2610        assert!(text.starts_with("block0(%0: i32, %1: i32):\n    jump block1(%1)"), "{text}");
2611        assert!(text.contains("block1(%2: i32):\n    %3 = iconst.i32 1"), "{text}");
2612        assert!(text.contains("br_if %7, block3, block4"), "{text}");
2613    }
2614
2615    #[test]
2616    fn a_goto_is_a_jump_to_the_block_the_label_starts() {
2617        let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
2618        // Both edges into `out` carry what `r` holds on the way, and neither is a stack slot.
2619        assert!(!text.contains("alloca"), "{text}");
2620        assert!(text.contains("block3(%4: i32):\n    return %4"), "{text}");
2621        assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
2622    }
2623
2624    #[test]
2625    fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
2626        let text =
2627            body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
2628        assert!(!text.contains("alloca"), "{text}");
2629        assert!(text.contains("block1(%2: i32):"), "{text}");
2630        assert!(text.contains("jump block1(%5)"), "{text}");
2631    }
2632
2633    #[test]
2634    fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
2635        // A block nothing branches to is not a legal function, and which labels are dead is not
2636        // known until the last statement has been walked, since the `goto` is allowed to be it.
2637        assert_eq!(
2638            body("int f(int x) { return x; spare: return 0; }\n"),
2639            "block0(%0: i32):\n    return %0\n"
2640        );
2641    }
2642
2643    #[test]
2644    fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
2645        let text = body(
2646            "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
2647        );
2648        // One byte holds both fields, and the signed one needs no mask: shifting it down
2649        // arithmetically is what says its top bit is a sign.
2650        assert_eq!(
2651            text,
2652            "\
2653block0(%0: ptr):
2654    %1 = load.i8 %0, align 1
2655    %2 = iconst.i8 3
2656    %3 = ashr %1, %2
2657    %4 = sext.i32 %3
2658    return %4
2659"
2660        );
2661    }
2662
2663    #[test]
2664    fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
2665        // C11 says an ordinary member beside a bit-field is a memory location of its own, so
2666        // the four byte store this would take is a data race in a program that has none. The
2667        // three bytes of `a` go in as two and one, and `c` is not touched.
2668        let text =
2669            body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
2670        assert_eq!(
2671            text,
2672            "\
2673block0(%0: ptr, %1: i32):
2674    %2 = iconst.i32 16777215
2675    %3 = and %1, %2
2676    %4 = trunc.i16 %3
2677    store %4 -> %0, align 2
2678    %5 = iconst.i32 16
2679    %6 = lshr %3, %5
2680    %7 = trunc.i8 %6
2681    %8 = iconst.i64 2
2682    %9 = ptr_add %0, %8
2683    store %7 -> %9, align 1
2684    return
2685"
2686        );
2687    }
2688
2689    #[test]
2690    fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
2691        let text =
2692            body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
2693        // 33 does not fit in five bits, and 1 is both what goes in the field and what the
2694        // assignment is worth.
2695        assert!(text.contains("%3 = iconst.i8 31\n    %4 = and %2, %3"), "{text}");
2696        assert!(text.ends_with("%9 = zext.i32 %4\n    return %9\n"), "{text}");
2697    }
2698
2699    #[test]
2700    fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
2701        // The value of an assignment to a bit-field takes a shift to build, and a statement
2702        // has no use for it. Nothing here reads back what was stored.
2703        let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
2704        assert_eq!(text.matches("ashr").count(), 0, "{text}");
2705        assert!(text.ends_with("store %8 -> %0, align 1\n    return\n"), "{text}");
2706    }
2707
2708    #[test]
2709    fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
2710        // A bit-field writes part of a byte and leaves the rest of it alone, so the object has
2711        // to be zero before it goes in or what the initializer did not name is whatever the
2712        // stack held.
2713        let text = body(
2714            "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
2715        );
2716        assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
2717    }
2718
2719    #[test]
2720    fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
2721        // Two fields in one byte are not two entries in the image, because an image is written
2722        // in bytes: they are the byte they are both in.
2723        let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
2724        assert!(
2725            text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
2726            "{text}"
2727        );
2728    }
2729
2730    #[test]
2731    fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
2732        // `sizeof` answers without the array and the definition has to hold what was written, so
2733        // the object is the size of its image. gcc 16 gives these four, three and two bytes and
2734        // so does this. The image used to be written at the size the type had, which left the
2735        // verifier looking at twenty bytes going into four.
2736        let text = ir(concat!(
2737            "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
2738            "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
2739            "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
2740            "char s[2] = \"hi\";\n",
2741        ));
2742        assert!(
2743            text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
2744            "{text}"
2745        );
2746        assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
2747        assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
2748        // The array with a length of its own still cuts the literal down to it, which is the
2749        // one case in C where a string initializer drops its terminator.
2750        assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
2751    }
2752
2753    #[test]
2754    fn a_definition_takes_a_parameter_it_left_unnamed() {
2755        // The entry block's parameters are the definition's, and one the front end dropped for
2756        // having no name left the two lists different lengths, which the walk read as an
2757        // old-style definition and refused. gcc has taken these for far longer than C23 has.
2758        let text = ir("int f(int a, int) { return a; }\n");
2759        assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
2760        assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
2761
2762        // The unnamed one first, so that the named one is the second parameter of the entry
2763        // block and not the first: the list says the order and not only how many there are.
2764        let text = ir("int g(int, int n) { return n; }\n");
2765        assert!(text.contains("block0(%0: i32, %1: i32):\n    return %1\n"), "{text}");
2766    }
2767
2768    #[test]
2769    fn an_assignment_of_a_structure_is_the_object_it_wrote() {
2770        // `d = e = c` used to be refused, because the middle assignment is a value of structure
2771        // type and the walk had nowhere to read one from. What an assignment is worth is the
2772        // value it stored, so the object it stored into is the answer and the chain is three
2773        // copies out of the one source with no temporary in it.
2774        let text = body(concat!(
2775            "struct s { int f; int g; };\n",
2776            "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
2777            "{ *d = *e = a[0] = *c; }\n",
2778        ));
2779        assert_eq!(text.matches("memcpy").count(), 3, "{text}");
2780        assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
2781        assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
2782        assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
2783    }
2784
2785    #[test]
2786    fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
2787        // The excess used to be laid into the object anyway, so the row after was written over
2788        // and the image refused the entry that came to it. C 6.7.10p14 says the terminator goes
2789        // in only if there is room for it, and gcc discards the rest of a literal that is longer
2790        // still, which is what the first of these is and why it warns.
2791        let mut opts = options();
2792        opts.emit = EmitKind::Ir;
2793        let result = run(
2794            &opts,
2795            concat!(
2796                "const char a[2][3] = { \"1234\", \"xyz\" };\n",
2797                "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
2798                "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
2799                "const union u c = { { \"1234\", \"567\" } };\n",
2800            ),
2801        );
2802        let text = result.text();
2803        assert_eq!(
2804            result.messages,
2805            ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
2806              (5 chars into 3 available) [E0637]"]
2807        );
2808        assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
2809        assert!(
2810            text.contains(
2811                "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
2812                 bytes \"9\\00\", zero 3 }"
2813            ),
2814            "{text}"
2815        );
2816        // The eight bytes are four, three and a terminator, and then the byte the shorter
2817        // literal left for the string in the other member of the union to end at.
2818        assert!(
2819            text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
2820            "{text}"
2821        );
2822    }
2823
2824    #[test]
2825    fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
2826        // gcc accepts one and does nothing with it, which sema already had. Lowering asked for
2827        // the object under it and had no arm for a cast, so `(struct s)x` in an initializer was
2828        // refused with E0519. It is one copy out of the object named, not two.
2829        let text = body(concat!(
2830            "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
2831            "void g(struct v *);\n",
2832            "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
2833        ));
2834        assert_eq!(text.matches("memcpy").count(), 1, "{text}");
2835    }
2836
2837    #[test]
2838    fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
2839        // C 6.7.11p4 says a compound literal at file scope has static storage duration, which
2840        // makes it a constant element, and tcc and c-testsuite both write one. Sema used to call
2841        // it a non constant because reading it is a node of its own and the read was what it
2842        // looked at, and lowering had no way to put an object where it wanted a number.
2843        let text = ir(concat!(
2844            "struct s { int x; };\n",
2845            "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
2846            "int n = (int){ 7 };\n",
2847            "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
2848        ));
2849        assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
2850        assert!(text.contains("global @n : i32 = 7,"), "{text}");
2851        // The second literal names nothing, so what it puts in is the zeros of its own size and
2852        // not the tail of the object it went in, which would have been the same bytes by luck.
2853        assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
2854    }
2855
2856    #[test]
2857    fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
2858        // Nothing declares a compound literal, so the reference is the only thing that can ask
2859        // for it to be emitted. The image named `.Lanon.0` and the module defined no such
2860        // symbol, which the link would have been the first to find out.
2861        let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
2862        assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
2863        assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
2864    }
2865
2866    #[test]
2867    fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
2868        // A zero length array, which gcc allows and real code uses as the tail of a structure.
2869        // The image is there and holds nothing, which is not the global that has no image at
2870        // all, and the IR reader used to stop on the empty one.
2871        let text = ir("unsigned char foo[1][0];\n");
2872        assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
2873    }
2874
2875    #[test]
2876    fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
2877        // `NULL` in a static initializer, which every program has. The IR type is `ptr` and a
2878        // `ptr` has no width of its own, so the width the bits are cut to is the target's.
2879        let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
2880        assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
2881        assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
2882    }
2883
2884    #[test]
2885    fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
2886        // Which the verifier used to refuse, having read a declaration as a definition with
2887        // nothing in it. `extern const` is how a program names something in the library's read
2888        // only data, and glibc and Darwin both have one in a header a real program includes.
2889        let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
2890        assert!(
2891            text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
2892            "{text}"
2893        );
2894    }
2895
2896    #[test]
2897    fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
2898        // A structure is not a value in the IR, so the two arms cannot be joined as one. The
2899        // addresses can, and the answer is the address of whichever arm was taken rather than
2900        // a copy of it into a third place: both arms outlive the expression, so a copy would
2901        // be one nothing could observe. SQLite's parser writes one of these.
2902        let text = body(
2903            "\
2904struct s { int a, b; };
2905struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
2906",
2907        );
2908        // The join takes an address, each arm hands it the one it has, and nothing is copied.
2909        assert!(text.contains("block3(%7: ptr)"), "{text}");
2910        assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
2911        assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
2912    }
2913
2914    #[test]
2915    fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
2916        // `struct pair` is two eightbytes on SysV, one of them integer, so the signature says
2917        // one `i64` in each direction and the body takes the object apart and puts it back
2918        // together around the call.
2919        let text = ir("\
2920struct pair { int a, b; };
2921struct pair make(int a, int b);
2922struct pair twice(struct pair p) { return make(p.a, p.b); }
2923");
2924        assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
2925        assert!(text.contains("func @twice(i64) -> i64"), "{text}");
2926    }
2927
2928    #[test]
2929    fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
2930        // Over two eightbytes the caller passes the bytes in the argument area, which is
2931        // `byval`, and passes somewhere to write the return value, which is `sret`. Neither is
2932        // a parameter the program wrote and both are parameters the function has.
2933        let text = ir("\
2934struct big { double v[8]; };
2935struct big grow(struct big b);
2936struct big twice(struct big b) { return grow(grow(b)); }
2937");
2938        assert!(
2939            text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
2940            "{text}"
2941        );
2942        assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
2943        // The inner call writes into a slot and the outer one reads the same slot, so the
2944        // object between the two calls is never copied anywhere.
2945        assert_eq!(text.matches("call @grow").count(), 2, "{text}");
2946    }
2947
2948    #[test]
2949    fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
2950        // The bytes travel in the argument area the same way they would for a parameter, and
2951        // `printf` has no parameter there to say it on, so the call says it instead. The one
2952        // that fits in registers says nothing, because travelling as the registers it fits in
2953        // is what an argument does when nothing says otherwise.
2954        let text = ir("\
2955struct big { double v[8]; };
2956struct pair { int a, b; };
2957int p(const char *, ...);
2958int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
2959");
2960        assert!(
2961            text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
2962            "{text}"
2963        );
2964    }
2965
2966    #[test]
2967    fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
2968        // `make(1, 2).b` has no object to read a member of until one is made, and what makes it
2969        // is a slot the returned registers are written to.
2970        let body = body(
2971            "\
2972struct pair { int a, b; };
2973struct pair make(int a, int b);
2974int second(void) { return make(1, 2).b; }
2975",
2976        );
2977        assert!(body.starts_with("block0:\n    %0 = alloca, size 8, align 4\n"), "{body}");
2978        assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
2979    }
2980
2981    #[test]
2982    fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
2983        // The same declaration, classified by a different ABI: three `float` members are an
2984        // eightbyte of two of them and a half eightbyte of the third on SysV, and three vector
2985        // registers on AAPCS64.
2986        let source = "\
2987struct hfa { float x, y, z; };
2988int take(struct hfa h);
2989int give(struct hfa h) { return take(h); }
2990";
2991        assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
2992        let mut opts = options();
2993        opts.emit = EmitKind::Ir;
2994        opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
2995        let result = run(&opts, source);
2996        assert_eq!(result.messages, Vec::<String>::new());
2997        assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
2998    }
2999
3000    #[test]
3001    fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
3002        // The size is a multiplication rather than a number, the slot is taken from the stack
3003        // where the declaration is, and the scope it was declared in gives it back.
3004        let source = "\
3005int use(int *);
3006void f(int n) {
3007  {
3008    int a[n];
3009    use(a);
3010  }
3011  use(0);
3012}
3013";
3014        let body = body(source);
3015        assert!(body.contains("mul.nsw"), "{body}");
3016        assert!(body.contains("stacksave"), "{body}");
3017        assert!(body.contains("alloca %"), "{body}");
3018        assert!(body.contains("stackrestore"), "{body}");
3019    }
3020
3021    #[test]
3022    fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
3023        // The label is outside the block the array is in, so arriving there means the array is
3024        // gone, and the restore that says so goes in front of the branch. The `goto` is written
3025        // before the walk knows where the label is, which is why the restore is put there at
3026        // the end rather than built where the branch was.
3027        let source = "\
3028int use(int *);
3029int f(int n) {
3030  {
3031    int a[n];
3032    if (use(a)) goto out;
3033    use(0);
3034  }
3035out:
3036  return 0;
3037}
3038";
3039        let body = body(source);
3040        // Two ways out of the block and a restore on each: the jump and the end of the block.
3041        assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
3042        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
3043        assert!(after.starts_with(" %4\n    jump block"), "{body}");
3044    }
3045
3046    #[test]
3047    fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
3048        // The label is after the declaration and in the same block, so control that arrives
3049        // there arrives somewhere the array exists. Giving it back would be giving back an
3050        // object the next statement reads.
3051        let source = "\
3052int use(int *);
3053int f(int n) {
3054  int a[n];
3055again:
3056  if (use(a)) goto again;
3057  return 0;
3058}
3059";
3060        let body = body(source);
3061        assert!(body.contains("stacksave"), "{body}");
3062        assert!(!body.contains("stackrestore"), "{body}");
3063    }
3064
3065    #[test]
3066    fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
3067        // A loop written out of a `goto`, with the array made inside it. The label is in the
3068        // same block as the declaration and before it, which is a place where the array does
3069        // not exist yet, so the jump there leaves its scope and has to give the stack back. A
3070        // compiler that skips this restore grows the stack once per iteration.
3071        let source = "\
3072int use(int *);
3073int f(int n) {
3074again:
3075  {
3076    int a[n];
3077    if (use(a)) goto again;
3078  }
3079  return 0;
3080}
3081";
3082        let body = body(source);
3083        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
3084        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
3085        assert!(after.starts_with(" %4\n    jump block1\n"), "{body}");
3086    }
3087
3088    #[test]
3089    fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
3090        // The scope opened for `for (int a[n];;)` used to stay open, and a scope left open is
3091        // not one mark nobody reads. The marks are a stack, so the next close took this one
3092        // instead of its own, and the body of the loop gave back nothing while the block after
3093        // the loop restored a pointer saved inside it. The verifier refused that, which is how
3094        // it was found.
3095        let source = "\
3096int f(void);
3097void t(void) {
3098  int count = 10;
3099  for (; count--;) {
3100    int b[f()];
3101    int i;
3102    for (i = 0; i < f(); i++) {
3103      b[i] = count;
3104    }
3105  }
3106}
3107";
3108        let body = body(source);
3109        // One save, in the body, and one restore for it, also in the body: the block the
3110        // restore is in is the one the inner loop leaves through, and it goes back round the
3111        // outer loop rather than out of it.
3112        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
3113        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
3114        let (next, _) = after.split_once("\n\n").expect("a block after the restore");
3115        assert!(next.contains("jump block1("), "{body}");
3116    }
3117
3118    #[test]
3119    fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
3120        // What C says about the length being evaluated once: `sizeof a` after `n` changed is
3121        // still as long as the array is, which is what `n` was when the array came into being.
3122        let source = "\
3123unsigned long f(int n) {
3124  int a[n];
3125  n = 0;
3126  return sizeof a;
3127}
3128";
3129        let body = body(source);
3130        // One read of the parameter, at the declaration, and the answer is built out of it.
3131        assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
3132    }
3133
3134    #[test]
3135    fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
3136        // GNU's statement expression: the statements happen where they are written and the last
3137        // one is the value, so the temporary in it never becomes a slot and never is copied.
3138        let source = "\
3139int use(int);
3140int f(int x) {
3141  return ({
3142    int t = use(x);
3143    t * t;
3144  });
3145}
3146";
3147        let expected = "\
3148block0(%0: i32):
3149    %1 = call @use(%0) : (i32) -> i32
3150    %2 = mul.nsw %1, %1
3151    return %2
3152";
3153        assert_eq!(body(source), expected);
3154    }
3155
3156    #[test]
3157    fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
3158        // A macro that always jumps, which is what this shape is in real code. The value is
3159        // never taken, and the block the rest of the expression would have been built in is
3160        // one nothing branches to, so it goes with the other unreachable blocks.
3161        let source = "int f(int x) { return ({ return x; 0; }); }\n";
3162        assert_eq!(body(source), "block0(%0: i32):\n    return %0\n");
3163    }
3164
3165    #[test]
3166    fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
3167        // What it becomes is the target's answer, and this is not where the target's answers
3168        // are, so the walk writes down which list and which type and leaves it at that. Two of
3169        // them are two instructions, since each moves the list on.
3170        let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
3171        let expected = "\
3172block0(%0: ptr):
3173    %1 = va_arg.f64 %0
3174    %2 = va_arg.f64 %0
3175    %3 = fadd %1, %2
3176    return %3
3177";
3178        assert_eq!(body(source), expected);
3179    }
3180
3181    #[test]
3182    fn one_that_reads_a_structure_answers_where_the_object_is() {
3183        // An aggregate is not a value, so there is nothing for the result of `va_arg` to be and
3184        // the object form is a second instruction. What it answers is an address, so it is a
3185        // place already and the walk copies nothing out of it: the copy here is the one the
3186        // initializer asks for, into the variable being declared. The size and the alignment
3187        // travel with it because they are what steps the list on and what a target that has to
3188        // put registers somewhere needs to know. So does the classification, which says the two
3189        // halves of this one arrived in general purpose registers: that is an answer about a C
3190        // type, and this is the last place that still has one.
3191        let source = "\
3192struct s { int a; long b; };
3193long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
3194";
3195        let expected = "\
3196block0(%0: ptr):
3197    %1 = alloca, size 16, align 8
3198    %2 = va_object %0, size 16, align 8, in(int 8 at 0, int 8 at 8)
3199    memcpy %1, %2, size 16, align 8
3200    %3 = iconst.i64 8
3201    %4 = ptr_add %1, %3
3202    %5 = load.i64 %4, align 8
3203    return %5
3204";
3205        assert_eq!(body(source), expected);
3206    }
3207
3208    /// Which register file each eightbyte arrived in is the whole of what the classification adds,
3209    /// and an object with no slots at all is one it sent to the caller's argument area, which is
3210    /// what everything over two eightbytes is whatever its members are.
3211    #[test]
3212    fn the_classification_says_which_registers_the_object_arrived_in() {
3213        let source = "\
3214struct s { double a; double b; };
3215double f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a; }
3216";
3217        assert!(
3218            body(source)
3219                .contains("va_object %0, size 16, align 8, in(float f64 at 0, float f64 at 8)"),
3220            "{}",
3221            body(source)
3222        );
3223
3224        let big = "\
3225struct s { long a[4]; };
3226long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a[0]; }
3227";
3228        assert!(body(big).contains("va_object %0, size 32, align 8\n"), "{}", body(big));
3229    }
3230
3231    #[test]
3232    fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
3233        // GNU's computed goto. Which label the address holds is not known here, so all of them
3234        // are listed, and the values arriving at one are passed on every edge the same way they
3235        // are on an ordinary branch.
3236        let source = "\
3237int f(int c) {
3238  void *p = c ? &&one : &&two;
3239  goto *p;
3240one:
3241  return 1;
3242two:
3243  return 2;
3244}
3245";
3246        let expected = "\
3247block0(%0: i32):
3248    %1 = iconst.i32 0
3249    %2 = icmp ne %0, %1
3250    br_if %2, block1, block2
3251
3252block1:
3253    %3 = block_addr block3
3254    jump block4(%3)
3255
3256block2:
3257    %4 = block_addr block5
3258    jump block4(%4)
3259
3260block3:
3261    %5 = iconst.i32 1
3262    return %5
3263
3264block4(%6: ptr):
3265    indirect_br %6, block3, block5
3266
3267block5:
3268    %7 = iconst.i32 2
3269    return %7
3270";
3271        assert_eq!(body(source), expected);
3272    }
3273
3274    #[test]
3275    fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
3276        // The address came from outside the function, and a jump to a label in another function
3277        // is undefined. The expression is still evaluated, since a call in it has to happen.
3278        let source = "void **next(void);
3279void f(void) { goto *next(); }
3280";
3281        let expected = "\
3282block0:
3283    %0 = call @next() : () -> ptr
3284    unreachable
3285";
3286        assert_eq!(body(source), expected);
3287    }
3288
3289    #[test]
3290    fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
3291        // Nothing reads a result, so the only thing that keeps it is that it is volatile, which
3292        // a basic asm implies.
3293        let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
3294        let expected = "\
3295block0:
3296    inline_asm.volatile \"mfence\", \"\", \"memory\"()
3297    return
3298";
3299        assert_eq!(body(source), expected);
3300    }
3301
3302    #[test]
3303    fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
3304        // The outputs first and then the inputs, which is the numbering `%0` and `%1` use. An
3305        // output in a register is a result, and one that is read as well is an argument too.
3306        let source = "\
3307int f(int x, int y) {
3308  int r;
3309  __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
3310  return r + y;
3311}
3312";
3313        let expected = "\
3314block0(%0: i32, %1: i32):
3315    %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
3316    %4 = add.nsw %2, %3
3317    return %4
3318";
3319        assert_eq!(body(source), expected);
3320    }
3321
3322    #[test]
3323    fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
3324        // The assembly is handed a pointer, so the object cannot live in a value, and the scan
3325        // that runs before the walk has to have known that or there would be nothing to point
3326        // at. A structure travels this way whatever else its constraint allows, since there is
3327        // no register that holds one.
3328        let source = "\
3329struct pair { int a, b; };
3330int f(int x) {
3331  int slot = x;
3332  struct pair p = { x, x };
3333  __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
3334  return slot + p.a;
3335}
3336";
3337        let text = body(source);
3338        assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
3339        assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
3340        assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
3341    }
3342
3343    #[test]
3344    fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
3345        // The output is only in scope where the instruction dominates, which is the fall through
3346        // block, so the edge to the label carries the value the object had before the assembly
3347        // ran. That is what document 11 asks for and it is what putting the fall through first
3348        // buys.
3349        let source = "\
3350int f(int x) {
3351  int r = 7;
3352  __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
3353  return r;
3354away:
3355  return r;
3356}
3357";
3358        let expected = "\
3359block0(%0: i32):
3360    %1 = iconst.i32 7
3361    %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
3362
3363block1:
3364    return %2
3365
3366block2:
3367    return %1
3368";
3369        assert_eq!(body(source), expected);
3370    }
3371
3372    #[test]
3373    fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
3374        // The operands are checked here rather than by the assembler, because by the time the
3375        // assembler sees the template the operands have become registers and it has nothing left
3376        // to say about the C that named them.
3377        let mut opts = options();
3378        opts.emit = EmitKind::Ir;
3379        for (source, expected) in [
3380            (
3381                "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
3382                "output operand constraint lacks '='",
3383            ),
3384            (
3385                "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
3386                "lvalue required in 'asm' statement",
3387            ),
3388            (
3389                "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
3390                "read-only variable 'g' used as 'asm' output",
3391            ),
3392            (
3393                "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
3394                "input operand constraint contains '='",
3395            ),
3396            (
3397                "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
3398                "memory input 0 is not directly addressable",
3399            ),
3400            ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
3401            (
3402                "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
3403                "duplicate asm operand name 'a'",
3404            ),
3405            ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
3406        ] {
3407            let result = run(&opts, source);
3408            assert!(result.failed(), "expected this to be reported:\n{source}");
3409            assert!(
3410                result.messages.iter().any(|m| m.contains(expected)),
3411                "{expected}\n{:?}",
3412                result.messages
3413            );
3414        }
3415    }
3416
3417    #[test]
3418    fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
3419        let mut opts = options();
3420        opts.emit = EmitKind::Ir;
3421        for source in [
3422            "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
3423            "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
3424        ] {
3425            let result = run(&opts, source);
3426            assert!(result.failed(), "expected this to be reported:\n{source}");
3427            assert!(
3428                result.messages.iter().any(|m| m.contains("not supported yet")),
3429                "{:?}",
3430                result.messages
3431            );
3432        }
3433    }
3434
3435    /// Compiles `source` to IR, reads that back as an input, and gives back both texts.
3436    fn round_trip(source: &str) -> (String, String) {
3437        let printed = ir(source);
3438        let mut opts = options();
3439        opts.emit = EmitKind::Ir;
3440        let mut fs = MemoryFileSystem::new();
3441        fs.insert("/main.ir", printed.clone().into_bytes());
3442        let result = compile_ir(&opts, "/main.ir", &fs);
3443        assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
3444        (printed, result.text().to_owned())
3445    }
3446
3447    #[test]
3448    fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
3449        // The other half of the round trip test below, through the driver rather than through
3450        // the library, which is what makes the property something to run over a real program
3451        // rather than over the modules a test builds.
3452        let (printed, again) = round_trip(
3453            "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",
3454        );
3455        assert_eq!(printed, again);
3456    }
3457
3458    #[test]
3459    fn ir_that_is_not_ir_says_which_line_stopped_it() {
3460        let mut opts = options();
3461        opts.emit = EmitKind::Ir;
3462        let mut fs = MemoryFileSystem::new();
3463        let text = "\
3464; ModuleID = 'a.c'
3465; format 0
3466target triple = \"x86_64-unknown-linux-gnu\"
3467target datalayout = \"e-p:64:64-i64:64-S128\"
3468
3469func @f(), linkage(external) {
3470block0:
3471    frobnicate
3472}
3473";
3474        fs.insert("/main.ir", text.as_bytes().to_vec());
3475        let result = compile_ir(&opts, "/main.ir", &fs);
3476        assert!(result.failed());
3477        assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
3478    }
3479
3480    #[test]
3481    fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
3482        // A module that a person edited has not been through the verifier, and the return of
3483        // an `i32` from a function that returns nothing is the kind of thing editing produces.
3484        let mut opts = options();
3485        opts.emit = EmitKind::Ir;
3486        let mut fs = MemoryFileSystem::new();
3487        let text = "\
3488; ModuleID = 'a.c'
3489; format 0
3490target triple = \"x86_64-unknown-linux-gnu\"
3491target datalayout = \"e-p:64:64-i64:64-S128\"
3492
3493func @f(), linkage(external) {
3494block0:
3495    %0 = iconst.i32 1
3496    return %0
3497}
3498";
3499        fs.insert("/main.ir", text.as_bytes().to_vec());
3500        let result = compile_ir(&opts, "/main.ir", &fs);
3501        assert!(result.failed());
3502        assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
3503    }
3504
3505    #[test]
3506    fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
3507        // The C that became this is not here any more, so there is nothing to print a tree of.
3508        let mut fs = MemoryFileSystem::new();
3509        fs.insert("/main.ir", Vec::new());
3510        let result = compile_ir(&options(), "/main.ir", &fs);
3511        assert!(result.failed());
3512        assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
3513    }
3514
3515    #[test]
3516    fn the_printed_ir_reads_back_as_the_same_module() {
3517        // The M2 exit criterion: the text is the module and nothing about it is lost by
3518        // writing it down. Anything the printer invents or the parser drops shows up here.
3519        let text = ir("\
3520struct point { int x, y; };
3521static const char greeting[] = \"hi\";
3522int table[4] = { 1, 2, 3 };
3523int puts(const char *);
3524double half(double x) { return x / 2.0; }
3525int f(int n) {
3526  int total = 0;
3527  for (int i = 0; i < n; i++) {
3528    if (i == 3) continue;
3529    total += table[i];
3530  }
3531  switch (n) {
3532    case 0: total = 1;
3533    case 1: total++; break;
3534    default: total = -total;
3535  }
3536  struct point p = { total, 1 };
3537  int *q = &p.y;
3538  puts(greeting);
3539  return p.x + *q;
3540}
3541int dispatch(int c) {
3542  void *p = c ? &&one : &&two;
3543  goto *p;
3544one:
3545  return 1;
3546two:
3547  return 2;
3548}
3549int assembly(int x, int *p) {
3550  int r;
3551  __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
3552  __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
3553  return r;
3554away:
3555  return 0;
3556}
3557");
3558        let mut names = Interner::new();
3559        let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
3560        assert_eq!(rucc_ir::print(&module, &names), text);
3561    }
3562}