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