1use 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_diag::{Diagnostic, Severity, Span};
20use rucc_lex::{Convert, Keywords, PpToken, convert};
21use rucc_sema::{Checker, Context as CheckContext};
22use rucc_session::{EmitKind, FileSystem, Options, Session};
23use rucc_target::TargetInfo;
24
25use crate::preprocess::render;
26
27#[derive(Debug, Clone, PartialEq, Eq, Default)]
34pub enum Artifact {
35 #[default]
38 Nothing,
39 Text(String),
41 Object(Vec<u8>),
43}
44
45impl Artifact {
46 #[must_use]
48 pub fn bytes(&self) -> &[u8] {
49 match self {
50 Artifact::Nothing => &[],
51 Artifact::Text(text) => text.as_bytes(),
52 Artifact::Object(bytes) => bytes,
53 }
54 }
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Compiled {
60 pub artifact: Artifact,
62 pub messages: Vec<String>,
64 pub errors: u32,
66 pub fired: Fired,
72 pub dumps: Vec<rucc_opt::Dump>,
78 pub remarks: String,
84}
85
86impl Compiled {
87 #[must_use]
89 pub fn failed(&self) -> bool {
90 self.errors > 0
91 }
92
93 #[must_use]
98 pub fn text(&self) -> &str {
99 match &self.artifact {
100 Artifact::Text(text) => text,
101 _ => "",
102 }
103 }
104}
105
106#[must_use]
119pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
120 let mut sess = Session::new(opts.clone());
121 let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
125 let mut diagnostics: Vec<Diagnostic> = Vec::new();
126 let mut fired = Fired::new();
128 let mut dumps = Vec::new();
130 let mut remarks = String::new();
131
132 let bytes = match fs.read(Path::new(name)) {
133 Ok(bytes) => bytes,
134 Err(e) => return failure(format!("{name}: {e}")),
135 };
136 let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
137 return failure(format!("{name}: the source map has no room left for this file"));
138 };
139
140 let mut pp = rucc_pp::Preprocessor::new();
144 let predef = rucc_pp::Predef::for_options(opts);
145 let expanded: Vec<PpToken> = {
146 let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
147 cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
148 if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
149 return failure(format!("{name}: the source map has no room for the built in macros"));
150 }
151 pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
152 };
153 diagnostics.extend(pp.take_diagnostics());
154
155 let cx = Convert {
158 keywords: &keywords,
159 interner: &sess.interner,
160 target: &sess.target,
161 std: opts.std,
162 gnu: opts.gnu_extensions,
163 pedantic: opts.pedantic,
164 };
165 let (tokens, complaints) = convert(&expanded, &cx);
166 diagnostics.extend(complaints);
167
168 let parsed = rucc_parse::parse(
169 &tokens,
170 rucc_parse::Context {
171 interner: &sess.interner,
172 std: opts.std,
173 gnu: opts.gnu_extensions,
174 pedantic: opts.pedantic,
175 error_limit: opts.error_limit as usize,
176 },
177 );
178 let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
179 diagnostics.extend(parsed.diagnostics);
180
181 let mut artifact = Artifact::Nothing;
182 let mut instrumented = Instrumented::default();
185 if !parse_failed {
186 let mut checker = Checker::new(
187 &parsed.ast,
188 CheckContext {
189 names: &sess.interner,
190 target: &sess.target,
191 std: opts.std,
192 gnu: opts.gnu_extensions,
193 pedantic: opts.pedantic,
194 gnu89_inline: opts.gnu89_inline,
195 error_limit: opts.error_limit as usize,
196 builtins: opts.builtins && opts.hosted,
199 no_builtin: &opts.no_builtin,
200 },
201 );
202 checker.check_unit();
203 let checked = checker.finish();
204 if !checked.failed() {
205 match opts.emit {
206 EmitKind::Tast => {
207 artifact = Artifact::Text(rucc_sema::print(
208 &checked.tast,
209 &checked.types,
210 &sess.interner,
211 ));
212 }
213 EmitKind::TypeGranules => {
217 artifact = Artifact::Text(rucc_types::granule_report(
218 &checked.types,
219 &sess.interner,
220 &sess.target,
221 ));
222 }
223 EmitKind::Ir
224 | EmitKind::MirFinal
225 | EmitKind::Asm
226 | EmitKind::Object
227 | EmitKind::Executable
228 | EmitKind::SafetySummary => {
229 let mut lowered = rucc_lower::lower(
230 name,
231 rucc_lower::Context {
232 tast: &checked.tast,
233 types: &checked.types,
234 target: &sess.target,
235 names: &mut sess.interner,
236 },
237 );
238 let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
242 if !failed {
243 if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
248 for error in errors {
249 diagnostics.push(internal(&format!("invalid IR, {error}")));
250 }
251 } else if let Err(complaints) =
252 instrument(&mut lowered.module, &mut sess.interner, opts)
253 .map(|done| instrumented = done)
254 {
255 diagnostics.extend(complaints);
256 } else if let Err(complaints) = optimize(
257 &mut lowered.module,
258 &sess.interner,
259 opts,
260 name,
261 &mut dumps,
262 &mut remarks,
263 ) {
264 diagnostics.extend(complaints);
265 } else if opts.emit == EmitKind::SafetySummary {
266 artifact = Artifact::Text(
271 rucc_safety::summarize(
272 &lowered.module,
273 &sess.interner,
274 name,
275 opts.safety.as_str(),
276 instrumented.checks,
277 instrumented.interposed,
278 instrumented.crossings,
279 )
280 .render(),
281 );
282 } else if opts.emit == EmitKind::Ir {
283 artifact =
288 Artifact::Text(rucc_ir::print(&lowered.module, &sess.interner));
289 } else {
290 match generate(
293 &mut lowered.module,
294 &mut sess.interner,
295 &sess.target,
296 opts,
297 &mut fired,
298 ) {
299 Ok(made) => artifact = made,
300 Err(complaints) => diagnostics.extend(complaints),
301 }
302 }
303 }
304 diagnostics.extend(lowered.diagnostics);
305 }
306 _ => {}
307 }
308 }
309 diagnostics.extend(checked.diagnostics);
310 }
311
312 let mut messages = Vec::with_capacity(diagnostics.len());
313 let mut errors = 0;
314 for diag in &diagnostics {
315 if !opts.warnings && diag.severity == Severity::Warning {
319 continue;
320 }
321 if diag.severity.is_fatal()
322 || (diag.severity == Severity::Warning && opts.warnings_are_errors)
323 {
324 errors += 1;
325 }
326 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
327 }
328 if errors > 0 {
329 artifact = Artifact::Nothing;
331 }
332 Compiled { artifact, messages, errors, fired, dumps, remarks }
335}
336
337#[must_use]
347pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
348 let mut sess = Session::new(opts.clone());
349 if opts.emit != EmitKind::Ir {
350 return failure(format!(
351 "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
352 the C in front of it became",
353 opts.emit.as_str()
354 ));
355 }
356 let bytes = match fs.read(Path::new(name)) {
357 Ok(bytes) => bytes,
358 Err(e) => return failure(format!("{name}: {e}")),
359 };
360 let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
361 return failure(format!("{name}: this is not text, so it is not IR"));
362 };
363
364 let module = match rucc_ir::parse(text, &mut sess.interner) {
365 Ok(module) => module,
366 Err(error) => {
367 return failure(format!("{name}:{}: {}", error.line, error.message));
368 }
369 };
370 let mut diagnostics: Vec<Diagnostic> = Vec::new();
371 if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
372 for error in errors {
373 diagnostics.push(invalid(&format!("invalid IR, {error}")));
374 }
375 }
376 let mut messages = Vec::with_capacity(diagnostics.len());
377 for diag in &diagnostics {
378 messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
379 }
380 let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
381 let artifact = if errors > 0 {
382 Artifact::Nothing
383 } else {
384 Artifact::Text(rucc_ir::print(&module, &sess.interner))
385 };
386 Compiled {
388 artifact,
389 messages,
390 errors,
391 fired: Fired::new(),
392 dumps: Vec::new(),
393 remarks: String::new(),
394 }
395}
396
397fn instrument(
420 module: &mut rucc_ir::Module,
421 names: &mut Interner,
422 opts: &Options,
423) -> Result<Instrumented, Vec<Diagnostic>> {
424 if !opts.safety.instruments() {
425 return Ok(Instrumented::default());
426 }
427 let checks = rucc_safety::run(module);
428 let interposed = rucc_safety::redirect(module, names);
433 let crossings = rucc_safety::witness(module, names);
436 match rucc_ir::verify(module, names) {
437 Ok(()) => Ok(Instrumented { checks, interposed, crossings }),
438 Err(errors) => Err(errors
439 .iter()
440 .map(|e| internal(&format!("invalid IR after check insertion, {e}")))
441 .collect()),
442 }
443}
444
445#[derive(Clone, Copy, Debug, Default)]
451struct Instrumented {
452 checks: rucc_safety::Counts,
454 interposed: usize,
456 crossings: rucc_safety::Sites,
458}
459
460fn optimize(
472 module: &mut rucc_ir::Module,
473 names: &Interner,
474 opts: &Options,
475 file: &str,
476 dumps: &mut Vec<rucc_opt::Dump>,
477 remarks: &mut String,
478) -> Result<(), Vec<Diagnostic>> {
479 let mut settings = rucc_opt::Options::for_level(opts.opt_level);
480 settings.toggles.clone_from(&opts.passes);
481 settings.fuel = opts.pass_fuel.iter().cloned().collect();
482 settings.global_fuel = opts.pass_fuel_global;
483 settings.verify |= opts.verify_each;
484 for (on, spec) in &opts.pass_gates {
485 if let Err(why) = settings.gates.add(*on, spec) {
488 return Err(vec![internal(&why)]);
489 }
490 }
491 for spec in &opts.dump_ir {
492 if let Err(why) = settings.dumps.add(spec) {
495 return Err(vec![internal(&why)]);
496 }
497 }
498 let mut wants = rucc_opt::Wants::none();
499 for spec in &opts.opt_info {
500 if let Err(why) = wants.add(spec) {
503 return Err(vec![internal(&why)]);
504 }
505 }
506 let report = rucc_opt::run(module, names, &settings);
507 remarks.push_str(&rucc_opt::optinfo::render(file, &report, names, wants));
508 dumps.extend(report.dumps);
509 match report.broke.is_empty() {
510 true => Ok(()),
511 false => Err(report.broke.iter().map(|why| internal(why)).collect()),
512 }
513}
514
515fn generate(
534 module: &mut rucc_ir::Module,
535 names: &mut Interner,
536 target: &TargetInfo,
537 opts: &Options,
538 fired: &mut Fired,
539) -> Result<Artifact, Vec<Diagnostic>> {
540 let Some(machine) = Machine::for_target(target) else {
541 return Err(vec![unsupported(&format!(
542 "there is no back end for {} in this compiler yet, so there is nothing to generate",
543 target.triple
544 ))]);
545 };
546 let flags = pipeline::Flags { frame_pointer: opts.frame_pointer, red_zone: opts.red_zone };
547
548 if opts.safety.instruments() {
557 rucc_safety::lower(module, names);
558 if let Err(errors) = rucc_ir::verify(module, names) {
559 return Err(errors
560 .iter()
561 .map(|e| internal(&format!("invalid IR after check lowering, {e}")))
562 .collect());
563 }
564 }
565
566 let elsewhere = Elsewhere::of(module);
570
571 let mut funcs = Vec::new();
572 let mut complaints = Vec::new();
573 for id in module.funcs() {
574 if module[id].is_declaration() {
575 continue;
576 }
577 match pipeline::compile_recording(
578 &mut module[id],
579 names,
580 &machine,
581 &elsewhere,
582 flags,
583 fired,
584 ) {
585 Ok(func) => funcs.push(func),
586 Err(why) => {
587 let name = names.resolve(module[id].name).to_owned();
588 let span = why.inst().map_or(Span::DUMMY, |inst| module[id].span(inst));
591 let said = format!("cannot generate code for '{name}': {why}");
592 complaints.push(unsupported_at(&said, span));
593 }
594 }
595 }
596 if !complaints.is_empty() {
597 return Err(complaints);
598 }
599 let (globals, aliases) = match opts.emit {
605 EmitKind::Asm | EmitKind::Object | EmitKind::Executable => (
606 rucc_asm::globals(module, names).map_err(refused)?,
607 rucc_asm::aliases(module, names).map_err(refused)?,
608 ),
609 _ => (rucc_asm::Globals::default(), Vec::new()),
610 };
611 match opts.emit {
615 EmitKind::Asm => rucc_asm::print(&funcs, &globals, &aliases, names, target)
616 .map(Artifact::Text)
617 .map_err(refused),
618 EmitKind::Object | EmitKind::Executable => {
621 let text = rucc_asm::assemble(&funcs, names, target).map_err(refused)?;
622 let data = globals.image();
623 rucc_object::write(&text, &data, &aliases, target).map(Artifact::Object).map_err(
626 |why| match why {
627 rucc_object::Error::Format { .. } => vec![unsupported(&why.to_string())],
628 rucc_object::Error::Refused { .. } => vec![internal(&why.to_string())],
629 },
630 )
631 }
632 _ => Ok(Artifact::Text(rucc_mir::print(&funcs, names, target.regs))),
633 }
634}
635
636fn refused(why: rucc_asm::Error) -> Vec<Diagnostic> {
642 match why {
643 rucc_asm::Error::Thread { .. } | rucc_asm::Error::IFunc { .. } => {
644 vec![unsupported(&why.to_string())]
645 }
646 _ => vec![internal(&why.to_string())],
647 }
648}
649
650fn unsupported(message: &str) -> Diagnostic {
656 unsupported_at(message, Span::DUMMY)
657}
658
659fn unsupported_at(message: &str, span: Span) -> Diagnostic {
665 Diagnostic::error(message.to_owned(), span)
666 .with_code("E0653")
667 .note("this construct is not lowered yet, see https://github.com/tamnd/rucc/issues", span)
668}
669
670fn invalid(message: &str) -> Diagnostic {
672 Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
673}
674
675fn internal(message: &str) -> Diagnostic {
677 Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
678 .with_code("E0652")
679 .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
680}
681
682fn failure(message: String) -> Compiled {
685 Compiled {
686 artifact: Artifact::Nothing,
687 messages: vec![format!("rucc: error: {message}")],
688 errors: 1,
689 fired: Fired::new(),
690 dumps: Vec::new(),
691 remarks: String::new(),
692 }
693}
694
695#[cfg(test)]
696mod tests {
697 use rucc_session::{MemoryFileSystem, Std};
698 use rucc_target::Triple;
699
700 use super::*;
701
702 fn options() -> Options {
703 let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
704 opts.emit = EmitKind::Tast;
705 opts
706 }
707
708 fn run(opts: &Options, source: &str) -> Compiled {
709 let mut fs = MemoryFileSystem::new();
710 fs.insert("/main.c", source.to_owned().into_bytes());
711 compile(opts, "/main.c", &fs)
712 }
713
714 fn freestanding() -> Options {
718 let mut opts = options();
719 opts.hosted = false;
720 opts.search.push_system(rucc_session::runtime::DIR);
721 opts
722 }
723
724 fn shipped(source: &str) -> String {
726 let result = run(&freestanding(), source);
727 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
728 result.text().to_owned()
729 }
730
731 fn tast(source: &str) -> String {
733 let result = run(&options(), source);
734 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
735 result.text().to_owned()
736 }
737
738 #[test]
739 fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
740 let text = shipped(concat!(
741 "#include <stdarg.h>\n",
742 "int sum(int n, ...) {\n",
743 " va_list ap, copy;\n",
744 " va_start(ap, n);\n",
745 " va_copy(copy, ap);\n",
746 " int total = va_arg(ap, int) + va_arg(copy, int);\n",
747 " va_end(ap);\n",
748 " va_end(copy);\n",
749 " return total;\n",
750 "}\n",
751 ));
752 assert!(text.contains("va-start"), "{text}");
753 assert!(text.contains("va-copy"), "{text}");
754 assert!(text.contains("va-arg"), "{text}");
755 assert!(text.contains("va-end"), "{text}");
756 }
757
758 #[test]
762 fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
763 let text = shipped(concat!(
764 "#define __need___va_list\n",
765 "#include <stdarg.h>\n",
766 "int vprint(const char *f, __gnuc_va_list ap);\n",
767 "#ifdef va_start\n",
768 "#error va_start should not be defined\n",
769 "#endif\n",
770 "#ifdef _VA_LIST_DEFINED\n",
771 "#error va_list should not have been made\n",
772 "#endif\n",
773 ));
774 assert!(text.contains("vprint"), "{text}");
775 }
776
777 #[test]
780 fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
781 let text = shipped(concat!(
782 "#define __need_size_t\n",
783 "#include <stddef.h>\n",
784 "#ifdef offsetof\n",
785 "#error offsetof should not be defined yet\n",
786 "#endif\n",
787 "#define __need_ptrdiff_t\n",
788 "#include <stddef.h>\n",
789 "#include <stddef.h>\n",
790 "size_t a;\n",
791 "ptrdiff_t b;\n",
792 "wchar_t c;\n",
793 "max_align_t d;\n",
794 "void *e = NULL;\n",
795 "struct P { int x; long y; };\n",
796 "size_t f = offsetof(struct P, y);\n",
797 ));
798 assert!(text.contains("decl #0 a : unsigned long"), "{text}");
799 assert!(text.contains("decl #1 b : long"), "{text}");
800 }
801
802 #[test]
803 fn the_shipped_limits_and_float_are_the_targets_own_answers() {
804 let text = shipped(concat!(
805 "#include <limits.h>\n",
806 "#include <float.h>\n",
807 "int bits = CHAR_BIT;\n",
808 "long big = LONG_MAX;\n",
809 "int low = INT_MIN;\n",
810 "int radix = FLT_RADIX;\n",
811 "int digits = DBL_MANT_DIG;\n",
812 ));
813 assert!(text.contains("const 8 : int"), "{text}");
814 assert!(text.contains("const 9223372036854775807 : long"), "{text}");
815 assert!(text.contains("const 2 : int"), "{text}");
816 assert!(text.contains("const 53 : int"), "{text}");
817 }
818
819 #[test]
823 fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
824 let text = shipped(concat!(
825 "#include <stdint.h>\n",
826 "int64_t a = INT64_C(1);\n",
827 "uint_least16_t b;\n",
828 "intptr_t c;\n",
829 "uintmax_t d = UINTMAX_MAX;\n",
830 "int wide = sizeof(int_fast64_t);\n",
831 ));
832 assert!(text.contains("decl #0 a : long"), "{text}");
833 assert!(text.contains("decl #1 b : unsigned short"), "{text}");
834 assert!(text.contains("decl #2 c : long"), "{text}");
835 }
836
837 #[test]
838 fn the_three_formality_headers_still_have_to_work() {
839 let text = shipped(concat!(
840 "#include <stdbool.h>\n",
841 "#include <stdalign.h>\n",
842 "#include <iso646.h>\n",
843 "#include <stdnoreturn.h>\n",
844 "int t = true and not false;\n",
845 "_Alignas(16) char buf[16];\n",
846 "int a = alignof(long);\n",
847 ));
848 assert!(text.contains("decl #0 t : int"), "{text}");
849 assert!(text.contains("const 8 : unsigned long"), "{text}");
850 }
851
852 #[test]
855 fn every_shipped_header_can_be_included_twice() {
856 let mut source = String::new();
857 for _ in 0..2 {
858 for name in rucc_session::runtime::names() {
859 source.push_str(&format!("#include <{name}>\n"));
860 }
861 }
862 source.push_str("int x;\n");
863 let text = shipped(&source);
864 assert!(text.starts_with("decl #0 x : int"), "{text}");
865 }
866
867 #[test]
868 fn a_file_that_is_not_there_says_so_and_produces_nothing() {
869 let fs = MemoryFileSystem::new();
870 let result = compile(&options(), "/nope.c", &fs);
871 assert!(result.failed());
872 assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
873 assert!(result.text().is_empty());
874 }
875
876 #[test]
877 fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
878 let text = tast("int x = 1;\n");
879 let expected = "\
880decl #0 x : int object external static defined
881 init
882 +0
883 const 1 : int
884";
885 assert_eq!(text, expected);
886 }
887
888 #[test]
889 fn the_macros_are_expanded_before_anything_is_parsed() {
890 let text = tast("#define N 2\nint a[N];\n");
894 assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
895 }
896
897 #[test]
903 fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
904 let text = tast(concat!(
905 "#pragma pack(4)\n",
906 "struct s { int a; };\n",
907 "#pragma pack()\n",
908 "int b;\n",
909 "_Pragma(\"GCC visibility push(default)\") int c;\n",
910 ));
911 assert!(text.contains("decl #0 b : int"), "{text}");
912 assert!(text.contains("decl #1 c : int"), "{text}");
913 }
914
915 #[test]
923 fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
924 tast(concat!(
925 "struct A { char c; int i; } __attribute__((packed));\n",
926 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
927 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
928 "struct B { char c; int i; } __attribute__((aligned));\n",
931 "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
932 "struct C { char c; int i __attribute__((packed)); };\n",
933 "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
934 "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
935 "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
936 "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
937 "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
938 "struct E { char c; _Alignas(8) int i; };\n",
939 "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
940 "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
941 "struct F { char c; int i __attribute__((aligned(8))); };\n",
942 "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
943 "struct G { char c; short s; } __attribute__((aligned(2)));\n",
946 "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
947 "struct H { char c; int i; } __attribute__((aligned(2)));\n",
948 "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
949 "struct I { [[gnu::packed]] char c; int i; };\n",
952 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
953 "struct J { char c; [[gnu::packed]] int i; };\n",
954 "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
955 "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
956 "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
957 "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
958 "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
959 "union L { char c; int i; } __attribute__((packed));\n",
960 "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
961 "struct O { char c; int i; } __attribute__((__packed__));\n",
965 "_Static_assert(sizeof(struct O) == 5 && _Alignof(struct O) == 1, \"O\");\n",
966 "struct P { char c; int i; } __attribute__((__aligned__(8)));\n",
967 "_Static_assert(sizeof(struct P) == 8 && _Alignof(struct P) == 8, \"P\");\n",
968 ));
969 }
970
971 #[test]
980 fn the_aligned_attribute_on_a_declaration_raises_what_that_one_object_is_aligned_to() {
981 tast(concat!(
982 "int v __attribute__((aligned(64)));\n",
983 "_Static_assert(__alignof__(v) == 64, \"v\");\n",
984 "__attribute__((aligned(32))) int w;\n",
987 "_Static_assert(__alignof__(w) == 32, \"w\");\n",
988 "[[gnu::aligned(16)]] int x;\n",
989 "_Static_assert(__alignof__(x) == 16, \"x\");\n",
990 "int y __attribute__((aligned(2)));\n",
993 "_Static_assert(__alignof__(y) == 4, \"y\");\n",
994 "void f(void) { int a __attribute__((aligned(128)));\n",
996 "_Static_assert(__alignof__(a) == 128, \"a\"); (void)a; }\n",
997 "_Static_assert(__alignof__(int) == 4, \"int\");\n",
1000 "void g(void) __attribute__((aligned(256)));\n",
1003 "void g(void) {}\n",
1004 "_Static_assert(__alignof__(g) == 256, \"g\");\n",
1005 ));
1006 }
1007
1008 #[test]
1012 fn what_a_declaration_asked_to_be_aligned_to_is_what_the_assembler_is_told() {
1013 let text = asm(concat!(
1014 "int v __attribute__((aligned(64)));\n",
1015 "void g(void) __attribute__((aligned(256)));\n",
1016 "void g(void) {}\n",
1017 "void plain(void) {}\n",
1018 ));
1019 assert!(text.contains("\t.p2align\t6\n\t.type\tv, @object\n"), "{text}");
1020 assert!(text.contains("\t.p2align\t8, 0x90\n\t.globl\tg\n"), "{text}");
1021 assert!(text.contains("\t.p2align\t4, 0x90\n\t.globl\tplain\n"), "{text}");
1022 }
1023
1024 #[test]
1033 fn an_aligned_typedef_says_what_an_object_of_it_is_aligned_to_and_may_lower_it() {
1034 tast(concat!(
1035 "typedef int L __attribute__((aligned(2)));\n",
1036 "_Static_assert(__alignof__(L) == 2, \"L\");\n",
1037 "_Static_assert(_Alignof(L) == 2, \"L alignof\");\n",
1038 "_Static_assert(sizeof(L) == 4, \"L size\");\n",
1040 "struct T { char c; L x; };\n",
1041 "_Static_assert(sizeof(struct T) == 6, \"T\");\n",
1042 "_Static_assert(__builtin_offsetof(struct T, x) == 2, \"T.x\");\n",
1043 "typedef int H __attribute__((aligned(16)));\n",
1045 "_Static_assert(__alignof__(H) == 16, \"H\");\n",
1046 "_Static_assert(sizeof(H) == 4, \"H size\");\n",
1047 "struct U { char c; H x; };\n",
1048 "_Static_assert(sizeof(struct U) == 32, \"U\");\n",
1049 "_Static_assert(__builtin_offsetof(struct U, x) == 16, \"U.x\");\n",
1050 "typedef L M __attribute__((aligned(8)));\n",
1053 "_Static_assert(__alignof__(M) == 8, \"M\");\n",
1054 "typedef L N;\n",
1057 "_Static_assert(__alignof__(N) == 2, \"N\");\n",
1058 "_Static_assert(__alignof__(int) == 4, \"int\");\n",
1060 ));
1061 let text = asm(concat!(
1062 "typedef int L __attribute__((aligned(2)));\n",
1063 "typedef int H __attribute__((aligned(16)));\n",
1064 "L low;\n",
1065 "H high;\n",
1066 ));
1067 assert!(text.contains("\t.p2align\t1\n\t.type\tlow, @object\n"), "{text}");
1068 assert!(text.contains("\t.p2align\t4\n\t.type\thigh, @object\n"), "{text}");
1069 }
1070
1071 #[test]
1079 fn the_vector_size_attribute_builds_a_type_of_lanes_and_measures_it_in_bytes() {
1080 tast(concat!(
1081 "typedef int __attribute__((vector_size(16))) v4si;\n",
1082 "_Static_assert(sizeof(v4si) == 16 && _Alignof(v4si) == 16, \"v4si\");\n",
1083 "typedef char __attribute__((vector_size(16))) v16qi;\n",
1084 "_Static_assert(sizeof(v16qi) == 16, \"v16qi\");\n",
1085 "typedef int __attribute__((vector_size(4))) v1si;\n",
1088 "_Static_assert(sizeof(v1si) == 4, \"v1si\");\n",
1089 "typedef float __attribute__((__vector_size__(8))) v2sf;\n",
1091 "_Static_assert(sizeof(v2sf) == 8, \"v2sf\");\n",
1092 "typedef short [[gnu::vector_size(8)]] v4hi;\n",
1093 "_Static_assert(sizeof(v4hi) == 8, \"v4hi\");\n",
1094 "v4si g;\n",
1097 "_Static_assert(sizeof(g[0]) == 4, \"lane\");\n",
1098 "_Static_assert(sizeof(g + g) == 16, \"whole\");\n",
1099 "_Static_assert(sizeof(g + 1) == 16, \"broadcast\");\n",
1102 "_Static_assert(sizeof(v4si[3]) == 48, \"array\");\n",
1104 ));
1105 }
1106
1107 #[test]
1117 fn a_vector_is_written_whole_into_an_array_of_them_and_named_by_a_type_name() {
1118 tast(concat!(
1119 "typedef int __attribute__((vector_size(8))) v2si;\n",
1120 "v2si table[] = { (v2si){ 1, 2 }, (v2si){ 3, 4 } };\n",
1121 "_Static_assert(sizeof(table) == 16, \"two of them and not eight lanes\");\n",
1122 "v2si written = (int __attribute__((vector_size(8)))){ 5, 6 };\n",
1124 "_Static_assert(sizeof((int __attribute__((vector_size(16)))){ 0 }) == 16, \"named\");\n",
1125 "v2si lanes[2] = { 1, 2, 3, 4 };\n",
1128 "_Static_assert(sizeof(lanes) == 16, \"still elided\");\n",
1129 ));
1130 }
1131
1132 #[test]
1140 fn a_lane_is_assignable_and_a_shift_takes_a_count_of_its_own_lane() {
1141 let result = run(
1142 &options(),
1143 concat!(
1144 "typedef int __attribute__((vector_size(16))) v4si;\n",
1145 "typedef unsigned __attribute__((vector_size(16))) v4ui;\n",
1146 "void write(v4si *out, v4ui a, v4si b, int n) {\n",
1147 " v4si v = { 1, 2, 3, 4 };\n",
1148 " v[0] = n;\n",
1149 " v[1] += n;\n",
1150 " v[2]++;\n",
1151 " *&v[3] = n;\n",
1152 " v4ui shifted = a >> b;\n",
1154 " shifted <<= b;\n",
1155 " *out = v + (v4si)shifted + (1 << b);\n",
1158 "}\n",
1159 "void refused(const v4si c) {\n",
1162 " c[0] = 1;\n",
1163 "}\n",
1164 ),
1165 );
1166 assert_eq!(result.messages.len(), 1, "{:?}", result.messages);
1167 assert!(result.messages[0].contains("assignment of read-only"), "{:?}", result.messages);
1168 }
1169
1170 #[test]
1177 fn a_record_that_asks_for_the_other_byte_order_is_refused_rather_than_laid_out_in_this_one() {
1178 let opts = options();
1179 let big = "struct s { int i; } __attribute__((scalar_storage_order(\"big-endian\")));\n";
1180 assert_eq!(
1181 run(&opts, big).messages,
1182 ["/main.c:1:36: error: 'scalar_storage_order' is not implemented yet [E0688]\n\
1183 /main.c:1:36: note: every scalar in this record would be read in the wrong byte \
1184 order"]
1185 );
1186
1187 let armoured =
1188 "struct s { int i; } __attribute__((__scalar_storage_order__(\"little-endian\")));\n";
1189 let messages = run(&opts, armoured).messages;
1190 assert!(messages[0].contains("[E0688]"), "{messages:?}");
1191
1192 let front = "struct __attribute__((scalar_storage_order(\"big-endian\"))) s { int i; };\n";
1195 assert!(run(&opts, front).messages[0].contains("[E0688]"), "{front}");
1196 let standard = "struct s { int i; } [[gnu::scalar_storage_order(\"big-endian\")]];\n";
1197 assert!(run(&opts, standard).messages[0].contains("[E0688]"), "{standard}");
1198 }
1199
1200 #[test]
1210 fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
1211 assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
1213 assert_eq!(
1214 bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
1215 1
1216 );
1217 assert_eq!(
1218 bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
1219 1
1220 );
1221 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
1222 assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
1224 assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
1225 assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
1227 assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
1228 }
1229
1230 fn bit_field_byte(record: &str) -> u64 {
1232 let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
1233 let body = body(&source);
1234 let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
1235 let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
1236 constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
1237 }
1238
1239 #[test]
1245 fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
1246 tast(concat!(
1247 "struct a { char c; __attribute__((aligned(8))) int i; };\n",
1248 "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
1249 "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
1250 "struct b { char c; __attribute__((packed)) int i; };\n",
1251 "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
1252 "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
1253 "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
1254 "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
1255 ));
1256 }
1257
1258 #[test]
1264 fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
1265 tast(concat!(
1266 "#pragma pack(1)\n",
1267 "struct A { char c; int i; };\n",
1268 "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
1269 "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
1270 "#pragma pack()\n",
1271 "struct B { char c; int i; };\n",
1272 "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
1273 "#pragma pack(2)\n",
1274 "struct C { char c; int i; double d; };\n",
1275 "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
1276 "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
1277 "struct K { char c; int i __attribute__((aligned(8))); };\n",
1279 "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
1280 "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
1281 "struct J { char c; int i; } __attribute__((aligned(8)));\n",
1283 "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
1284 "#pragma pack()\n",
1285 "#pragma pack(push, 1)\n",
1286 "struct D { char c; short s; };\n",
1287 "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
1288 "#pragma pack(pop)\n",
1289 "struct E { char c; short s; };\n",
1290 "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
1291 "struct H { char c;\n",
1293 "#pragma pack(1)\n",
1294 " int i; };\n",
1295 "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
1296 "#pragma pack(1)\n",
1297 "struct I { char c;\n",
1298 "#pragma pack()\n",
1299 " int i; };\n",
1300 "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
1301 "#pragma pack()\n",
1302 "#pragma pack(push, 8)\n",
1304 "#pragma pack(push, 1)\n",
1305 "struct P { char c; int i; };\n",
1306 "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
1307 "#pragma pack(pop)\n",
1308 "struct Q { char c; int i; };\n",
1309 "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
1310 "#pragma pack(pop)\n",
1311 "#pragma pack(16)\n",
1313 "struct R { char c; int i; };\n",
1314 "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
1315 "#pragma pack()\n",
1316 "#pragma pack(1)\n",
1317 "struct S { char c; int i : 5; int j : 20; };\n",
1318 "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
1319 "union T { char c; int i; };\n",
1320 "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
1321 "#pragma pack()\n",
1322 ));
1323 }
1324
1325 #[test]
1329 fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
1330 let result = run(
1331 &options(),
1332 concat!(
1333 "#pragma pack 4\n",
1334 "#pragma pack(pop)\n",
1335 "#pragma pack(3)\n",
1336 "#pragma pack(1) junk\n",
1337 "#pragma pack(push, 1\n",
1338 "#pragma pack(x)\n",
1339 "#pragma pack(0)\n",
1342 "#pragma pack(push)\n",
1343 "struct s { char c; int i; };\n",
1344 "#pragma pack(pop)\n",
1345 "#pragma pack(pop, foo)\n",
1346 ),
1347 );
1348 let expected = [
1349 "missing `(` after `#pragma pack` - ignored",
1350 "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
1351 "alignment must be a small power of two, not 3",
1352 "junk at end of `#pragma pack`",
1353 "malformed `#pragma pack(push[, id][, <n>])` - ignored",
1354 "unknown action `x` for `#pragma pack` - ignored",
1355 "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
1356 ];
1357 assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
1358 for (message, want) in result.messages.iter().zip(expected) {
1359 assert!(message.contains(want), "expected {want:?} in {message:?}");
1360 }
1361 }
1362
1363 #[test]
1367 fn the_wide_integer_answers_to_all_three_of_its_names() {
1368 let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
1369 assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
1370 assert!(text.contains("decl #1 b : __int128"), "{text}");
1371 assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
1372 }
1373
1374 #[test]
1375 fn every_conversion_the_language_performs_is_a_node_in_the_output() {
1376 let text = tast("long f(int a, long b) { return a + b; }\n");
1380 assert!(text.contains("convert arithmetic"), "{text}");
1381 }
1382
1383 #[test]
1384 fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
1385 for source in [
1386 "#error stop\n",
1387 "int f(void) { return 1 + ; }\n",
1388 "int f(void) { return undeclared; }\n",
1389 ] {
1390 let result = run(&options(), source);
1391 assert!(result.failed(), "expected this to fail:\n{source}");
1392 assert!(
1393 result.text().is_empty(),
1394 "a file that did not compile wrote a tree:\n{source}"
1395 );
1396 }
1397 }
1398
1399 #[test]
1400 fn one_undeclared_name_is_one_message_and_not_one_per_use() {
1401 let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
1405 assert_eq!(result.errors, 1, "{:?}", result.messages);
1406 }
1407
1408 #[test]
1409 fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
1410 let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
1414 assert_eq!(result.errors, 1, "{:?}", result.messages);
1415 }
1416
1417 #[test]
1418 fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
1419 let source = "int f(void) { char c = 300; return c; }\n";
1420 let plain = run(&options(), source);
1421 assert_eq!(plain.errors, 0, "{:?}", plain.messages);
1422 assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
1423 assert!(!plain.text().is_empty(), "a warning is not a reason to write nothing");
1424
1425 let mut opts = options();
1426 opts.warnings_are_errors = true;
1427 let strict = run(&opts, source);
1428 assert!(strict.failed());
1429 assert!(strict.text().is_empty(), "and under -Werror it is a reason to write nothing");
1430 for message in &strict.messages {
1431 assert!(!message.contains("warning:"), "{message}");
1432 }
1433 }
1434
1435 #[test]
1436 fn w_drops_the_warning_before_werror_can_promote_it() {
1437 let source = "int f(void) { char c = 300; return c; }\n";
1438 let mut opts = options();
1439 opts.warnings = false;
1440 let quiet = run(&opts, source);
1441 assert_eq!(quiet.messages, Vec::<String>::new());
1442 assert_eq!(quiet.errors, 0);
1443 assert!(!quiet.text().is_empty(), "and the file still compiles");
1444
1445 opts.warnings_are_errors = true;
1448 let both = run(&opts, source);
1449 assert_eq!(both.messages, Vec::<String>::new());
1450 assert!(!both.failed(), "-w -Werror is not an error about a warning nobody saw");
1451 }
1452
1453 #[test]
1454 fn the_dialect_reaches_the_keywords_and_the_checking() {
1455 let source = "typeof(1) x;\n";
1458 let mut opts = options();
1459 opts.std = Std::C23;
1460 opts.gnu_extensions = false;
1461 assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
1462
1463 opts.std = Std::C17;
1464 assert!(run(&opts, source).failed());
1465 }
1466
1467 #[test]
1468 fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
1469 let mut opts = options();
1470 opts.emit = EmitKind::Object;
1471 let result = run(&opts, "int x = 1;\n");
1472 assert!(!result.failed(), "{:?}", result.messages);
1473 assert!(result.text().is_empty());
1474 assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
1477 }
1478
1479 fn mir(source: &str) -> String {
1481 let mut opts = options();
1482 opts.emit = EmitKind::MirFinal;
1483 let result = run(&opts, source);
1484 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1485 result.text().to_owned()
1486 }
1487
1488 #[test]
1494 fn a_function_goes_from_c_to_instructions_with_real_registers_in_them() {
1495 let text = mir("int add(int a, int b) { return a + b; }\n");
1496 assert!(text.starts_with("mfunc @add {"), "{text}");
1497 assert!(text.contains("x64.add_rr_32"), "{text}");
1498 assert!(text.contains("x64.ret"), "{text}");
1499 assert!(!text.contains('%'), "{text}");
1502 }
1503
1504 #[test]
1506 fn a_function_with_no_body_produces_no_machine_function() {
1507 let text = mir("int g(int);\nint f(int a) { return g(a); }\n");
1508 assert_eq!(text.matches("mfunc @").count(), 1, "{text}");
1509 assert!(text.contains("mfunc @f {"), "{text}");
1510 assert!(text.contains("x64.call"), "{text}");
1511 }
1512
1513 #[test]
1515 fn every_definition_in_the_file_is_generated_and_they_keep_their_order() {
1516 let text = mir("int a(int x) { return x; }\nint b(int x) { return x; }\n");
1517 let first = text.find("mfunc @a").expect("the first function");
1518 let second = text.find("mfunc @b").expect("the second function");
1519 assert!(first < second, "{text}");
1520 }
1521
1522 #[test]
1524 fn the_target_decides_which_convention_the_generated_code_follows() {
1525 let mut opts = options();
1526 opts.emit = EmitKind::MirFinal;
1527 let linux = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1528 assert!(linux.contains("$rdi"), "{linux}");
1529
1530 opts.target = "x86_64-pc-windows-msvc".parse::<Triple>().unwrap();
1531 let windows = run(&opts, "int f(int a) { return a; }\n").text().to_owned();
1532 assert!(windows.contains("$rcx"), "{windows}");
1533 assert!(!windows.contains("$rdi"), "{windows}");
1534 }
1535
1536 #[test]
1538 fn a_target_this_has_no_back_end_for_is_reported_rather_than_generated() {
1539 let mut opts = options();
1540 opts.emit = EmitKind::MirFinal;
1541 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1542 let result = run(&opts, "int f(int a) { return a; }\n");
1543 assert!(result.failed());
1544 assert!(result.messages[0].contains("no back end for aarch64"), "{:?}", result.messages);
1545 assert!(result.text().is_empty());
1546 }
1547
1548 #[test]
1555 fn a_construct_the_back_end_cannot_reach_yet_is_reported_against_its_function() {
1556 let mut opts = options();
1557 opts.emit = EmitKind::MirFinal;
1558 let source = "void a(int n) { int v[n]; v[0] = 1; }\n\
1559 void b(int n) { int v[n]; v[0] = 1; }\n";
1560 let result = run(&opts, source);
1561 assert!(result.failed());
1562 assert_eq!(result.messages.len(), 2, "{:?}", result.messages);
1563 assert!(result.messages[0].contains("cannot generate code for 'a'"), "{:?}", result);
1564 assert!(result.messages[0].contains("no rule lowers a `stacksave`"), "{:?}", result);
1565 assert!(result.messages[1].contains("cannot generate code for 'b'"), "{:?}", result);
1566 assert!(result.text().is_empty());
1567 }
1568
1569 #[test]
1576 fn an_opcode_with_no_name_in_the_rule_language_is_named_by_its_own_spelling() {
1577 let mut opts = options();
1578 opts.emit = EmitKind::MirFinal;
1579 let result = run(&opts, "int f(int a) {\n __int128 wide = a;\n return (int) wide;\n}\n");
1580 assert!(result.failed());
1581 assert!(
1582 result.messages[0].contains("no rule lowers a `sext` producing a `i128`"),
1583 "{result:?}"
1584 );
1585 assert!(result.messages[0].contains(":2:"), "the line the widening is on: {result:?}");
1586 assert!(!result.messages[0].contains("this instruction"), "{result:?}");
1587 }
1588
1589 #[test]
1591 fn the_note_on_unfinished_work_points_at_the_issues_rather_than_at_the_plan() {
1592 let mut opts = options();
1593 opts.emit = EmitKind::MirFinal;
1594 let result = run(&opts, "int f(int a) { __int128 wide = a; return (int) wide; }\n");
1595 assert!(result.failed());
1596 let note = result.messages.iter().find(|line| line.contains("note:")).expect("a note");
1597 assert!(note.contains("https://github.com/tamnd/rucc/issues"), "{note}");
1598 assert!(!note.contains("spec/17-milestones.md"), "{note}");
1599 }
1600
1601 #[test]
1603 fn the_frame_flags_on_the_command_line_reach_the_generated_frame() {
1604 let source = "int f(int a) { return a; }\n";
1605 assert!(!mir(source).contains("$rbp"), "a leaf needs no frame pointer by default");
1606
1607 let mut opts = options();
1608 opts.emit = EmitKind::MirFinal;
1609 opts.frame_pointer = true;
1610 let kept = run(&opts, source).text().to_owned();
1611 assert!(kept.contains("x64.push_64 $rbp"), "{kept}");
1612 }
1613
1614 fn asm(source: &str) -> String {
1616 let mut opts = options();
1617 opts.emit = EmitKind::Asm;
1618 let result = run(&opts, source);
1619 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1620 result.text().to_owned()
1621 }
1622
1623 #[test]
1630 fn a_function_goes_from_c_to_assembly_an_assembler_would_take() {
1631 let text = asm("int add(int a, int b) { return a + b; }\n");
1632 assert!(text.contains("\t.globl\tadd\n"), "{text}");
1633 assert!(text.contains("\t.type\tadd, @function\n"), "{text}");
1634 assert!(text.contains("\nadd:\n"), "{text}");
1635 assert!(text.contains("\taddl\t"), "{text}");
1636 assert!(text.contains("\tret\n"), "{text}");
1637 assert!(text.contains("\t.size\tadd, .-add\n"), "{text}");
1638 assert!(text.contains(".note.GNU-stack"), "{text}");
1641 }
1642
1643 #[test]
1649 fn a_call_through_a_function_pointer_goes_through_the_register_it_is_in() {
1650 let text = asm("int g(int);\nint f(int (*p)(int), int a) { return p(a) + g(a); }\n");
1651 assert!(text.contains("\tcall\t*%"), "{text}");
1652 assert!(text.contains("\tcall\tg\n"), "{text}");
1653 assert!(text.contains("%rdi"), "{text}");
1657 }
1658
1659 #[test]
1661 fn the_address_of_a_global_is_read_from_the_instruction_pointer() {
1662 let text = asm("extern int counter;\nint f(void) { return counter; }\n");
1663 assert!(text.contains("\tleaq\tcounter(%rip), "), "{text}");
1664 }
1665
1666 #[test]
1668 fn a_cast_between_a_pointer_and_an_integer_leaves_the_value_where_it_is() {
1669 let text = asm("long f(void *p) { return (long)p; }\n");
1670 for line in text.lines().filter(|line| line.starts_with('\t') && !line.contains('.')) {
1675 let mnemonic = line.split_whitespace().next().unwrap_or("");
1676 assert!(matches!(mnemonic, "movq" | "ret"), "{line} in\n{text}");
1677 }
1678 }
1679
1680 #[test]
1684 fn an_argument_past_the_last_register_is_read_out_of_the_caller_s_stack() {
1685 let six = "long a, long b, long c, long d, long e, long f";
1686 let text = asm(&format!("long f({six}, long g, long h) {{ return g + h; }}\n"));
1687
1688 assert!(text.contains("\tmovq\t8(%rsp), "), "{text}");
1692 assert!(text.contains("\tmovq\t16(%rsp), "), "{text}");
1693
1694 let narrow = asm(&format!("int f({six}, int g) {{ return g; }}\n"));
1698 assert!(narrow.contains("\tmovl\t8(%rsp), "), "{narrow}");
1699 let eight =
1700 "double a, double b, double c, double d, double e, double f, double g, double h";
1701 let float = asm(&format!("double f({eight}, double i) {{ return i; }}\n"));
1702 assert!(float.contains("\tmovsd\t8(%rsp), "), "{float}");
1703 }
1704
1705 #[test]
1708 fn a_call_writes_the_arguments_with_no_register_left_at_the_stack_pointer() {
1709 let six = "1, 2, 3, 4, 5, 6";
1710 let decl = "long g(long, long, long, long, long, long, long, long);\n";
1711 let text = asm(&format!("{decl}long f(void) {{ return g({six}, 7, 8); }}\n"));
1712
1713 assert!(text.contains("\tmovq\t%"), "{text}");
1714 assert!(text.contains(", (%rsp)\n"), "{text}");
1715 assert!(text.contains(", 8(%rsp)\n"), "{text}");
1716 assert!(text.contains("\tsubq\t$"), "{text}");
1718
1719 let narrow = "int g(int, int, int, int, int, int, int);\n";
1721 let text = asm(&format!("{narrow}int f(void) {{ return g({six}, 7); }}\n"));
1722 assert!(text.contains("\tmovl\t%"), "{text}");
1723 assert!(text.contains(", (%rsp)\n"), "{text}");
1724 }
1725
1726 #[test]
1729 fn a_variadic_call_counts_registers_and_not_arguments() {
1730 let nine = "1., 2., 3., 4., 5., 6., 7., 8., 9.";
1731 let decl = "int g(int, ...);\n";
1732 let text = asm(&format!("{decl}int f(void) {{ return g(0, {nine}); }}\n"));
1733
1734 assert!(text.contains("\tmovl\t$8, "), "eight registers, not nine: {text}");
1735 assert!(text.contains("\tmovsd\t%"), "{text}");
1736 assert!(text.contains(", (%rsp)\n"), "{text}");
1737 }
1738
1739 #[test]
1744 fn a_variadic_function_writes_the_argument_registers_it_was_handed_into_its_frame() {
1745 let body =
1746 "__builtin_va_list ap; __builtin_va_start(ap, n); __builtin_va_end(ap); return n;";
1747 let text = asm(&format!("int f(int n, ...) {{ {body} }}\n"));
1748
1749 let stores = |mnemonic: &str| text.matches(&format!("\t{mnemonic}\t%")).count();
1752 assert!(text.contains(", 8(%r"), "the second slot, not the first: {text}");
1753 assert!(!text.contains(", 0(%r"), "{text}");
1754 assert_eq!(stores("movsd"), 8, "every vector register: {text}");
1755
1756 assert!(text.contains("\tsubq\t$"), "{text}");
1758 }
1759
1760 #[test]
1763 fn va_start_writes_the_four_fields_the_psabi_describes() {
1764 let start = "__builtin_va_list ap; __builtin_va_start(ap, d);";
1765 let params = "int a, int b, int c, double d";
1766 let text = asm(&format!("int f({params}, ...) {{ {start} return a; }}\n"));
1767
1768 assert!(text.contains(" movl $24, "), "{text}");
1772 assert!(text.contains(" movl $64, "), "{text}");
1773 assert!(text.contains(", 8(%r"), "{text}");
1777 assert!(text.contains(", 16(%r"), "{text}");
1778 let frame: u32 = text
1779 .lines()
1780 .find_map(|line| line.trim().strip_prefix("subq $")?.split(',').next()?.parse().ok())
1781 .expect("a variadic function takes a frame for the save area");
1782 let above = |line: &str| {
1783 let at: u32 = line.trim().strip_prefix("leaq ")?.split('(').next()?.parse().ok()?;
1784 Some(at > frame)
1785 };
1786 assert!(text.lines().filter_map(above).any(|it| it), "{frame}: {text}");
1787 }
1788
1789 #[test]
1792 fn va_arg_branches_on_whether_the_argument_is_still_in_the_save_area() {
1793 let read = "__builtin_va_list ap; __builtin_va_start(ap, n);";
1794 let ints = format!("int f(int n, ...) {{ {read} return __builtin_va_arg(ap, int); }}\n");
1795 let text = asm(&ints);
1796
1797 assert!(text.contains("$40, "), "{text}");
1800 assert!(text.contains(" cmpl "), "{text}");
1801 assert!(text.contains(" setbe "), "unsigned, since an offset is a count of bytes: {text}");
1802
1803 let arg = "__builtin_va_arg(ap, double)";
1804 let text = asm(&format!("double f(int n, ...) {{ {read} return {arg}; }}\n"));
1805 assert!(text.contains("$160, "), "the last vector slot: {text}");
1806 }
1807
1808 #[test]
1811 fn a_structure_assignment_is_a_move_for_each_word_of_it() {
1812 let decl = "struct pair { long a, b; };\n";
1813 let body = "struct pair p = *q; return p.a + p.b;";
1814 let text = asm(&format!("{decl}long f(struct pair *q) {{ {body} }}\n"));
1815
1816 assert!(!text.contains("memcpy"), "nothing calls the library: {text}");
1817 assert!(!text.contains("\tcall"), "{text}");
1818 assert!(text.matches("\tmovq\t").count() >= 4, "two words each way: {text}");
1820 }
1821
1822 #[test]
1825 fn how_wide_a_word_of_a_copy_is_follows_the_alignment() {
1826 let decl = "struct bytes { char a[8]; };\n";
1827 let body = "struct bytes p = *q; return p.a[0];";
1828 let text = asm(&format!("{decl}int f(struct bytes *q) {{ {body} }}\n"));
1829
1830 assert!(text.matches("\tmovb\t").count() >= 16, "a byte at a time: {text}");
1832 }
1833
1834 #[test]
1837 fn the_part_of_an_initialiser_that_names_nothing_is_stored_as_zero() {
1838 let decl = "struct wide { long a, b, c; };\n";
1839 let text = asm(&format!("{decl}long f(void) {{ struct wide w = {{ 7 }}; return w.c; }}\n"));
1840
1841 assert!(!text.contains("memset"), "nothing calls the library: {text}");
1842 assert!(text.contains("\tmovq\t$0, ") || text.contains("$0, %"), "the zero: {text}");
1843 }
1844
1845 #[test]
1848 fn a_copy_too_large_to_unroll_calls_the_runtime() {
1849 let decl = "struct huge { char a[4096]; };\n";
1850 let mut opts = options();
1851 opts.emit = EmitKind::Asm;
1852 let source = format!("{decl}void f(struct huge *p, struct huge *q) {{ *p = *q; }}\n");
1853 let result = run(&opts, &source);
1854 assert!(!result.failed(), "{:?}", result.messages);
1855 let text = result.text();
1856 assert!(text.contains("call") && text.contains("memcpy"), "{text}");
1857 assert!(text.contains("4096"), "the size travels: {text}");
1860 }
1861
1862 #[test]
1865 fn a_realigned_frame_reads_them_through_the_frame_pointer() {
1866 let six = "long a, long b, long c, long d, long e, long f";
1867 let body = "_Alignas(32) long wide[4]; wide[0] = g; return wide[0];";
1868 let text = asm(&format!("long f({six}, long g) {{ {body} }}\n"));
1869
1870 assert!(text.contains("\tandq\t$-32, %rsp"), "{text}");
1874 assert!(text.contains("\tmovq\t16(%rbp), "), "{text}");
1875 assert!(!text.contains("\tmovq\t16(%rsp), "), "{text}");
1876 }
1877
1878 #[test]
1880 fn the_target_decides_how_the_assembly_is_spelled() {
1881 let mut opts = options();
1882 opts.emit = EmitKind::Asm;
1883 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
1884 let text = run(&opts, "int f(void) { return 0; }\n").text().to_owned();
1885 assert!(text.contains("__TEXT,__text"), "{text}");
1886 assert!(text.contains("\n_f:\n"), "{text}");
1887 assert!(!text.contains(".note.GNU-stack"), "{text}");
1888 }
1889
1890 fn obj(source: &str) -> Vec<u8> {
1892 let mut opts = options();
1893 opts.emit = EmitKind::Object;
1894 let result = run(&opts, source);
1895 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
1896 match result.artifact {
1897 Artifact::Object(bytes) => bytes,
1898 other => panic!("expected an object, got {other:?}"),
1899 }
1900 }
1901
1902 #[test]
1908 fn a_function_goes_from_c_to_an_object_a_linker_would_take() {
1909 let bytes = obj("int add(int a, int b) { return a + b; }\n");
1910 assert_eq!(&bytes[..4], b"\x7fELF", "an object file starts by saying it is one");
1911 let text = asm("int add(int a, int b) { return a + b; }\n");
1912 assert!(
1913 text.contains("\taddl\t"),
1914 "and the listing of it is the same instructions:\n{text}"
1915 );
1916 }
1917
1918 #[test]
1920 fn a_variable_goes_from_c_to_the_section_it_belongs_in() {
1921 let text = asm("int counter = 42;\nstatic int hidden;\nconst int fixed = 7;\n");
1922 assert!(text.contains("\t.data\n\t.globl\tcounter\n"), "{text}");
1923 assert!(text.contains("\ncounter:\n\t.long\t42\n"), "{text}");
1924 assert!(text.contains("\t.size\tcounter, .-counter\n"), "{text}");
1925 assert!(text.contains("\t.bss\n\t.p2align\t2\n"), "{text}");
1928 assert!(text.contains("\nhidden:\n\t.space\t4\n"), "{text}");
1929 assert!(!text.contains(".globl\thidden"), "{text}");
1930 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1933 }
1934
1935 #[test]
1942 fn a_bit_field_initializer_writes_every_byte_of_the_value_and_not_only_the_ones_that_are_set() {
1943 let text = asm("struct s { unsigned f : 20; } x = { 0x12300 };\n");
1944 assert!(text.contains("\t.data\n"), "there is something to write: {text}");
1945 assert!(text.contains("\nx:\n\t.ascii\t\"\\000#\\001\"\n"), "and it is the value: {text}");
1946
1947 let text = asm("struct s { unsigned a : 8; unsigned b : 8; } x = { 0, 3 };\n");
1950 assert!(text.contains("\nx:\n\t.ascii\t\"\\000\\003\"\n"), "{text}");
1951
1952 let text = asm("struct s { unsigned long long f : 40; } x = { 0x100000 };\n");
1955 assert!(text.contains("\nx:\n\t.ascii\t\"\\000\\000\\020\"\n\t.space\t5\n"), "{text}");
1956
1957 let text = asm("struct s { unsigned f : 20; } x = { 0 };\n");
1959 assert!(text.contains("\t.bss\n"), "an object of zeroes is zeroes: {text}");
1960 assert!(text.contains("\nx:\n\t.space\t4\n"), "{text}");
1961 }
1962
1963 #[test]
1965 fn a_string_literal_is_a_variable_with_a_name_no_program_could_write() {
1966 let text = asm("const char *f(void) { return \"hi\"; }\n");
1967 assert!(text.contains("\t.ascii\t\"hi\\000\"\n"), "{text}");
1968 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
1969 let label = text
1970 .lines()
1971 .find(|line| line.starts_with(".Lstr"))
1972 .unwrap_or_else(|| panic!("a label for the literal in\n{text}"));
1973 assert!(!text.contains(&format!(".globl\t{}", label.trim_end_matches(':'))), "{text}");
1974 }
1975
1976 #[test]
1978 fn an_address_in_an_initializer_is_left_to_the_linker() {
1979 let source = "int counter;\nint *p = &counter;\n";
1980 let text = asm(source);
1981 assert!(text.contains("\np:\n\t.quad\tcounter\n"), "{text}");
1982 let bytes = obj(source);
1985 assert!(bytes.windows(8).any(|w| w == b"counter\0"), "the object has to name it");
1986 }
1987
1988 #[test]
1997 fn a_constant_holding_an_address_goes_in_the_section_the_loader_may_write_once() {
1998 let text = asm("static void a(void) {}\nstatic void b(void) {}\n\
2001 struct m { void (*x)(void); void (*y)(void); };\n\
2002 const struct m t = { a, b };\n");
2003 assert!(text.contains("\t.section\t.data.rel.ro.local,\"aw\",@progbits\n"), "{text}");
2004 assert!(text.contains("\nt:\n\t.quad\ta\n\t.quad\tb\n"), "{text}");
2005
2006 let text =
2009 asm("void a(void);\nstruct m { void (*x)(void); };\nconst struct m t = { a };\n");
2010 assert!(text.contains("\t.section\t.data.rel.ro,\"aw\",@progbits\n"), "{text}");
2011
2012 let text = asm("const int fixed = 7;\n");
2014 assert!(text.contains("\t.section\t.rodata\n"), "{text}");
2015 }
2016
2017 #[test]
2019 fn a_thread_local_variable_is_reported_as_work_that_is_not_done() {
2020 let mut opts = options();
2021 opts.emit = EmitKind::Asm;
2022 let result = run(&opts, "_Thread_local int x = 1;\n");
2023 assert!(result.failed(), "every thread sharing one variable is worse than a message");
2024 assert!(result.messages.iter().any(|m| m.contains("thread-local")), "{:?}", result);
2025 assert!(!result.messages.iter().any(|m| m.contains("internal")), "{:?}", result);
2027 }
2028
2029 #[test]
2031 fn the_object_and_the_listing_are_two_spellings_of_one_compilation() {
2032 let source = "int callee(void); int g(void) { return callee(); }\n";
2036 let bytes = obj(source);
2037 assert!(
2038 bytes.windows(7).any(|w| w == b"callee\0"),
2039 "the object has to name the callee for the linker to find it"
2040 );
2041 let text = asm(source);
2042 assert!(text.contains("\tcall\tcallee\n"), "{text}");
2043 }
2044
2045 #[test]
2051 fn compiling_for_an_executable_produces_an_object_and_not_a_dump() {
2052 let mut opts = options();
2053 opts.emit = EmitKind::Executable;
2055 let result = run(&opts, "int main(void) { return 0; }\n");
2056 assert_eq!(result.messages, Vec::<String>::new());
2057 match result.artifact {
2058 Artifact::Object(bytes) => assert_eq!(&bytes[..4], b"\x7fELF"),
2059 other => panic!("expected an object, got {other:?}"),
2060 }
2061 }
2062
2063 #[test]
2065 fn a_platform_with_no_object_writer_is_said_so_rather_than_written_as_elf() {
2066 let mut opts = options();
2067 opts.emit = EmitKind::Object;
2068 opts.target = "x86_64-apple-darwin".parse::<Triple>().unwrap();
2069 let result = run(&opts, "int f(void) { return 0; }\n");
2070 assert!(result.failed(), "an object nobody can read is worse than a message");
2071 assert!(
2072 result.messages.iter().any(|m| m.contains("no object writer")),
2073 "{:?}",
2074 result.messages
2075 );
2076 }
2077
2078 fn ir(source: &str) -> String {
2080 let mut opts = options();
2081 opts.emit = EmitKind::Ir;
2082 let result = run(&opts, source);
2083 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2084 result.text().to_owned()
2085 }
2086
2087 fn errors(source: &str) -> Vec<String> {
2089 let mut opts = options();
2090 opts.emit = EmitKind::Ir;
2091 let result = run(&opts, source);
2092 assert!(result.failed(), "expected this to be refused:\n{source}");
2093 result.messages
2094 }
2095
2096 fn body(source: &str) -> String {
2098 let text = ir(source);
2099 let (_, rest) = text.split_once("{\n").expect("a function definition");
2100 let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
2101 body.to_owned()
2102 }
2103
2104 #[test]
2112 fn gnu89_inline_is_what_decides_whether_a_bare_inline_definition_reaches_the_module() {
2113 let source = "inline int f(int x) { return x + 1; }\n";
2114 let with = |flag: bool| {
2115 let mut opts = options();
2116 opts.emit = EmitKind::Ir;
2117 opts.gnu89_inline = flag;
2118 let result = run(&opts, source);
2119 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile");
2120 result.text().to_owned()
2121 };
2122
2123 assert!(!with(false).contains("block0"), "no body: {}", with(false));
2126
2127 assert!(with(true).contains("block0"), "a body: {}", with(true));
2130 }
2131
2132 fn safe_ir(tier: rucc_session::Safety, source: &str) -> String {
2134 let mut opts = options();
2135 opts.emit = EmitKind::Ir;
2136 opts.safety = tier;
2137 let result = run(&opts, source);
2138 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2139 result.text().to_owned()
2140 }
2141
2142 const READS_THROUGH_A_POINTER: &str = "int read(int *p) { return p[1]; }\n";
2143
2144 #[test]
2145 fn a_build_that_did_not_ask_for_the_monitor_is_compiled_the_way_it_always_was() {
2146 let text = ir(READS_THROUGH_A_POINTER);
2150 assert!(!text.contains("check_"), "{text}");
2151 assert!(!text.contains("cap_of"), "{text}");
2152 }
2153
2154 #[test]
2155 fn asking_for_a_tier_puts_the_checks_in_before_the_optimizer_sees_them() {
2156 let text = safe_ir(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2157 assert!(text.contains("cap_of"), "{text}");
2158 assert!(text.contains("check_bounds"), "{text}");
2159 assert!(text.contains("check_live"), "{text}");
2160 assert!(text.contains("check_deriv"), "{text}");
2162 }
2163
2164 #[test]
2165 fn the_three_tiers_that_are_not_off_all_check_the_same_accesses_so_far() {
2166 let detect = safe_ir(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2170 for tier in [rucc_session::Safety::Enforce, rucc_session::Safety::Kernel] {
2171 assert_eq!(safe_ir(tier, READS_THROUGH_A_POINTER), detect, "{tier}");
2172 }
2173 }
2174
2175 fn summary(tier: rucc_session::Safety, source: &str) -> String {
2177 let mut opts = options();
2178 opts.emit = EmitKind::SafetySummary;
2179 opts.safety = tier;
2180 let result = run(&opts, source);
2181 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2182 result.text().to_owned()
2183 }
2184
2185 #[test]
2186 fn the_summary_counts_the_checks_that_went_in_and_the_ones_still_standing() {
2187 let text = summary(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2188 assert!(text.contains("\"tier\": \"detect\""), "{text}");
2189 assert!(
2191 text.contains("\"bounds\": { \"emitted\": 1, \"remaining\": 1, \"discharged\": 0 }"),
2192 "{text}"
2193 );
2194 assert!(
2195 text.contains(
2196 "\"derivation\": { \"emitted\": 1, \"remaining\": 1, \"discharged\": 0 }"
2197 ),
2198 "{text}"
2199 );
2200 }
2201
2202 #[test]
2203 fn a_build_without_the_monitor_summarises_as_a_build_with_no_checks_in_it() {
2204 let text = summary(rucc_session::Safety::Off, READS_THROUGH_A_POINTER);
2208 assert!(text.contains("\"tier\": \"off\""), "{text}");
2209 assert!(
2210 text.contains("\"bounds\": { \"emitted\": 0, \"remaining\": 0, \"discharged\": 0 }"),
2211 "{text}"
2212 );
2213 }
2214
2215 #[test]
2216 fn a_call_the_boundary_models_is_counted_apart_from_one_it_does_not() {
2217 let text = summary(
2218 rucc_session::Safety::Detect,
2219 "void *memcpy(void *, const void *, unsigned long);\n\
2220 int puts(const char *);\n\
2221 void f(char *d, char *s) { memcpy(d, s, 4); puts(d); }\n",
2222 );
2223 assert!(text.contains("\"interposed\": 1"), "{text}");
2224 assert!(text.contains("\"puts\""), "{text}");
2225 assert!(!text.contains("__rucc_wrap_memcpy\""), "{text}");
2229 }
2230
2231 #[test]
2232 fn the_two_directions_a_pointer_crosses_the_boundary_are_counted_apart() {
2233 let text = summary(
2237 rucc_session::Safety::Detect,
2238 "void *notes_open(void);\n\
2239 char *f(char *p) { char *q = notes_open(); return q ? q : p; }\n",
2240 );
2241 assert!(text.contains("\"crossings\": { \"entered\": 1, \"returned\": 1 }"), "{text}");
2242 assert!(text.contains("\"notes_open\""), "{text}");
2243 }
2244
2245 #[test]
2246 fn a_static_function_nobody_takes_the_address_of_is_not_a_crossing() {
2247 let text = summary(
2250 rucc_session::Safety::Detect,
2251 "static int len(const char *p) { return p ? 1 : 0; }\n\
2252 int f(void) { return len(\"x\"); }\n",
2253 );
2254 assert!(text.contains("\"crossings\": { \"entered\": 0, \"returned\": 0 }"), "{text}");
2255 }
2256
2257 fn granules(source: &str) -> String {
2259 let mut opts = options();
2260 opts.emit = EmitKind::TypeGranules;
2261 let result = run(&opts, source);
2262 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2263 result.text().to_owned()
2264 }
2265
2266 #[test]
2267 fn the_granule_report_names_every_record_and_both_keyings() {
2268 let text = granules(
2269 "struct hot { char *p; int a; int b; };\n\
2270 int f(struct hot *h) { return h->a; }\n",
2271 );
2272 assert!(text.contains("struct hot"), "{text}");
2273 assert!(text.contains("every type distinct"), "{text}");
2276 assert!(text.contains("every pointer one type"), "{text}");
2277 assert!(text.contains("budget"), "{text}");
2278 }
2279
2280 #[test]
2281 fn a_record_nothing_uses_is_still_measured() {
2282 let text = granules("struct unused { long a; double b; };\nint f(void) { return 0; }\n");
2285 assert!(text.contains("struct unused"), "{text}");
2286 }
2287
2288 #[test]
2289 fn the_granule_report_stops_before_anything_is_lowered() {
2290 let text = granules(
2294 "struct wide { long double d; };\n\
2295 long double f(long double x) { return x * x; }\n",
2296 );
2297 assert!(text.contains("struct wide"), "{text}");
2298 }
2299
2300 #[test]
2301 fn a_witness_reaches_the_assembler_as_a_call_to_the_runtime() {
2302 let text = safe_asm(rucc_session::Safety::Detect, "char *f(char *p) { return p; }\n");
2305 assert!(text.contains("\tcall\t__rucc_cap_witness\n"), "{text}");
2306 }
2307
2308 #[test]
2309 fn a_pointer_turned_into_an_integer_is_on_the_trust_set() {
2310 let text = summary(
2311 rucc_session::Safety::Detect,
2312 "unsigned long f(int *p) { return (unsigned long) p; }\n",
2313 );
2314 assert!(text.contains("\"exposed\": 1"), "{text}");
2315 }
2316
2317 fn safe_asm(tier: rucc_session::Safety, source: &str) -> String {
2319 let mut opts = options();
2320 opts.emit = EmitKind::Asm;
2321 opts.safety = tier;
2322 let result = run(&opts, source);
2323 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
2324 result.text().to_owned()
2325 }
2326
2327 #[test]
2328 fn a_check_reaches_the_assembler_as_a_call_to_the_runtime() {
2329 let text = safe_asm(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2330 assert!(text.contains("\tcall\t__rucc_check_bounds\n"), "{text}");
2331 assert!(text.contains("\tcall\t__rucc_check_live\n"), "{text}");
2332 assert!(text.contains("\tcall\t__rucc_check_deriv\n"), "{text}");
2333 }
2334
2335 #[test]
2336 fn every_check_that_reached_the_assembler_has_a_row_describing_it() {
2337 let text = safe_asm(rucc_session::Safety::Detect, READS_THROUGH_A_POINTER);
2341 let section = format!("\t.section\t{},", rucc_safety::SECTION);
2342 assert_eq!(text.matches(§ion).count(), 3, "{text}");
2343 for index in 0..3 {
2344 let name = format!("__rucc_safety_desc_{index}");
2345 assert!(text.contains(&format!("{name}:\n")), "{text}");
2348 assert!(text.contains(&format!("{name}(%rip)")), "{text}");
2349 }
2350 assert!(!text.contains("__rucc_safety_desc_3"), "{text}");
2351 }
2352
2353 #[test]
2361 fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
2362 let text = ir(concat!(
2363 "int g;\n",
2364 "int a = __builtin_constant_p(1);\n",
2365 "int b = __builtin_constant_p(g);\n",
2366 "int c = __builtin_constant_p(\"abc\");\n",
2367 "int d = __builtin_constant_p(&g);\n",
2368 "int e = __builtin_constant_p(1.5);\n",
2369 "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
2370 ));
2371 assert!(text.contains("global @a : i32 = 1,"), "{text}");
2372 assert!(text.contains("global @b : i32 = 0,"), "{text}");
2373 assert!(text.contains("global @c : i32 = 1,"), "{text}");
2374 assert!(text.contains("global @d : i32 = 0,"), "{text}");
2375 assert!(text.contains("global @e : i32 = 1,"), "{text}");
2376 assert!(text.contains("global @h : i32 = 11,"), "{text}");
2377 assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
2378
2379 let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
2383 assert_eq!(text, "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 0\n return %0\n");
2384 }
2385
2386 #[test]
2395 fn a_call_to_a_library_builtin_reaches_the_library_function() {
2396 let text = body("void f(void) { __builtin_abort(); }\n");
2397 assert_eq!(text, "block0:\n call @abort() : ()\n return\n");
2398
2399 let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
2402 assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
2403 assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
2404 assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
2405 }
2406
2407 #[test]
2418 fn the_absolute_value_family_is_the_magnitude_and_not_a_call() {
2419 let text = body(concat!(
2420 "long long llabs(long long);\n",
2421 "long long f(long long x) { return llabs(x); }\n",
2422 ));
2423 assert!(text.contains("%1 = iconst.i64 63"), "{text}");
2424 assert!(text.contains("%2 = ashr %0, %1"), "{text}");
2425 assert!(text.contains("%3 = xor %0, %2"), "{text}");
2426 assert!(text.contains("%4 = sub %3, %2"), "{text}");
2427 assert!(!text.contains("call"), "the call does not happen:\n{text}");
2428
2429 let text = body("int abs(int);\nint f(int x) { return abs(x); }\n");
2432 assert!(text.contains("iconst.i32 31"), "{text}");
2433 let text = body("long labs(long);\nlong f(long x) { return labs(x); }\n");
2434 assert!(text.contains("iconst.i64 63"), "{text}");
2435
2436 let text = body("long long f(long long x) { return __builtin_llabs(x); }\n");
2439 assert!(!text.contains("call"), "{text}");
2440
2441 let text = ir(concat!(
2443 "long long llabs(long long b);\n",
2444 "long long g(long long x) { return llabs(x); }\n",
2445 "long long llabs(long long b) { return 7; }\n",
2446 ));
2447 assert!(!text.contains("call @llabs"), "{text}");
2448 }
2449
2450 #[test]
2457 fn a_byte_swap_is_arithmetic_and_not_a_call() {
2458 let text = body("unsigned f(unsigned x) { return __builtin_bswap32(x); }\n");
2459 assert_eq!(text, "block0(%0: i32):\n %1 = bswap %0\n return %1\n");
2460
2461 let text = body("unsigned f(unsigned char c) { return __builtin_bswap32(c); }\n");
2464 assert!(text.contains("zext.i32 %0"), "widened first: {text}");
2465 assert!(text.contains("bswap %1"), "and swapped at four bytes: {text}");
2466 }
2467
2468 #[test]
2474 fn the_byte_swaps_reverse_at_the_width_their_name_says() {
2475 for (name, ty, width) in [
2476 ("__builtin_bswap16", "unsigned short", "i16"),
2477 ("__builtin_bswap32", "unsigned", "i32"),
2478 ("__builtin_bswap64", "unsigned long long", "i64"),
2479 ] {
2480 let source = format!("{ty} f({ty} x) {{ return {name}(x); }}\n");
2481 let text = body(&source);
2482 assert_eq!(
2483 text,
2484 format!("block0(%0: {width}):\n %1 = bswap %0\n return %1\n"),
2485 "{name}"
2486 );
2487 }
2488 }
2489
2490 #[test]
2497 fn the_bit_counts_are_instructions_and_not_calls() {
2498 let text = body("int f(unsigned x) { return __builtin_clz(x); }\n");
2499 assert_eq!(text, "block0(%0: i32):\n %1 = ctlz %0\n return %1\n");
2500
2501 let text = body("int f(unsigned x) { return __builtin_ctz(x); }\n");
2502 assert_eq!(text, "block0(%0: i32):\n %1 = cttz %0\n return %1\n");
2503
2504 let text = body("int f(unsigned x) { return __builtin_popcount(x); }\n");
2505 assert_eq!(text, "block0(%0: i32):\n %1 = ctpop %0\n return %1\n");
2506 }
2507
2508 #[test]
2517 fn the_bit_counts_ask_about_the_width_their_name_says() {
2518 let text = body("int f(unsigned long long x) { return __builtin_clzll(x); }\n");
2519 assert!(text.starts_with("block0(%0: i64):"), "counted at eight bytes: {text}");
2520 assert!(text.contains("%1 = ctlz %0"), "{text}");
2521 assert!(text.contains("trunc.i32 %1"), "and answered in an int: {text}");
2522
2523 let text = body("int f(unsigned long long x) { return __builtin_clz(x); }\n");
2526 assert!(text.contains("trunc.i32 %0"), "narrowed to what was asked about: {text}");
2527 assert!(text.contains("ctlz %1"), "and counted there: {text}");
2528
2529 let text = body("int f(unsigned long x) { return __builtin_popcountl(x); }\n");
2530 assert!(text.contains("%1 = ctpop %0"), "{text}");
2531 assert!(!text.contains("call"), "{text}");
2532 }
2533
2534 #[test]
2539 fn a_parity_is_the_low_bit_of_the_set_bit_count() {
2540 let text = body("int f(unsigned x) { return __builtin_parity(x); }\n");
2541 assert!(text.contains("%1 = ctpop %0"), "{text}");
2542 assert!(text.contains("iconst.i32 1"), "{text}");
2543 assert!(text.contains("and %1, %2"), "the low bit of it: {text}");
2544 }
2545
2546 #[test]
2552 fn the_first_set_bit_is_one_based_and_zero_for_a_zero() {
2553 let text = body("int f(int x) { return __builtin_ffs(x); }\n");
2554 assert!(text.contains("%1 = cttz %0"), "{text}");
2555 assert!(text.contains("%4 = add %1, %2"), "one more than the count: {text}");
2556 assert!(text.contains("%5 = icmp ne %0, %3"), "whether there was a bit at all: {text}");
2557 assert!(text.contains("%7 = sub %3, %6"), "spread to a mask: {text}");
2558 assert!(text.contains("%8 = and %4, %7"), "and kept only then: {text}");
2559 assert!(!text.contains("br_if"), "no branch: {text}");
2560 }
2561
2562 #[test]
2572 fn an_overflow_check_is_arithmetic_and_not_a_call() {
2573 let text =
2574 body("int f(int a, int b, int *r) { return __builtin_add_overflow(a, b, r); }\n");
2575 assert!(text.contains("%3, %4 = sadd_overflow.(i32, i1) %0, %1"), "{text}");
2576 assert!(text.contains("store %3 -> %2"), "{text}");
2577 assert!(!text.contains("call"), "{text}");
2578
2579 let text =
2580 body("int f(int a, int b, int *r) { return __builtin_sub_overflow(a, b, r); }\n");
2581 assert!(text.contains("ssub_overflow.(i32, i1) %0, %1"), "{text}");
2582
2583 let text =
2584 body("int f(int a, int b, int *r) { return __builtin_mul_overflow(a, b, r); }\n");
2585 assert!(text.contains("smul_overflow.(i32, i1) %0, %1"), "{text}");
2586
2587 let text = body(
2590 "int f(unsigned a, unsigned b, unsigned *r) { return __builtin_add_overflow(a, b, r); }\n",
2591 );
2592 assert!(text.contains("uadd_overflow.(i32, i1) %0, %1"), "{text}");
2593 }
2594
2595 #[test]
2603 fn an_overflow_check_is_done_at_a_type_that_holds_every_operand() {
2604 let text = body(
2605 "int f(unsigned a, int b, long long *r) { return __builtin_add_overflow(a, b, r); }\n",
2606 );
2607 assert!(text.contains("%3 = zext.i64 %0"), "the unsigned operand keeps its value: {text}");
2608 assert!(text.contains("%4 = sext.i64 %1"), "and so does the signed one: {text}");
2609 assert!(text.contains("sadd_overflow.(i64, i1) %3, %4"), "{text}");
2610
2611 let text = body(
2614 "int f(long long a, long long b, long long *r) { return __builtin_mul_overflow(a, b, r); }\n",
2615 );
2616 assert!(text.contains("smul_overflow.(i64, i1) %0, %1"), "{text}");
2617 assert!(!text.contains("sext."), "{text}");
2618 assert!(!text.contains("zext.i64"), "{text}");
2620 }
2621
2622 #[test]
2630 fn an_overflow_check_writes_the_wrapped_answer_whether_or_not_it_fit() {
2631 let text =
2632 body("int f(int a, int b, char *r) { return __builtin_sub_overflow(a, b, r); }\n");
2633 assert!(text.contains("%3, %4 = ssub_overflow.(i32, i1) %0, %1"), "{text}");
2634 assert!(text.contains("%5 = trunc.i8 %3"), "narrowed to where it goes: {text}");
2635 assert!(text.contains("%6 = sext.i32 %5"), "and back: {text}");
2636 assert!(text.contains("%7 = icmp ne %6, %3"), "which is whether it fit: {text}");
2637 assert!(text.contains("store %5 -> %2"), "the narrowed value is stored either way: {text}");
2638 assert!(text.contains("%8 = or %4, %7"), "and either bit is an overflow: {text}");
2639 }
2640
2641 #[test]
2648 fn a_call_needing_more_than_sixty_four_bits_says_so() {
2649 let refused = concat!(
2650 "int f(unsigned long long a, long long b, long long *r) {\n",
2651 " return __builtin_add_overflow(a, b, r);\n",
2652 "}\n",
2653 );
2654 let messages = errors(refused);
2655 assert_eq!(messages.len(), 1, "{messages:?}");
2656 assert!(messages[0].contains("E0694"), "{messages:?}");
2657 assert!(messages[0].contains("wider than 64 bits"), "{messages:?}");
2658 }
2659
2660 #[test]
2663 fn an_overflow_check_over_something_that_is_not_an_integer_says_so() {
2664 let messages =
2665 errors("int f(double a, int b, int *r) { return __builtin_add_overflow(a, b, r); }\n");
2666 assert!(messages.iter().any(|line| line.contains("E0671")), "{messages:?}");
2667
2668 let messages =
2669 errors("int f(int a, int b, double *r) { return __builtin_add_overflow(a, b, r); }\n");
2670 assert!(messages.iter().any(|line| line.contains("E0671")), "{messages:?}");
2671 }
2672
2673 #[test]
2684 fn an_ordered_access_is_ordered_in_the_ir() {
2685 let text = body("int f(int *p) { return __atomic_load_n(p, 0); }\n");
2686 assert!(text.contains("atomic_load.i32 %0, align 4, relaxed"), "{text}");
2687
2688 let text = body("long f(long *p) { return __atomic_load_n(p, 2); }\n");
2689 assert!(text.contains("atomic_load.i64 %0, align 8, acquire"), "{text}");
2690
2691 let text = body("void f(int *p, int v) { __atomic_store_n(p, v, 3); }\n");
2692 assert!(text.contains("atomic_store %1 -> %0, align 4, release"), "{text}");
2693
2694 let text = body("void f(int *p, int v) { __atomic_store_n(p, v, 5); }\n");
2695 assert!(text.contains("atomic_store %1 -> %0, align 4, seq_cst"), "{text}");
2696
2697 let text = body("void f(char *p, int v) { __atomic_store_n(p, v, 0); }\n");
2700 assert!(text.contains("trunc.i8 %1"), "{text}");
2701 assert!(text.contains("atomic_store %2 -> %0, align 1, relaxed"), "{text}");
2702 }
2703
2704 #[test]
2713 fn an_ordered_access_is_the_plain_instruction_on_this_machine() {
2714 let text = asm("int f(int *p) { return __atomic_load_n(p, 5); }\n");
2715 assert!(text.contains("movl\t(%rdi), %eax"), "{text}");
2716 assert!(!text.contains("mfence"), "a load needs no barrier here: {text}");
2717
2718 let text = asm("void f(int *p, int v) { __atomic_store_n(p, v, 3); }\n");
2719 assert!(text.contains("movl\t%esi, (%rdi)"), "{text}");
2720 assert!(!text.contains("mfence"), "a release store needs no barrier here: {text}");
2721
2722 let text = asm("void f(int *p, int v) { __atomic_store_n(p, v, 5); }\n");
2723 let (before, after) = text.split_once("mfence").expect("a barrier: {text}");
2724 assert!(before.contains("movl\t%esi, (%rdi)"), "the store comes first: {text}");
2725 assert!(!after.contains("movl"), "and nothing else is between them: {text}");
2726 }
2727
2728 #[test]
2738 fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
2739 assert!(asm("void f(void) { __atomic_thread_fence(5); }\n").contains("mfence"));
2740 assert!(asm("void f(void) { __sync_synchronize(); }\n").contains("mfence"));
2741
2742 for weaker in ["1", "2", "3", "4"] {
2743 let source = format!("void f(void) {{ __atomic_thread_fence({weaker}); }}\n");
2744 assert!(!asm(&source).contains("mfence"), "{weaker} costs nothing here");
2745 }
2746 }
2747
2748 #[test]
2760 fn the_lock_free_questions_are_answered_as_constants() {
2761 for size in ["1", "2", "4", "8"] {
2762 let source =
2763 format!("int f(void) {{ return __atomic_always_lock_free({size}, 0); }}\n");
2764 let text = asm(&source);
2765 assert!(text.contains("movb\t$1, %al"), "{size} bytes is lock free: {text}");
2766 assert!(!text.contains("call"), "and is not a call: {text}");
2767 }
2768 for size in ["3", "16", "sizeof(long double)"] {
2769 let source = format!("int f(void) {{ return __atomic_is_lock_free({size}, 0); }}\n");
2770 let text = asm(&source);
2771 assert!(text.contains("movb\t$0, %al"), "{size} bytes is not: {text}");
2772 assert!(!text.contains("call"), "and is not a call either: {text}");
2773 }
2774
2775 let text = asm("int f(int n) { return __atomic_is_lock_free(n, 0); }\n");
2779 assert!(text.contains("movb\t$0, %al"), "a size nobody knows is not lock free: {text}");
2780 let text = asm("int f(int *p) { return __atomic_always_lock_free(8, p); }\n");
2781 assert!(text.contains("movb\t$0, %al"), "eight bytes at four is not: {text}");
2782 let text = asm("int f(long *p) { return __atomic_always_lock_free(8, p); }\n");
2783 assert!(text.contains("movb\t$1, %al"), "and at eight it is: {text}");
2784 }
2785
2786 #[test]
2798 fn a_memory_order_an_operation_cannot_carry_is_read_as_the_strongest() {
2799 let mut opts = options();
2800 opts.emit = EmitKind::Ir;
2801
2802 let acquire_store = run(&opts, "void f(int *p, int v) { __atomic_store_n(p, v, 2); }\n");
2803 assert!(acquire_store.text().contains("seq_cst"), "{:?}", acquire_store.text());
2804 assert!(acquire_store.messages[0].contains("[W0333]"), "{:?}", acquire_store.messages);
2805
2806 let nonsense = run(&opts, "int f(int *p) { return __atomic_load_n(p, 99); }\n");
2807 assert!(nonsense.text().contains("seq_cst"), "{:?}", nonsense.text());
2808 assert!(nonsense.messages[0].contains("[W0333]"), "{:?}", nonsense.messages);
2809
2810 let computed = run(&opts, "int f(int *p, int n) { return __atomic_load_n(p, n); }\n");
2811 assert!(computed.text().contains("seq_cst"), "{:?}", computed.text());
2812 assert_eq!(computed.messages, Vec::<String>::new(), "a computed order is not a mistake");
2813 }
2814
2815 #[test]
2827 fn a_conversion_between_a_float_and_the_widest_unsigned_integer_is_written_without_a_branch() {
2828 let text = asm("double f(unsigned long long x) { return (double)x; }\n");
2829 assert!(text.contains("cvtsi2sdq"), "the signed conversion is what runs: {text}");
2830 assert!(text.contains("shrq"), "with the value halved first: {text}");
2831 assert!(text.contains("addsd"), "and doubled after: {text}");
2832 assert!(!text.contains("\tj"), "and no branch anywhere: {text}");
2833
2834 let text = asm("unsigned long long f(double d) { return (unsigned long long)d; }\n");
2835 assert!(text.contains("cvttsd2siq"), "the signed conversion is what runs: {text}");
2836 assert!(text.contains("subsd"), "with half the range taken off first: {text}");
2837 assert!(text.contains("shlq\t$63"), "and the top bit put back: {text}");
2838 assert!(!text.contains("\tj"), "and no branch anywhere: {text}");
2839 }
2840
2841 #[test]
2852 fn a_plain_name_the_program_took_is_the_programs_own_function() {
2853 let taken = concat!(
2854 "static long long llabs(long long b) { return 7; }\n",
2855 "long long f(long long x) { return llabs(x); }\n",
2856 );
2857 assert!(ir(taken).contains("call @llabs"), "a static definition is the program's own");
2858
2859 let retyped = concat!("int llabs(int b);\n", "int f(int x) { return llabs(x); }\n",);
2860 assert!(ir(retyped).contains("call @llabs"), "another type is another function");
2861
2862 let plain = concat!(
2863 "long long llabs(long long b);\n",
2864 "long long f(long long x) { return llabs(x); }\n",
2865 );
2866 let mut opts = options();
2867 opts.emit = EmitKind::Ir;
2868 assert!(!run(&opts, plain).text().contains("call @llabs"), "the library's by default");
2869
2870 opts.builtins = false;
2871 assert!(run(&opts, plain).text().contains("call @llabs"), "-fno-builtin");
2872
2873 opts.builtins = true;
2874 opts.no_builtin = vec!["llabs".to_owned()];
2875 assert!(run(&opts, plain).text().contains("call @llabs"), "-fno-builtin-llabs");
2876 let one = "long labs(long b);\nlong f(long x) { return labs(x); }\n";
2877 assert!(!run(&opts, one).text().contains("call @labs"), "one name and not the family");
2878
2879 opts.no_builtin = Vec::new();
2882 opts.builtins = false;
2883 let prefixed = "long long f(long long x) { return __builtin_llabs(x); }\n";
2884 assert!(!run(&opts, prefixed).text().contains("call @llabs"), "the prefix is a promise");
2885 }
2886
2887 #[test]
2900 fn the_hint_builtins_are_their_first_argument_and_the_hint_leaves_no_trace() {
2901 let text = ir(concat!(
2902 "long a = __builtin_expect(7, 1);\n",
2903 "long b = __builtin_expect_with_probability(9, 1, 0.9);\n",
2904 "unsigned long c = sizeof(__builtin_expect((char)1, 1));\n",
2905 ));
2906 assert!(text.contains("global @a : i64 = 7,"), "{text}");
2907 assert!(text.contains("global @b : i64 = 9,"), "{text}");
2908 assert!(text.contains("global @c : i64 = 8,"), "{text}");
2909 assert!(!text.contains("__builtin_expect"), "it is not a call to anything:\n{text}");
2910
2911 let text = body("long f(char c) { return __builtin_expect(c, 1); }\n");
2914 assert!(text.contains("sext"), "{text}");
2915
2916 let one = "block0:\n %0 = iconst.i32 0\n %1 = iconst.i32 1\n %2 = sext.i64 %1\n return %0\n";
2920 assert_eq!(body("int f(void) { int i = 0; __builtin_expect(1, i++); return i; }\n"), one);
2921 let source = "int g(void) { int i = 0; __builtin_expect_with_probability(1, i++, 0.5); return i; }\n";
2922 assert_eq!(body(source), one);
2923
2924 let kept = body("int f(int n) { int i = 0; __builtin_expect(n, i++); return i; }\n");
2929 assert!(kept.contains("add.nsw"), "the hint still runs: {kept}");
2930 assert!(kept.ends_with("return %3\n"), "and the answer is what it left behind: {kept}");
2931 let both = "int g(int n) { int i = 0; __builtin_expect_with_probability(n, i++, 0.5); return i; }\n";
2932 assert!(body(both).contains("add.nsw"), "and so does the one with three arguments");
2933 }
2934
2935 #[test]
2947 fn a_promise_that_control_does_not_arrive_writes_no_instruction() {
2948 let promised = "int f(int x) { if (x) return 1; __builtin_unreachable(); }\n";
2949 let text = ir(promised);
2950 assert!(text.contains(" unreachable_hint\n"), "{text}");
2951 assert!(!text.contains("call"), "it is not a call to anything:\n{text}");
2952
2953 let after = body("int g(int x) { __builtin_unreachable(); return x; }\n");
2957 assert!(after.contains("return"), "{after}");
2958
2959 let text = asm(promised);
2962 let mine = text.split_once("\nf:\n").expect("a definition").1;
2963 let mine = mine.split_once("\t.size").expect("a definition").0;
2964 let plain = asm("int f(int x) { if (x) return 1; }\n");
2965 let plain = plain.split_once("\nf:\n").expect("a definition").1;
2966 let plain = plain.split_once("\t.size").expect("a definition").0;
2967 assert_eq!(mine, plain);
2968 assert!(mine.trim_end().ends_with("ret"), "{mine}");
2969 assert!(!mine.contains("ud2"), "{mine}");
2970 }
2971
2972 #[test]
2979 fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
2980 let mut opts = options();
2981 opts.emit = EmitKind::Ir;
2982 let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
2983 assert!(
2984 messages.iter().any(|m| m.contains("__builtin_abort")),
2985 "expected the written name in {messages:?}"
2986 );
2987 }
2988
2989 #[test]
2997 fn a_builtin_nothing_lowers_is_refused_by_name() {
2998 let mut opts = options();
2999 opts.emit = EmitKind::Ir;
3000 for (builtin, call) in [
3001 ("__builtin_return_address", "(int)(long)__builtin_return_address(0)"),
3002 ("__builtin_alloca", "(int)(long)__builtin_alloca(8)"),
3003 ("__atomic_exchange_n", "__atomic_exchange_n(&counter, 1, 0)"),
3004 ("__sync_fetch_and_add", "(int)__sync_fetch_and_add(&counter, 1)"),
3005 ] {
3006 let source = format!("int counter;\nint f(void) {{ return {call}; }}\n");
3007 let messages = run(&opts, &source).messages;
3008 let named = messages.iter().any(|m| m.contains(builtin) && m.contains("E0686"));
3009 assert!(named, "expected {builtin} to be refused by name in {messages:?}");
3010 }
3011 }
3012
3013 #[test]
3021 fn what_is_refused_is_the_call_and_not_the_name() {
3022 let text = ir("unsigned long n = sizeof(__builtin_return_address(0));\n");
3023 assert!(text.contains("global @n : i64 = 8,"), "{text}");
3024
3025 let text = ir(concat!(
3026 "void *__builtin_return_address(unsigned x) { return 0; }\n",
3027 "void *f(void) { return __builtin_return_address(0); }\n",
3028 ));
3029 assert!(text.contains("call @__builtin_return_address"), "{text}");
3030 }
3031
3032 #[test]
3037 fn a_static_function_nothing_refers_to_is_not_emitted() {
3038 let text = ir("static int dropped(void) { return 1; }\n\
3039 static int kept(void) { return 2; }\n\
3040 int main(void) { return kept(); }\n");
3041 assert!(text.contains("func @kept"), "{text}");
3042 assert!(!text.contains("dropped"), "{text}");
3043 }
3044
3045 #[test]
3051 fn two_static_functions_that_only_call_each_other_are_both_dropped() {
3052 let text = ir("static int ping(void);\n\
3053 static int pong(void) { return ping(); }\n\
3054 static int ping(void) { return pong(); }\n\
3055 int main(void) { return 0; }\n");
3056 assert!(!text.contains("ping"), "{text}");
3057 assert!(!text.contains("pong"), "{text}");
3058 }
3059
3060 #[test]
3066 fn naming_a_static_function_anywhere_keeps_it() {
3067 let text = ir("static int by_address(void) { return 1; }\n\
3068 static int in_an_image(void) { return 2; }\n\
3069 static int deeper(void) { return 3; }\n\
3070 static int reaches_deeper(void) { return deeper(); }\n\
3071 static int (*table[1])(void) = {in_an_image};\n\
3072 int main(void) {\n\
3073 int (*p)(void) = by_address;\n\
3074 return p() + table[0]() + reaches_deeper();\n\
3075 }\n");
3076 for kept in ["by_address", "in_an_image", "deeper", "reaches_deeper"] {
3077 assert!(text.contains(&format!("func @{kept}")), "expected {kept} in:\n{text}");
3078 }
3079 }
3080
3081 #[test]
3087 fn an_attribute_keeps_a_static_function_nothing_refers_to() {
3088 for attribute in ["used", "retain", "constructor", "destructor", "__used__"] {
3089 let source = format!(
3090 "__attribute__(({attribute})) static int kept(void) {{ return 1; }}\n\
3091 int main(void) {{ return 0; }}\n"
3092 );
3093 let text = ir(&source);
3094 assert!(text.contains("func @kept"), "for {attribute}:\n{text}");
3095 }
3096 }
3097
3098 #[test]
3101 fn a_function_anything_could_call_is_emitted_without_being_called() {
3102 let text =
3103 ir("int nobody_here_calls_it(void) { return 1; }\nint main(void) { return 0; }\n");
3104 assert!(text.contains("func @nobody_here_calls_it"), "{text}");
3105 }
3106
3107 #[test]
3114 fn a_classification_c_has_an_operator_for_is_that_operator() {
3115 for (builtin, operator) in [
3116 ("__builtin_isgreater", "binary >"),
3117 ("__builtin_isgreaterequal", "binary >="),
3118 ("__builtin_isless", "binary <"),
3119 ("__builtin_islessequal", "binary <="),
3120 ] {
3121 let source = format!("int f(double x, double y) {{ return {builtin}(x, y); }}\n");
3122 let text = tast(&source);
3123 assert!(text.contains(&format!("{operator} : int")), "for {builtin}:\n{text}");
3124 }
3125 }
3126
3127 #[test]
3136 fn the_classification_builtins_are_comparisons_and_not_calls() {
3137 let text = body("int f(double x, double y) { return __builtin_isunordered(x, y); }\n");
3138 assert_eq!(
3139 text,
3140 "block0(%0: f64, %1: f64):\n %2 = fcmp uno %0, %1\n %3 = zext.i32 \
3141 %2\n return %3\n"
3142 );
3143
3144 let text = body("int f(double x, double y) { return __builtin_islessgreater(x, y); }\n");
3146 assert!(text.contains("fcmp one %0, %1"), "{text}");
3147
3148 let text = body("int f(double x) { return __builtin_isnan(x); }\n");
3149 assert!(text.contains("fcmp uno %0, %0"), "{text}");
3150
3151 let text = body("int f(double x) { return __builtin_isinf(x); }\n");
3152 assert!(text.contains("fconst.f64 0x7ff0000000000000"), "{text}");
3153 assert!(text.contains("fconst.f64 0xfff0000000000000"), "{text}");
3154 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
3155 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
3156 assert!(text.contains("%5 = or %3, %4"), "{text}");
3157
3158 let text = body("int f(double x) { return __builtin_isfinite(x); }\n");
3161 assert!(text.contains("%3 = fcmp olt %2, %0"), "{text}");
3162 assert!(text.contains("%4 = fcmp olt %0, %1"), "{text}");
3163 assert!(text.contains("%5 = and %3, %4"), "{text}");
3164
3165 let text = body("int f(double x) { return __builtin_signbit(x); }\n");
3166 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
3167 assert!(text.contains("icmp slt %1, %2"), "{text}");
3168
3169 let text = body("int f(long double x) { return __builtin_signbitl(x); }\n");
3172 assert!(text.contains("%1 = bitcast.i80 %0"), "{text}");
3173
3174 let text = body("double g(void);\nint f(void) { return __builtin_isnan(g()); }\n");
3177 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
3178 }
3179
3180 #[test]
3187 fn a_classification_spelling_that_names_a_width_converts_before_it_asks() {
3188 let text = ir(concat!(
3189 "int a = __builtin_isinff(1e300);\n",
3190 "int b = __builtin_isinf(1e300);\n",
3191 "int c = __builtin_isnan(0.0);\n",
3195 "int d = __builtin_signbit(-0.0);\n",
3196 "int e = __builtin_islessgreater(1.0, 2.0);\n",
3197 ));
3198 assert!(text.contains("global @a : i32 = 1,"), "{text}");
3199 assert!(text.contains("global @b : i32 = 0,"), "{text}");
3200 assert!(text.contains("global @c : i32 = 0,"), "{text}");
3201 assert!(text.contains("global @d : i32 = 1,"), "{text}");
3202 assert!(text.contains("global @e : i32 = 1,"), "{text}");
3203 }
3204
3205 #[test]
3207 fn a_classification_builtin_refuses_an_argument_that_is_not_floating_point() {
3208 let mut opts = options();
3209 opts.emit = EmitKind::Ir;
3210 let source = concat!(
3211 "int a(int x) { return __builtin_isnan(x); }\n",
3212 "int b(int x, int y) { return __builtin_isunordered(x, y); }\n",
3213 "int c(double x) { return __builtin_isnan(x, x); }\n",
3214 );
3215 let messages = run(&opts, source).messages;
3216 assert_eq!(
3217 messages,
3218 [
3219 "/main.c:1:23: error: non-floating-point argument in call to function \
3220 '__builtin_isnan' [E0685]",
3221 "/main.c:2:30: error: non-floating-point arguments in call to function \
3222 '__builtin_isunordered' [E0685]",
3223 "/main.c:3:26: error: too many arguments to function '__builtin_isnan' [E0511]",
3224 ]
3225 );
3226 }
3227
3228 #[test]
3237 fn the_last_three_classification_builtins_are_comparisons_and_not_calls() {
3238 let text = body("int f(double x) { return __builtin_isnormal(x); }\n");
3239 assert!(text.contains("%1 = bitcast.i64 %0"), "{text}");
3243 assert!(text.contains("%2 = iconst.i64 9223372036854775807"), "{text}");
3244 assert!(text.contains("%3 = and %1, %2"), "{text}");
3245 assert!(text.contains("%4 = iconst.i64 4503599627370496"), "{text}");
3246 assert!(text.contains("%5 = iconst.i64 9218868437227405312"), "{text}");
3247 assert!(text.contains("%6 = icmp uge %3, %4"), "{text}");
3248 assert!(text.contains("%7 = icmp ult %3, %5"), "{text}");
3249 assert!(text.contains("%8 = and %6, %7"), "{text}");
3250
3251 let text = body("int f(long double x) { return __builtin_isnormal(x); }\n");
3255 assert!(text.contains("%4 = iconst.i80 27670116110564327424"), "{text}");
3256 assert!(text.contains("%5 = iconst.i80 604453686435277732577280"), "{text}");
3257
3258 let text = body("int f(double x) { return __builtin_isinf_sign(x); }\n");
3259 assert!(text.contains("%3 = fcmp oeq %0, %1"), "{text}");
3260 assert!(text.contains("%4 = fcmp oeq %0, %2"), "{text}");
3261 assert!(text.contains("%7 = sub %5, %6"), "{text}");
3262
3263 let text = body("int f(double x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n");
3264 assert!(text.contains("fcmp uno %0, %0"), "{text}");
3265 assert!(text.contains("fcmp oeq %0, %6"), "{text}");
3266 assert_eq!(text.matches(" = zext.i32 ").count(), 4, "{text}");
3270 assert_eq!(text.matches(" = xor ").count(), 4, "{text}");
3271 assert!(!text.contains("call"), "{text}");
3272
3273 let text = body(concat!(
3276 "double g(void);\n",
3277 "int f(void) { return __builtin_fpclassify(0, 1, 2, 3, 4, g()); }\n",
3278 ));
3279 assert_eq!(text.matches("call @g()").count(), 1, "{text}");
3280 }
3281
3282 #[test]
3289 fn the_last_three_classification_builtins_fold_where_their_operand_is_a_constant() {
3290 let text = ir(concat!(
3291 "int a = __builtin_isnormal(1.0);\n",
3292 "int b = __builtin_isnormal(0.0);\n",
3293 "int c = __builtin_isnormal(1.0 / 0.0);\n",
3294 "int d = __builtin_isinf_sign(-1.0 / 0.0);\n",
3295 "int e = __builtin_isinf_sign(1.0);\n",
3296 "int g = __builtin_fpclassify(0, 1, 2, 3, 4, 0.0);\n",
3297 "int h = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0);\n",
3298 "int i = __builtin_fpclassify(0, 1, 2, 3, 4, 1.0 / 0.0);\n",
3299 ));
3300 assert!(text.contains("global @a : i32 = 1,"), "{text}");
3301 assert!(text.contains("global @b : i32 = 0,"), "{text}");
3302 assert!(text.contains("global @c : i32 = 0,"), "{text}");
3303 assert!(text.contains("global @d : i32 = -1,"), "{text}");
3304 assert!(text.contains("global @e : i32 = 0,"), "{text}");
3305 assert!(text.contains("global @g : i32 = 4,"), "{text}");
3306 assert!(text.contains("global @h : i32 = 2,"), "{text}");
3307 assert!(text.contains("global @i : i32 = 1,"), "{text}");
3308 }
3309
3310 #[test]
3316 fn fpclassify_refuses_an_answer_that_is_not_an_integer_constant() {
3317 let mut opts = options();
3318 opts.emit = EmitKind::Ir;
3319 let source = concat!(
3320 "int a(double x, int n) { return __builtin_fpclassify(0, 1, n, 3, 4, x); }\n",
3321 "int b(double x) { return __builtin_fpclassify(0, 1, 2, 3, x); }\n",
3322 "int c(int x) { return __builtin_fpclassify(0, 1, 2, 3, 4, x); }\n",
3323 );
3324 let messages = run(&opts, source).messages;
3325 assert_eq!(
3326 messages,
3327 [
3328 "/main.c:1:60: error: non-const integer argument 3 in call to function \
3329 '__builtin_fpclassify' [E0687]",
3330 "/main.c:2:26: error: too few arguments to function '__builtin_fpclassify' \
3331 [E0511]",
3332 "/main.c:3:23: error: non-floating-point argument in call to function \
3333 '__builtin_fpclassify' [E0685]",
3334 ]
3335 );
3336 }
3337
3338 #[test]
3346 fn a_builtin_whose_answer_is_a_constant_is_one_and_not_a_call() {
3347 let text = ir(concat!(
3348 "double a = __builtin_inf();\n",
3349 "float b = __builtin_huge_valf();\n",
3350 "long double c = __builtin_infl();\n",
3351 "double d = __builtin_huge_val();\n",
3352 ));
3353 assert!(text.contains("global @a : f64 = 0x7ff0000000000000,"), "{text}");
3354 assert!(text.contains("global @b : f32 = 0x7f800000,"), "{text}");
3355 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
3356 assert!(text.contains("global @d : f64 = 0x7ff0000000000000,"), "{text}");
3357 assert!(!text.contains("call"), "{text}");
3358 }
3359
3360 #[test]
3369 fn a_nan_is_written_with_the_payload_the_program_asked_for() {
3370 let text = ir(concat!(
3371 "double a = __builtin_nan(\"\");\n",
3372 "double b = __builtin_nan(\"0x1\");\n",
3373 "double c = __builtin_nan(\"010\");\n",
3375 "double d = __builtin_nans(\"\");\n",
3376 "double e = __builtin_nans(\"0x1\");\n",
3377 "float f = __builtin_nanf(\"0x1\");\n",
3378 "float g = __builtin_nansf(\"\");\n",
3379 "long double h = __builtin_nansl(\"\");\n",
3380 ));
3381 assert!(text.contains("global @a : f64 = 0x7ff8000000000000,"), "{text}");
3382 assert!(text.contains("global @b : f64 = 0x7ff8000000000001,"), "{text}");
3383 assert!(text.contains("global @c : f64 = 0x7ff8000000000008,"), "{text}");
3384 assert!(text.contains("global @d : f64 = 0x7ff4000000000000,"), "{text}");
3385 assert!(text.contains("global @e : f64 = 0x7ff0000000000001,"), "{text}");
3386 assert!(text.contains("global @f : f32 = 0x7fc00001,"), "{text}");
3387 assert!(text.contains("global @g : f32 = 0x7fa00000,"), "{text}");
3388 assert!(text.contains("f80 0x7fffa000000000000000"), "{text}");
3389
3390 let text = ir(concat!(
3393 "double f(const char *p) { return __builtin_nan(p); }\n",
3394 "double g(void) { return __builtin_nans(\"1x\"); }\n",
3395 ));
3396 assert_eq!(text.matches("call @nan(").count(), 1, "{text}");
3397 assert_eq!(text.matches("call @nans(").count(), 1, "{text}");
3398 }
3399
3400 #[test]
3408 fn the_length_and_the_order_of_a_string_literal_are_known_here() {
3409 let text = ir(concat!(
3410 "unsigned long a = __builtin_strlen(\"hello\");\n",
3411 "unsigned long b = __builtin_strlen(\"a\\0bc\");\n",
3412 "int c = __builtin_strcmp(\"X\", \"X\\376\") < 0;\n",
3413 "int d = __builtin_strcmp(\"abc\", \"abc\");\n",
3414 "int e = __builtin_strcmp(\"abc\", \"ab\") > 0;\n",
3415 ));
3416 assert!(text.contains("global @a : i64 = 5,"), "{text}");
3417 assert!(text.contains("global @b : i64 = 1,"), "{text}");
3418 assert!(text.contains("global @c : i32 = 1,"), "{text}");
3419 assert!(text.contains("global @d : i32 = 0,"), "{text}");
3420 assert!(text.contains("global @e : i32 = 1,"), "{text}");
3421 assert!(!text.contains("call"), "{text}");
3422
3423 let text = ir("unsigned long f(const char *p) { return __builtin_strlen(p); }\n");
3425 assert!(text.contains("call @strlen("), "{text}");
3426 }
3427
3428 #[test]
3435 fn a_sign_builtin_is_a_mask_over_the_bits_and_not_a_call() {
3436 let text = body("double f(double x) { return __builtin_fabs(x); }\n");
3437 assert!(text.contains("bitcast.i64 %0"), "{text}");
3438 assert!(text.contains("iconst.i64 9223372036854775807"), "{text}");
3439 assert!(text.contains("and %1, %2"), "{text}");
3440 assert!(text.contains("bitcast.f64 %3"), "{text}");
3441 assert!(!text.contains("call"), "{text}");
3442
3443 let text = body("double f(double x, double y) { return __builtin_copysign(x, y); }\n");
3444 assert!(text.contains("iconst.i64 -9223372036854775808"), "{text}");
3445 assert!(text.contains("%8 = or %4, %7"), "{text}");
3446 assert!(!text.contains("call"), "{text}");
3447
3448 let text = body("long double f(long double x) { return __builtin_fabsl(x); }\n");
3451 assert!(text.contains("bitcast.i80 %0"), "{text}");
3452 assert!(text.contains("bitcast.f80"), "{text}");
3453
3454 let text = body("double f(float x) { return __builtin_fabs(x); }\n");
3457 assert!(text.contains("fpext.f64 %0"), "{text}");
3458 assert!(text.contains("bitcast.i64 %1"), "{text}");
3459 }
3460
3461 #[test]
3470 fn the_sign_builtins_answer_a_zero_and_a_nan_the_way_the_bits_say() {
3471 let text = ir(concat!(
3472 "double a = __builtin_fabs(-3.5);\n",
3473 "double b = __builtin_copysign(1.0, -0.0);\n",
3474 "double c = __builtin_copysign(0.0, -2.0);\n",
3475 "double d = __builtin_copysign(-__builtin_nan(\"\"), 1.0);\n",
3477 "double e = __builtin_fabs(-__builtin_nan(\"0x1\"));\n",
3478 "float g = __builtin_copysignf(-0.0f, 2.0f);\n",
3479 "long double h = __builtin_copysignl(1.0L, -1.0L);\n",
3480 "long double i = __builtin_fabsl(-__builtin_infl());\n",
3481 ));
3482 assert!(text.contains("global @a : f64 = 0x400c000000000000,"), "{text}");
3483 assert!(text.contains("global @b : f64 = 0xbff0000000000000,"), "{text}");
3484 assert!(text.contains("global @c : f64 = 0x8000000000000000,"), "{text}");
3485 assert!(text.contains("global @d : f64 = 0x7ff8000000000000,"), "{text}");
3486 assert!(text.contains("global @e : f64 = 0x7ff8000000000001,"), "{text}");
3487 assert!(text.contains("global @g : f32 = 0x0,"), "{text}");
3488 assert!(text.contains("f80 0xbfff8000000000000000"), "{text}");
3489 assert!(text.contains("f80 0x7fff8000000000000000"), "{text}");
3490 }
3491
3492 #[test]
3499 fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
3500 let text = ir(concat!(
3501 "constexpr int side = 4;\n",
3502 "constexpr int wider = side + 1;\n",
3503 "constexpr double half = 1.5;\n",
3504 "struct point { int x; int y; };\n",
3505 "constexpr struct point origin = { 5, 6 };\n",
3506 "int square[side * side];\n",
3507 "int rectangle[wider];\n",
3508 "int rounded[(int)half * 2];\n",
3509 "int across[origin.y];\n",
3510 "enum named { four = side };\n",
3511 "int e = four;\n",
3512 ));
3513 assert!(text.contains("global @square : bytes 64 ="), "{text}");
3514 assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
3515 assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
3516 assert!(text.contains("global @across : bytes 24 ="), "{text}");
3517 assert!(text.contains("global @e : i32 = 4,"), "{text}");
3518
3519 let mut opts = options();
3522 opts.emit = EmitKind::Ir;
3523 let konst = "const int n = 1;\nint a[n];\n";
3524 let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
3525 assert_eq!(run(&opts, konst).messages, [message]);
3526
3527 let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
3529 assert_eq!(run(&opts, subscript).messages, [message]);
3530
3531 let address = "constexpr int c = 3;\nint *p = &c;\n";
3533 let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
3534 pointer target type [E0514]";
3535 assert_eq!(run(&opts, address).messages, [warning]);
3536 }
3537
3538 #[test]
3547 fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
3548 let mut opts = options();
3551 opts.std = Std::C17;
3552 let source = concat!(
3553 "int add(a, b)\n",
3554 "int a;\n",
3555 "int b;\n",
3556 "{ return a + b; }\n",
3557 "int promoted(c)\n",
3558 "char c;\n",
3559 "{ return c; }\n",
3560 "int narrow(char);\n",
3561 "int narrow(c)\n",
3562 "char c;\n",
3563 "{ return c; }\n",
3564 "int first(a)\n",
3565 "int a[4];\n",
3566 "{ return a[0]; }\n",
3567 );
3568 let result = run(&opts, source);
3569 assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
3570 let text = result.text();
3571 assert!(text.contains("add : int(int, int) function external defined"), "{text}");
3572 assert!(text.contains("promoted : int(int) function external defined"), "{text}");
3573 assert!(text.contains("c : char object automatic defined"), "{text}");
3575 assert!(text.contains("narrow : int(char) function external defined"), "{text}");
3576 assert!(text.contains("first : int(int *) function external defined"), "{text}");
3578 }
3579
3580 #[test]
3587 fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
3588 let mut opts = options();
3589 opts.std = Std::C17;
3590 for (source, message) in [
3591 ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
3592 (
3593 "int f(a)\nint a;\nint b;\n{ return a; }\n",
3594 "3:5: error: declaration for parameter 'b' but no such parameter",
3595 ),
3596 ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
3597 ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
3598 (
3599 "int f(a)\nstatic int a;\n{ return a; }\n",
3600 "2:12: error: storage class specified for parameter 'a'",
3601 ),
3602 (
3603 "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
3604 "2:7: error: argument 'a' doesn't match prototype",
3605 ),
3606 ] {
3607 let result = run(&opts, source);
3608 assert!(result.failed(), "expected this to fail:\n{source}");
3609 assert!(result.messages[0].contains(message), "{:?}", result.messages);
3610 }
3611
3612 let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
3615 let mut older = options();
3616 older.std = Std::C89;
3617 assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
3618 let result = run(&opts, implicit);
3619 assert!(
3620 result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
3621 "{:?}",
3622 result.messages
3623 );
3624
3625 let mut newer = options();
3629 newer.std = Std::C23;
3630 let plain = "int f(a)\nint a;\n{ return a; }\n";
3631 let result = run(&newer, plain);
3632 assert!(!result.failed(), "{:?}", result.messages);
3633 assert_eq!(
3634 result.messages,
3635 ["/main.c:1:5: warning: old-style function definition [E0412]"]
3636 );
3637 assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
3638 }
3639
3640 #[test]
3647 fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
3648 let text = ir(concat!(
3649 "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
3650 "struct brim { char buf[9223372036854775807L]; };\n",
3651 "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
3652 "unsigned long h = sizeof(struct huge_struct);\n",
3653 "unsigned long b = sizeof(struct brim);\n",
3654 "unsigned long y = sizeof(struct bitty);\n",
3655 ));
3656 assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
3657 assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
3658 assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
3659
3660 let mut opts = options();
3661 opts.emit = EmitKind::Ir;
3662 let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
3663 let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
3664 assert_eq!(run(&opts, over).messages, [message]);
3665 let array = "struct wide { short buf[1L << 62]; };\n";
3666 let message = "/main.c:1:25: error: size of array 'buf' exceeds \
3667 maximum object size '9223372036854775807' [E0537]";
3668 assert_eq!(run(&opts, array).messages[0], message);
3669 }
3670
3671 fn compile_bytes(source: &[u8]) -> Compiled {
3676 let mut opts = options();
3677 opts.emit = EmitKind::Ir;
3678 let mut fs = MemoryFileSystem::new();
3679 fs.insert("/main.c", source.to_vec());
3680 compile(&opts, "/main.c", &fs)
3681 }
3682
3683 #[test]
3690 fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
3691 let mut source = b"char s[] = \"a".to_vec();
3692 source.push(0xff);
3693 source.extend_from_slice(b"b\";\nchar c = '");
3694 source.push(0xff);
3695 source.extend_from_slice(b"';\n");
3696 let result = compile_bytes(&source);
3697 assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
3698 assert!(result.text().contains(r#"bytes "a\ffb\00""#), "{}", result.text());
3699 assert!(result.text().contains("global @c : i8 = -1,"), "{}", result.text());
3701
3702 let mut stray = b"int a".to_vec();
3703 stray.push(0xff);
3704 stray.extend_from_slice(b" = 1;\n");
3705 let result = compile_bytes(&stray);
3706 assert!(
3707 result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
3708 "{:?}",
3709 result.messages
3710 );
3711 }
3712
3713 #[test]
3714 fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
3715 let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
3716 assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
3717 let expected = "\
3718func @add(i32, i32) -> i32, linkage(external) {
3719block0(%0: i32, %1: i32):
3720 %2 = add.nsw %0, %1
3721 return %2
3722}
3723";
3724 assert!(text.contains(expected), "{text}");
3725 }
3726
3727 #[test]
3728 fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
3729 let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
3730 assert!(!text.contains("alloca"), "{text}");
3731 assert!(!text.contains("load"), "{text}");
3732 assert!(!text.contains("store"), "{text}");
3733 }
3734
3735 #[test]
3736 fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
3737 let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
3738 let expected = "\
3739block0:
3740 %0 = alloca, size 4, align 4
3741 %1 = iconst.i32 1
3742 store %1 -> %0, align 4
3743 %2 = call @g(%0) : (ptr) -> i32
3744 return %2
3745";
3746 assert_eq!(text, expected);
3747 }
3748
3749 #[test]
3750 fn a_loop_carries_what_it_changes_as_block_parameters() {
3751 let text = body(
3754 "int f(int n) {\n int total = 0;\n for (int i = 0; i < n; i++) total += i;\n \
3755 return total;\n}\n",
3756 );
3757 assert!(!text.contains("alloca"), "{text}");
3758 assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
3759 assert!(text.contains("jump block1("), "{text}");
3760 }
3761
3762 #[test]
3763 fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
3764 let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
3765 assert!(text.contains("icmp slt %0, %1"), "{text}");
3766 assert!(!text.contains("zext"), "{text}");
3767 }
3768
3769 #[test]
3770 fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
3771 let text = body("int f(int a, int b) { return a && b; }\n");
3772 let expected = "\
3773block0(%0: i32, %1: i32):
3774 %2 = iconst.i32 0
3775 %3 = icmp ne %0, %2
3776 %4 = iconst.i1 0
3777 br_if %3, block1, block2(%4)
3778
3779block1:
3780 %5 = iconst.i32 0
3781 %6 = icmp ne %1, %5
3782 jump block2(%6)
3783
3784block2(%7: i1):
3785 %8 = zext.i32 %7
3786 return %8
3787";
3788 assert_eq!(text, expected);
3789 }
3790
3791 #[test]
3792 fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
3793 let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
3794 assert!(!text.contains("block3"), "{text}");
3797 assert!(!text.contains("iconst.i32 3"), "{text}");
3798 }
3799
3800 #[test]
3801 fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
3802 assert!(body("int main(void) { }\n").contains("iconst.i32 0\n return"));
3803 assert_eq!(body("void f(void) { }\n"), "block0:\n return\n");
3804 assert!(body("int f(void) { }\n").contains("unreachable"));
3805 }
3806
3807 #[test]
3808 fn a_structure_is_copied_rather_than_held_in_a_value() {
3809 let text = body(
3810 "struct point { int x, y; };\n\
3811 int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
3812 );
3813 assert!(text.contains("memcpy"), "{text}");
3814 }
3815
3816 #[test]
3817 fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
3818 let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
3819 assert!(text.contains("memset"), "{text}");
3820 }
3821
3822 #[test]
3823 fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
3824 let text = body(
3825 "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
3826 default: r = 4; } return r; }\n",
3827 );
3828 let expected = "\
3829block0(%0: i32):
3830 %1 = iconst.i32 0
3831 switch %0, block1, [1 => block2, 2 => block3(%1)]
3832
3833block1:
3834 %2 = iconst.i32 4
3835 jump block4(%2)
3836
3837block2:
3838 %3 = iconst.i32 1
3839 jump block3(%3)
3840
3841block3(%4: i32):
3842 %5 = iconst.i32 2
3843 %6 = add.nsw %4, %5
3844 jump block4(%6)
3845
3846block4(%7: i32):
3847 return %7
3848";
3849 assert_eq!(text, expected);
3850 }
3851
3852 #[test]
3853 fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
3854 let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
3857 assert!(text.contains("%2 = sub %0, %1"), "{text}");
3858 assert!(text.contains("icmp ule"), "{text}");
3859 assert!(!text.contains("switch"), "{text}");
3860 }
3861
3862 #[test]
3863 fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
3864 let text = body(
3865 "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
3866 case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
3867 );
3868 assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
3871 assert!(text.contains("block5:\n jump block7("), "{text}");
3872 assert!(text.contains("block6:\n jump block8("), "{text}");
3873 }
3874
3875 #[test]
3876 fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
3877 assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n return\n");
3878 }
3879
3880 #[test]
3881 fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
3882 let text = body(
3887 "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
3888 return n; }\n",
3889 );
3890 assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
3893 assert!(text.contains("block3(%3: i32):\n %4 = iconst.i32 1"), "{text}");
3894 assert!(text.contains("block4:\n jump block3("), "{text}");
3895 }
3896
3897 #[test]
3898 fn a_goto_into_a_loop_body_enters_it_without_the_test() {
3899 let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
3902 assert!(text.starts_with("block0(%0: i32, %1: i32):\n jump block1(%1)"), "{text}");
3903 assert!(text.contains("block1(%2: i32):\n %3 = iconst.i32 1"), "{text}");
3904 assert!(text.contains("br_if %6, block2, block3"), "{text}");
3905 }
3906
3907 #[test]
3908 fn a_goto_is_a_jump_to_the_block_the_label_starts() {
3909 let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
3910 assert!(!text.contains("alloca"), "{text}");
3914 assert!(text.contains("block2(%4: i32):\n return %4"), "{text}");
3915 assert_eq!(text.matches("jump block2(").count(), 2, "{text}");
3916 }
3917
3918 #[test]
3919 fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
3920 let text =
3921 body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
3922 assert!(!text.contains("alloca"), "{text}");
3923 assert!(text.contains("block1(%2: i32):"), "{text}");
3924 assert!(text.contains("jump block1(%5)"), "{text}");
3925 }
3926
3927 #[test]
3928 fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
3929 assert_eq!(
3932 body("int f(int x) { return x; spare: return 0; }\n"),
3933 "block0(%0: i32):\n return %0\n"
3934 );
3935 }
3936
3937 #[test]
3938 fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
3939 let text = body(
3940 "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
3941 );
3942 assert_eq!(
3945 text,
3946 "\
3947block0(%0: ptr):
3948 %1 = load.i8 %0, align 1
3949 %2 = iconst.i8 3
3950 %3 = ashr %1, %2
3951 %4 = sext.i32 %3
3952 return %4
3953"
3954 );
3955 }
3956
3957 #[test]
3958 fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
3959 let text =
3963 body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
3964 assert_eq!(
3965 text,
3966 "\
3967block0(%0: ptr, %1: i32):
3968 %2 = iconst.i32 16777215
3969 %3 = and %1, %2
3970 %4 = trunc.i16 %3
3971 store %4 -> %0, align 2
3972 %5 = iconst.i32 16
3973 %6 = lshr %3, %5
3974 %7 = trunc.i8 %6
3975 %8 = iconst.i64 2
3976 %9 = ptr_add %0, %8
3977 store %7 -> %9, align 1
3978 return
3979"
3980 );
3981 }
3982
3983 #[test]
3984 fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
3985 let text =
3986 body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
3987 assert!(text.contains("%3 = iconst.i8 31\n %4 = and %2, %3"), "{text}");
3990 assert!(text.ends_with("%9 = zext.i32 %4\n return %9\n"), "{text}");
3991 }
3992
3993 #[test]
3994 fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
3995 let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
3998 assert_eq!(text.matches("ashr").count(), 0, "{text}");
3999 assert!(text.ends_with("store %8 -> %0, align 1\n return\n"), "{text}");
4000 }
4001
4002 #[test]
4003 fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
4004 let text = body(
4008 "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
4009 );
4010 assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
4011 }
4012
4013 #[test]
4014 fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
4015 let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
4018 assert!(
4019 text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
4020 "{text}"
4021 );
4022 }
4023
4024 #[test]
4025 fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
4026 let text = ir(concat!(
4031 "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
4032 "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
4033 "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
4034 "char s[2] = \"hi\";\n",
4035 ));
4036 assert!(
4037 text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
4038 "{text}"
4039 );
4040 assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
4041 assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
4042 assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
4045 }
4046
4047 #[test]
4048 fn a_definition_takes_a_parameter_it_left_unnamed() {
4049 let text = ir("int f(int a, int) { return a; }\n");
4053 assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
4054 assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
4055
4056 let text = ir("int g(int, int n) { return n; }\n");
4059 assert!(text.contains("block0(%0: i32, %1: i32):\n return %1\n"), "{text}");
4060 }
4061
4062 #[test]
4063 fn an_assignment_of_a_structure_is_the_object_it_wrote() {
4064 let text = body(concat!(
4069 "struct s { int f; int g; };\n",
4070 "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
4071 "{ *d = *e = a[0] = *c; }\n",
4072 ));
4073 assert_eq!(text.matches("memcpy").count(), 3, "{text}");
4074 assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
4075 assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
4076 assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
4077 }
4078
4079 #[test]
4080 fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
4081 let mut opts = options();
4086 opts.emit = EmitKind::Ir;
4087 let result = run(
4088 &opts,
4089 concat!(
4090 "const char a[2][3] = { \"1234\", \"xyz\" };\n",
4091 "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
4092 "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
4093 "const union u c = { { \"1234\", \"567\" } };\n",
4094 ),
4095 );
4096 let text = result.text();
4097 assert_eq!(
4098 result.messages,
4099 ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
4100 (5 chars into 3 available) [E0637]"]
4101 );
4102 assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
4103 assert!(
4104 text.contains(
4105 "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
4106 bytes \"9\\00\", zero 3 }"
4107 ),
4108 "{text}"
4109 );
4110 assert!(
4113 text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
4114 "{text}"
4115 );
4116 }
4117
4118 #[test]
4119 fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
4120 let text = body(concat!(
4124 "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
4125 "void g(struct v *);\n",
4126 "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
4127 ));
4128 assert_eq!(text.matches("memcpy").count(), 1, "{text}");
4129 }
4130
4131 #[test]
4132 fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
4133 let text = ir(concat!(
4138 "struct s { int x; };\n",
4139 "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
4140 "int n = (int){ 7 };\n",
4141 "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
4142 ));
4143 assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
4144 assert!(text.contains("global @n : i32 = 7,"), "{text}");
4145 assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
4148 }
4149
4150 #[test]
4151 fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
4152 let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
4156 assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
4157 assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
4158 }
4159
4160 #[test]
4161 fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
4162 let text = ir("unsigned char foo[1][0];\n");
4166 assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
4167 }
4168
4169 #[test]
4170 fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
4171 let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
4174 assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
4175 assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
4176 }
4177
4178 #[test]
4179 fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
4180 let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
4184 assert!(
4185 text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
4186 "{text}"
4187 );
4188 }
4189
4190 #[test]
4191 fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
4192 let text = body(
4197 "\
4198struct s { int a, b; };
4199struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
4200",
4201 );
4202 assert!(text.contains("block3(%7: ptr)"), "{text}");
4204 assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
4205 assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
4206 }
4207
4208 #[test]
4209 fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
4210 let text = ir("\
4214struct pair { int a, b; };
4215struct pair make(int a, int b);
4216struct pair twice(struct pair p) { return make(p.a, p.b); }
4217");
4218 assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
4219 assert!(text.contains("func @twice(i64) -> i64"), "{text}");
4220 }
4221
4222 #[test]
4223 fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
4224 let text = ir("\
4228struct big { double v[8]; };
4229struct big grow(struct big b);
4230struct big twice(struct big b) { return grow(grow(b)); }
4231");
4232 assert!(
4233 text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
4234 "{text}"
4235 );
4236 assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
4237 assert_eq!(text.matches("call @grow").count(), 2, "{text}");
4240 }
4241
4242 #[test]
4243 fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
4244 let text = ir("\
4249struct big { double v[8]; };
4250struct pair { int a, b; };
4251int p(const char *, ...);
4252int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
4253");
4254 assert!(
4255 text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
4256 "{text}"
4257 );
4258 }
4259
4260 #[test]
4261 fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
4262 let body = body(
4265 "\
4266struct pair { int a, b; };
4267struct pair make(int a, int b);
4268int second(void) { return make(1, 2).b; }
4269",
4270 );
4271 assert!(body.starts_with("block0:\n %0 = alloca, size 8, align 4\n"), "{body}");
4272 assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
4273 }
4274
4275 #[test]
4276 fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
4277 let source = "\
4281struct hfa { float x, y, z; };
4282int take(struct hfa h);
4283int give(struct hfa h) { return take(h); }
4284";
4285 assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
4286 let mut opts = options();
4287 opts.emit = EmitKind::Ir;
4288 opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
4289 let result = run(&opts, source);
4290 assert_eq!(result.messages, Vec::<String>::new());
4291 assert!(result.text().contains("func @take(f32, f32, f32) -> i32"), "{}", result.text());
4292 }
4293
4294 #[test]
4295 fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
4296 let source = "\
4299int use(int *);
4300void f(int n) {
4301 {
4302 int a[n];
4303 use(a);
4304 }
4305 use(0);
4306}
4307";
4308 let body = body(source);
4309 assert!(body.contains("mul.nsw"), "{body}");
4310 assert!(body.contains("stacksave"), "{body}");
4311 assert!(body.contains("alloca %"), "{body}");
4312 assert!(body.contains("stackrestore"), "{body}");
4313 }
4314
4315 #[test]
4316 fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
4317 let source = "\
4322int use(int *);
4323int f(int n) {
4324 {
4325 int a[n];
4326 if (use(a)) goto out;
4327 use(0);
4328 }
4329out:
4330 return 0;
4331}
4332";
4333 let body = body(source);
4334 assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
4336 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
4337 assert!(after.starts_with(" %4\n jump block"), "{body}");
4338 }
4339
4340 #[test]
4341 fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
4342 let source = "\
4346int use(int *);
4347int f(int n) {
4348 int a[n];
4349again:
4350 if (use(a)) goto again;
4351 return 0;
4352}
4353";
4354 let body = body(source);
4355 assert!(body.contains("stacksave"), "{body}");
4356 assert!(!body.contains("stackrestore"), "{body}");
4357 }
4358
4359 #[test]
4360 fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
4361 let source = "\
4366int use(int *);
4367int f(int n) {
4368again:
4369 {
4370 int a[n];
4371 if (use(a)) goto again;
4372 }
4373 return 0;
4374}
4375";
4376 let body = body(source);
4377 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
4378 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
4379 assert!(after.starts_with(" %4\n jump block1\n"), "{body}");
4380 }
4381
4382 #[test]
4383 fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
4384 let source = "\
4390int f(void);
4391void t(void) {
4392 int count = 10;
4393 for (; count--;) {
4394 int b[f()];
4395 int i;
4396 for (i = 0; i < f(); i++) {
4397 b[i] = count;
4398 }
4399 }
4400}
4401";
4402 let body = body(source);
4403 assert_eq!(body.matches("stacksave").count(), 1, "{body}");
4407 let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
4408 let next = after.split("\n\n").next().expect("the block the restore is in");
4411 assert!(next.contains("jump block1("), "{body}");
4412 }
4413
4414 #[test]
4415 fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
4416 let source = "\
4419unsigned long f(int n) {
4420 int a[n];
4421 n = 0;
4422 return sizeof a;
4423}
4424";
4425 let body = body(source);
4426 assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
4428 }
4429
4430 #[test]
4431 fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
4432 let source = "\
4435int use(int);
4436int f(int x) {
4437 return ({
4438 int t = use(x);
4439 t * t;
4440 });
4441}
4442";
4443 let expected = "\
4444block0(%0: i32):
4445 %1 = call @use(%0) : (i32) -> i32
4446 %2 = mul.nsw %1, %1
4447 return %2
4448";
4449 assert_eq!(body(source), expected);
4450 }
4451
4452 #[test]
4453 fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
4454 let source = "int f(int x) { return ({ return x; 0; }); }\n";
4458 assert_eq!(body(source), "block0(%0: i32):\n return %0\n");
4459 }
4460
4461 #[test]
4462 fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
4463 let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
4467 let expected = "\
4468block0(%0: ptr):
4469 %1 = va_arg.f64 %0
4470 %2 = va_arg.f64 %0
4471 %3 = fadd %1, %2
4472 return %3
4473";
4474 assert_eq!(body(source), expected);
4475 }
4476
4477 #[test]
4478 fn one_that_reads_a_structure_answers_where_the_object_is() {
4479 let source = "\
4493struct s { int a; long b; };
4494long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
4495";
4496 let expected = "\
4497block0(%0: ptr):
4498 %1 = alloca, size 16, align 16
4499 %2 = va_object %0, size 16, align 8, in(int 8 at 0, int 8 at 8)
4500 memcpy %1, %2, size 16, align 8
4501 %3 = iconst.i64 8
4502 %4 = ptr_add %1, %3
4503 %5 = load.i64 %4, align 8
4504 return %5
4505";
4506 assert_eq!(body(source), expected);
4507 }
4508
4509 #[test]
4513 fn the_classification_says_which_registers_the_object_arrived_in() {
4514 let source = "\
4515struct s { double a; double b; };
4516double f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a; }
4517";
4518 assert!(
4519 body(source)
4520 .contains("va_object %0, size 16, align 8, in(float f64 at 0, float f64 at 8)"),
4521 "{}",
4522 body(source)
4523 );
4524
4525 let big = "\
4526struct s { long a[4]; };
4527long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.a[0]; }
4528";
4529 assert!(body(big).contains("va_object %0, size 32, align 8\n"), "{}", body(big));
4530 }
4531
4532 #[test]
4533 fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
4534 let source = "\
4538int f(int c) {
4539 void *p = c ? &&one : &&two;
4540 goto *p;
4541one:
4542 return 1;
4543two:
4544 return 2;
4545}
4546";
4547 let expected = "\
4548block0(%0: i32):
4549 %1 = iconst.i32 0
4550 %2 = icmp ne %0, %1
4551 br_if %2, block1, block2
4552
4553block1:
4554 %3 = block_addr block3
4555 jump block4(%3)
4556
4557block2:
4558 %4 = block_addr block5
4559 jump block4(%4)
4560
4561block3:
4562 %5 = iconst.i32 1
4563 return %5
4564
4565block4(%6: ptr):
4566 indirect_br %6, block3, block5
4567
4568block5:
4569 %7 = iconst.i32 2
4570 return %7
4571";
4572 assert_eq!(body(source), expected);
4573 }
4574
4575 #[test]
4576 fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
4577 let source = "void **next(void);
4580void f(void) { goto *next(); }
4581";
4582 let expected = "\
4583block0:
4584 %0 = call @next() : () -> ptr
4585 unreachable
4586";
4587 assert_eq!(body(source), expected);
4588 }
4589
4590 #[test]
4591 fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
4592 let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
4595 let expected = "\
4596block0:
4597 inline_asm.volatile \"mfence\", \"\", \"memory\"()
4598 return
4599";
4600 assert_eq!(body(source), expected);
4601 }
4602
4603 #[test]
4604 fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
4605 let source = "\
4608int f(int x, int y) {
4609 int r;
4610 __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
4611 return r + y;
4612}
4613";
4614 let expected = "\
4615block0(%0: i32, %1: i32):
4616 %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
4617 %4 = add.nsw %2, %3
4618 return %4
4619";
4620 assert_eq!(body(source), expected);
4621 }
4622
4623 #[test]
4624 fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
4625 let source = "\
4630struct pair { int a, b; };
4631int f(int x) {
4632 int slot = x;
4633 struct pair p = { x, x };
4634 __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
4635 return slot + p.a;
4636}
4637";
4638 let text = body(source);
4639 assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
4640 assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
4641 assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
4642 }
4643
4644 #[test]
4645 fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
4646 let source = "\
4651int f(int x) {
4652 int r = 7;
4653 __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
4654 return r;
4655away:
4656 return r;
4657}
4658";
4659 let expected = "\
4660block0(%0: i32):
4661 %1 = iconst.i32 7
4662 %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
4663
4664block1:
4665 return %2
4666
4667block2:
4668 return %1
4669";
4670 assert_eq!(body(source), expected);
4671 }
4672
4673 #[test]
4674 fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
4675 let mut opts = options();
4679 opts.emit = EmitKind::Ir;
4680 for (source, expected) in [
4681 (
4682 "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
4683 "output operand constraint lacks '='",
4684 ),
4685 (
4686 "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
4687 "lvalue required in 'asm' statement",
4688 ),
4689 (
4690 "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
4691 "read-only variable 'g' used as 'asm' output",
4692 ),
4693 (
4694 "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
4695 "input operand constraint contains '='",
4696 ),
4697 (
4698 "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
4699 "memory input 0 is not directly addressable",
4700 ),
4701 ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
4702 (
4703 "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
4704 "duplicate asm operand name 'a'",
4705 ),
4706 ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
4707 ] {
4708 let result = run(&opts, source);
4709 assert!(result.failed(), "expected this to be reported:\n{source}");
4710 assert!(
4711 result.messages.iter().any(|m| m.contains(expected)),
4712 "{expected}\n{:?}",
4713 result.messages
4714 );
4715 }
4716 }
4717
4718 #[test]
4719 fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
4720 let mut opts = options();
4721 opts.emit = EmitKind::Ir;
4722 for source in [
4723 "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
4724 "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
4725 ] {
4726 let result = run(&opts, source);
4727 assert!(result.failed(), "expected this to be reported:\n{source}");
4728 assert!(
4729 result.messages.iter().any(|m| m.contains("not supported yet")),
4730 "{:?}",
4731 result.messages
4732 );
4733 }
4734 }
4735
4736 fn round_trip(source: &str) -> (String, String) {
4738 let printed = ir(source);
4739 let mut opts = options();
4740 opts.emit = EmitKind::Ir;
4741 let mut fs = MemoryFileSystem::new();
4742 fs.insert("/main.ir", printed.clone().into_bytes());
4743 let result = compile_ir(&opts, "/main.ir", &fs);
4744 assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
4745 (printed, result.text().to_owned())
4746 }
4747
4748 #[test]
4749 fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
4750 let (printed, again) = round_trip(
4754 "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",
4755 );
4756 assert_eq!(printed, again);
4757 }
4758
4759 #[test]
4760 fn ir_that_is_not_ir_says_which_line_stopped_it() {
4761 let mut opts = options();
4762 opts.emit = EmitKind::Ir;
4763 let mut fs = MemoryFileSystem::new();
4764 let text = "\
4765; ModuleID = 'a.c'
4766; format 0
4767target triple = \"x86_64-unknown-linux-gnu\"
4768target datalayout = \"e-p:64:64-i64:64-S128\"
4769
4770func @f(), linkage(external) {
4771block0:
4772 frobnicate
4773}
4774";
4775 fs.insert("/main.ir", text.as_bytes().to_vec());
4776 let result = compile_ir(&opts, "/main.ir", &fs);
4777 assert!(result.failed());
4778 assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
4779 }
4780
4781 #[test]
4782 fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
4783 let mut opts = options();
4786 opts.emit = EmitKind::Ir;
4787 let mut fs = MemoryFileSystem::new();
4788 let text = "\
4789; ModuleID = 'a.c'
4790; format 0
4791target triple = \"x86_64-unknown-linux-gnu\"
4792target datalayout = \"e-p:64:64-i64:64-S128\"
4793
4794func @f(), linkage(external) {
4795block0:
4796 %0 = iconst.i32 1
4797 return %0
4798}
4799";
4800 fs.insert("/main.ir", text.as_bytes().to_vec());
4801 let result = compile_ir(&opts, "/main.ir", &fs);
4802 assert!(result.failed());
4803 assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
4804 }
4805
4806 #[test]
4807 fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
4808 let mut fs = MemoryFileSystem::new();
4810 fs.insert("/main.ir", Vec::new());
4811 let result = compile_ir(&options(), "/main.ir", &fs);
4812 assert!(result.failed());
4813 assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
4814 }
4815
4816 #[test]
4817 fn the_printed_ir_reads_back_as_the_same_module() {
4818 let text = ir("\
4821struct point { int x, y; };
4822static const char greeting[] = \"hi\";
4823int table[4] = { 1, 2, 3 };
4824int puts(const char *);
4825double half(double x) { return x / 2.0; }
4826int f(int n) {
4827 int total = 0;
4828 for (int i = 0; i < n; i++) {
4829 if (i == 3) continue;
4830 total += table[i];
4831 }
4832 switch (n) {
4833 case 0: total = 1;
4834 case 1: total++; break;
4835 default: total = -total;
4836 }
4837 struct point p = { total, 1 };
4838 int *q = &p.y;
4839 puts(greeting);
4840 return p.x + *q;
4841}
4842int dispatch(int c) {
4843 void *p = c ? &&one : &&two;
4844 goto *p;
4845one:
4846 return 1;
4847two:
4848 return 2;
4849}
4850int assembly(int x, int *p) {
4851 int r;
4852 __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
4853 __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
4854 return r;
4855away:
4856 return 0;
4857}
4858");
4859 let mut names = Interner::new();
4860 let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
4861 assert_eq!(rucc_ir::print(&module, &names), text);
4862 }
4863}